method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
1c1b8fcf-dd92-4071-93a1-32212a64d50d | 2 | public void obtenirFormes() {
final String serverAddress[] = JOptionPane.showInputDialog("Quel est le nom d'h�te et le port du serveur de formes?").split(":");
final Socket srvCnx;
final PrintWriter srvOutput;
final BufferedReader srvInput;
final String hostName = serverAddress[0];
final int portNumber = Integer.parseInt(serverAddress[1]);
/*
* CODE EMPRUNTÉ:
* Les lignes suivantes sont basées sur les exemples de la classe
* Socket de la document de l'API de Java
* http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html
* (consulté le 27 septembre 2014)
* J'ai repris la structure de base et j'ai modifié le type de certains flux.
*/
try {
// Ouverture de la connexion au serveur
srvCnx = new Socket(hostName, portNumber);
srvOutput = new PrintWriter(srvCnx.getOutputStream(), true);
srvInput = new BufferedReader(
new InputStreamReader(srvCnx.getInputStream())
);
// Récupère 10 formes et les enregistre dans le GestionnaireForme de l'application
for (int i = 1; i <= 10; i++) {
srvOutput.println("GET");
srvInput.readLine();
GestionnaireForme.getInstance().ajouterForme(srvInput.readLine());
}
// Fermeture de la connexion au serveur
srvOutput.println("END");
srvCnx.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
} |
3d61a78e-4915-49d5-87ef-76a1076f04ea | 4 | final public CycObject existExactForm(boolean requireEOF) throws ParseException, java.io.IOException, UnsupportedVocabularyException {
CycVariable var = null;
CycObject sent = null;
CycList val = new CycList();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case THEREEXISTEXACTLY_CONSTANT:
jj_consume_token(THEREEXISTEXACTLY_CONSTANT);
break;
case THEREEXISTEXACTLY_GUID_CONSTANT:
jj_consume_token(THEREEXISTEXACTLY_GUID_CONSTANT);
break;
default:
jj_la1[12] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
val.add(getCycAccess().thereExistExactlyConst);
var = variable(false);
val.add(var);
sent = sentence(false);
val.add(sent);
eof(requireEOF);
{if (true) return val;}
throw new Error("Missing return statement in function");
} |
64cfa774-1925-4ba6-9b69-83008a914c77 | 1 | public static StockStorage getInstance() {
if (theOne == null) {
theOne = new StockStorage();
}
return theOne;
} |
08a93eff-3645-4bd4-92a4-3e59bfbcff2c | 3 | private synchronized void checkGridletCompletion()
{
ResGridlet obj = null;
int i = 0;
// NOTE: This one should stay as it is since gridletFinish()
// will modify the content of this list if a Gridlet has finished.
// Can't use iterator since it will cause an exception
while ( i < gridletInExecList_.size() )
{
obj = (ResGridlet) gridletInExecList_.get(i);
if (obj.getRemainingGridletLength() == 0.0)
{
gridletInExecList_.remove(obj);
gridletFinish(obj, Gridlet.SUCCESS);
continue;
}
i++;
}
// if there are still Gridlets left in the execution
// then send this into itself for an hourly interrupt
// NOTE: Setting the internal event time too low will make the
// simulation more realistic, BUT will take longer time to
// run this simulation. Also, size of sim_trace will be HUGE!
if (gridletInExecList_.size() > 0) {
super.sendInternalEvent(60.0*60.0);
}
} |
d8fe2cf3-c064-48b4-9078-738f7964ec7d | 3 | public static void main(String[] args) throws SQLException {
ShowAllEmployeesOOP command = new ShowAllEmployeesOOP();
Collection<ShowAllEmployeesBasicInfo> allEmployeesBasicInformation = command
.getAllEmployeesBasicInformation();
if (allEmployeesBasicInformation == null
|| allEmployeesBasicInformation.isEmpty()) {
System.out
.println("Unfortunatelly employee information is unavailable");
return;
}
for (ShowAllEmployeesBasicInfo employeeInfo : allEmployeesBasicInformation) {
System.out.println(employeeInfo);
}
} |
89ee13ee-3953-4203-9224-b698d0179cb4 | 2 | public static String getFilenameExtension(String path) {
if (path == null) {
return null;
}
int sepIndex = path.lastIndexOf(EXTENSION_SEPARATOR);
return (sepIndex != -1 ? path.substring(sepIndex + 1) : null);
} |
4142391b-e473-40fc-9ff1-68b389643f12 | 5 | public SampleResult runTest(JavaSamplerContext context) {
SampleResult sampleResult = new SampleResult();
sampleResult.sampleStart();
String key = String.valueOf(String.valueOf(new Random().nextInt(keyNumLength)).hashCode());
try {
if (methedType.equals("put")) {
put = new Put(Bytes.toBytes(key));
put.setWriteToWAL(writeToWAL);
for (int j = 0; j < cfs.length; j++) {
for (int n = 0; n < qualifiers.length; n++) {
put.add(Bytes.toBytes(cfs[j]),
Bytes.toBytes(qualifiers[n]),
Bytes.toBytes(values));
table.put(put);
}
}
} else if (methedType.equals("get")) {
get = new Get((key ).getBytes());
Result rs = table.get(get);
}
sampleResult.setSuccessful(true);
} catch (Throwable e) {
sampleResult.setSuccessful(false);
} finally {
sampleResult.sampleEnd();
}
// // 返回是否处理成功
return sampleResult;
} |
1a80045a-135f-4fde-9145-44a41a5d58f3 | 1 | public Sprite create(Owner owner, Resource res, Message sdt) {
GaussianPlant spr = new GaussianPlant(owner, res);
spr.addnegative();
Random rnd = owner.mkrandoom();
for(int i = 0; i < num; i++) {
Coord c = neg.bc.add(rnd.nextInt(neg.bs.x), rnd.nextInt(neg.bs.y));
Tex s = strands[rnd.nextInt(strands.length)];
spr.add(s, 0, MapView.m2s(c), new Coord(s.sz().x / 2, s.sz().y).inv());
}
return(spr);
} |
f978b686-b94d-407c-aa17-5f5ff1c6f004 | 8 | public static void main(String[] args)
{
URL url = null; // create url Object
InputStream is = null;
HttpURLConnection connection = null;
try
{
url = new URL("http://www.bankisrael.gov.il/currency.xml");
is = url.openConnection().getInputStream(); // connection.getInputStream(); // Receive reference to the connection input stream
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // create an instance of the Document factory
DocumentBuilder builder = factory.newDocumentBuilder(); // create with the factory new Doc Builder
Document doc = builder.parse(is);
NodeList lastModifiedList = doc.getElementsByTagName("LAST_UPDATE"); // get the last_update
System.out.println("Last Updated value = " + lastModifiedList.item(0).getTextContent());
NodeList allCurrenciesList = doc.getElementsByTagName("CURRENCY"); // create node list of all the currency
for (int i=0; i < allCurrenciesList.getLength(); i++)
{
NodeList singleCurrency = allCurrenciesList.item(i).getChildNodes();
System.out.println("Current currency details:");
System.out.println(singleCurrency.item(1).getTextContent());
System.out.println(singleCurrency.item(3).getTextContent());
System.out.println(singleCurrency.item(5).getTextContent());
System.out.println(singleCurrency.item(7).getTextContent());
System.out.println(singleCurrency.item(9).getTextContent());
System.out.println(singleCurrency.item(11).getTextContent());
}
System.out.println("Which currency is missing???");
} catch (MalformedURLException e)
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (ProtocolException e)
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (ParserConfigurationException e)
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (SAXException e)
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e)
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
finally
{
if (is != null)
{
try
{
is.close();
} catch (IOException e)
{
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
} |
87f4bbf4-b8c6-4a5a-ac04-b547ecf8113f | 6 | private static void call(GameException exception) {
HandlerList handlers = exception.getHandlers();
RegisteredListener[] listeners = handlers.getRegisteredListeners();
for (RegisteredListener registration : listeners) {
if (!registration.getPlugin().isEnabled()) {
continue;
}
// Check if the exception belongs to the plugin which registered the listener
else if (!registration.getPlugin().equals(exception.getPlugin())) {
continue;
}
try {
registration.callEvent(exception);
} catch (AuthorNagException e) {
Plugin plugin = registration.getPlugin();
if (plugin.isNaggable()) {
plugin.setNaggable(false);
Bukkit.getLogger().log(Level.SEVERE, String.format("Nag author(s): '%s' of '%s' about the following: %s", new Object[] { plugin.getDescription().getAuthors(), plugin.getDescription().getFullName(), e.getMessage() }));
}
} catch (Exception e) {
Bukkit.getLogger().log(Level.SEVERE, "Could not pass exception " + exception.getEventName() + " to " + registration.getPlugin().getDescription().getFullName(), e);
}
}
} |
48cafc47-78f2-4a24-9ac2-e6dbaf374b0a | 9 | public final GalaxyXPreprocessorParser.assignment_operator_return assignment_operator() throws RecognitionException {
GalaxyXPreprocessorParser.assignment_operator_return retval = new GalaxyXPreprocessorParser.assignment_operator_return();
retval.start = input.LT(1);
int assignment_operator_StartIndex = input.index();
Object root_0 = null;
Token set102=null;
Object set102_tree=null;
try {
if ( state.backtracking>0 && alreadyParsedRule(input, 16) ) { return retval; }
// C:\\Users\\Timo\\EclipseProjects\\GalaxyX\\build\\classes\\com\\galaxyx\\parser\\GalaxyXPreprocessorParser.g:116:2: ( ASSGN | ASSGNP | ASSGNS | ASSGNT | ASSGND | ASSGNM | ASSGNSHL | ASSGNSHR | ASSGNBITAND | ASSGNBITOR | ASSGNBITXOR )
// C:\\Users\\Timo\\EclipseProjects\\GalaxyX\\build\\classes\\com\\galaxyx\\parser\\GalaxyXPreprocessorParser.g:
{
root_0 = (Object)adaptor.nil();
set102=(Token)input.LT(1);
if ( (input.LA(1)>=ASSGN && input.LA(1)<=ASSGNBITXOR) ) {
input.consume();
if ( state.backtracking==0 ) adaptor.addChild(root_0, (Object)adaptor.create(set102));
state.errorRecovery=false;state.failed=false;
}
else {
if (state.backtracking>0) {state.failed=true; return retval;}
MismatchedSetException mse = new MismatchedSetException(null,input);
throw mse;
}
}
retval.stop = input.LT(-1);
if ( state.backtracking==0 ) {
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
if ( state.backtracking>0 ) { memoize(input, 16, assignment_operator_StartIndex); }
}
return retval;
} |
4e4c7392-9a48-4e62-a7bb-37f783be8dff | 7 | public void move(int xa, int ya) {
System.out.println("Size: " + level.getProjectiles().size());
if (xa != 0 && ya !=0) {
move(xa, 0);
move(0, ya);
return;
}
//right
if (xa > 0) dir =1;
//left
if (xa < 0) dir =3;
//down
if (ya > 0) dir =2;
//up
if (ya < 0) dir =0;
if (!collision(xa, ya)) {
x += xa;
y += ya;
} else {
Particle p = new Particle(x, y, 50, 50);
level.add(p);
}
} |
316422b8-9080-4782-b0fc-7c3f2eefad6a | 4 | public void run() {
while(true){
System.out.println("input q to quit, input d to download");
String c = input.next();
c = c.toLowerCase();
switch(c){
case "d": download();break;
case "q": gracefulExit();break;
case "t": System.out.println("I like Scarves");break;
}
}
} |
b38378a7-d472-4fc0-83bd-20a073612001 | 3 | @Override
public void run()
{
try
{
while (!isInterrupted() && run)
{
final String message = getNextMessageFromQueue();
sendMessageToClient(message + "\n");
Log.d("ClientSender", "run()" + message);
}
}
catch (final Exception e)
{
// erreur silencieuse...
}
clientInfo.getClientReciever().interrupt();
} |
944012bc-ef0c-47de-bc03-9cdf5969c4c8 | 2 | public String loadGames(String profileId, String parameters) throws Exception {
String url = "http://steamcommunity.com/";
if (containsOnlyDigits(profileId))
url += "profiles/";
else
url += "id/";
url += profileId + "/" + parameters;
WebPage page = WebPage.loadWebPage(url, ENCODING);
String pageContent = page.getContent();
int lineIdx = pageContent.indexOf("var rgGames");
if (lineIdx <= -1) {
reaction.add("Invalid profile!");
return null;
}
int startIdx = pageContent.indexOf("[", lineIdx)+1;
int endIdx = pageContent.indexOf("];", startIdx);
String gamesString = pageContent.substring(startIdx, endIdx);
// chop first and last char
gamesString = gamesString.substring(1, gamesString.length()-1);
return gamesString;
} |
2e1a46c9-55b6-4ced-8001-d55193cc9ce2 | 2 | public void preOrder() {
// 1 Konten selber, 2 Linker Knoten , 3 Rechter Knoten
print();
if (left != null) {
left.preOrder();
}
if (right != null) {
right.preOrder();
}
} |
9d780dfb-80ec-4266-9a3e-c781c256c741 | 4 | private int convertToDirection(String s)
{
if(s.equals("w")) {return Location.NORTH;}
if(s.equals("a")) {return Location.WEST;}
if(s.equals("s")) {return Location.SOUTH;}
if(s.equals("d")) {return Location.EAST;}
return -1;
} |
cb6abcac-6a9b-4348-9f4a-ca2093122129 | 3 | @Override
public void actionPerformed(ActionEvent e) {
suljeEdellinenKortti();
if (e.getSource().equals(kertaus)){
ui.kertausmaatti();
}else if (e.getSource().equals(ajastus)){
ui.ajastinmaatti();
} else if (e.getSource().equals(tilastot)){
ui.tilastomaatti();
}
} |
6c9a9ecb-64cb-468e-b63c-1dfb4e3389e8 | 8 | public String value() {
String result = "";
// If a number card.
if (value >= 2 && value <= 10) {
result = Integer.toString(value);
}
// If a face card.
else if (value >= 11 && value <= 14) {
if (value == 11) {
result = "J";
} else if (value == 12) {
result = "Q";
} else if (value == 13) {
result = "K";
} else if (value == 14) {
result = "A";
} else {
result = "WTF";
}
}
return result;
} |
cc7ac099-4473-4ebf-a9a0-6d7805c1995e | 8 | protected void cleanup(JComponent c, boolean remove) {
if (!cleaned && remove && indices != null) {
source = (JList) c;
DefaultListModel model = (DefaultListModel) source.getModel();
//If we are moving items around in the same list, we
//need to adjust the indices accordingly, since those
//after the insertion point have moved.
if (addCount > 0) {
for (int i = 0; i < indices.length; i++) {
if (indices[i] > addIndex) {
indices[i] += addCount;
}
}
}
for (int i = indices.length - 1; i >= 0; i--) {
try {
model.remove(indices[i]);
} catch (ArrayIndexOutOfBoundsException ignored) {
}
}
}
indices = null;
addCount = 0;
addIndex = -1;
} |
f96ef6ea-9efb-4d60-986d-9b951278836e | 4 | public boolean conflicts(String name, int usageType) {
if (usageType == AMBIGUOUSNAME || usageType == LOCALNAME)
return findLocal(name) != null;
if (usageType == AMBIGUOUSNAME || usageType == CLASSNAME)
return findAnonClass(name) != null;
return false;
} |
d8445fc6-bc31-48b2-8394-78557fc23f68 | 1 | protected static Element createElement(Document document, String tagname,
Map attributes, String text) {
// Create the new element.
Element element = document.createElement(tagname);
// Add the text element.
if (text != null)
element.appendChild(document.createTextNode(text));
return element;
} |
de7704c9-55da-4d9b-ad8f-5e2a8f872daf | 7 | public NXNode<?> resolvePath(String s) {
String[] e = (s.startsWith("/") ? s.substring(1) : s).split(Pattern.quote("/"));
NXNode<?> r = _baseNode;
for (String f : e) {
if (f.equals(".")) continue;
else if (f.equals("..")) r = _baseNode._parent;
else r = r.getChild(f);
if (r == null) return null;
}
return r;
} |
23785cd2-9636-4ef8-a03a-9d31dad62ddd | 4 | private void buildTree(JsonNode root, JsonNode parent){
if(root.isArray()){
for(JsonNode n : root){
buildTree(n, parent);
}
return;
}
if(root.isContainerNode()){
String name = getNodeName(root);
String parentName = getNodeName(parent);
JsonNode value = root.findValue(name);
treeInsert(parentName,name);
//System.out.println("Container: " + name + " begin");
buildTree(value, root);
//System.out.println("Container: " + name + " end");
return;
}
if(root.isValueNode()){
String parentName = getNodeName(parent);
String value = root.asText();
//System.out.println("Value: " + value + " (parent " + parentName + ")");
treeInsert(parentName, value);
return;
}
} |
5c2125cf-26d4-472d-8ae3-aad906b6e72a | 0 | private Set<Card> foursFullWithTwoJacksAndTwoKings() {
return convertToCardSet("KD,4S,4C,KS,JD,4H,JH");
} |
f98eb448-10fb-49a9-9ba4-abe2b20c15a7 | 5 | public void CreateAANakedTorsoAlternativeTexturesFemalesOld() throws Exception {
NumberFormat formatter = new DecimalFormat("000");
for (int bodies = 1; bodies < RBS_Main.amountBodyTypes; bodies++) {
String s_bodies = formatter.format(bodies);
for (ARMA sourceAA : SkyProcStarter.patch.getArmatures()) {
if (sourceAA.getEDID().equals("NakedTorsoRBS_F" + "standard" + s_bodies)) {
for (TXST t : SkyProcStarter.patch.getTextureSets()) {
if (t.getEDID().contains("RBS_F_TEXT")) {
String[] splitResult = t.getEDID().split("RBS_F_TEXT");
String bodyID = splitResult[1];
ARMA targetAA = (ARMA) SkyProcStarter.patch.makeCopy(sourceAA, sourceAA.getEDID() + "RBS_F_TEXT" + bodyID);
targetAA.setSkinTexture(t.getForm(), Gender.FEMALE);
// patch.addRecord(targetAA);
}
}
}
}
}
} |
fad6c7f4-2113-4d79-8925-4c12adfe43d2 | 1 | private void jTextFieldCmdCliQte8FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldCmdCliQte8FocusLost
mondecimal = new DecimalFormat("#######.00");
if (!(jTextFieldCmdCliQte8.getText().equals(""))) {
int qte = Integer.parseInt(jTextFieldCmdCliQte8.getText().trim());
Float totalht8 = (qte * (Float.valueOf(jTextFieldCmdCliPxHt8.getText().replace(",", "."))));
jTextFieldCmdCliLg8Totalht8.setText(mondecimal.format(totalht8).replace(",", "."));
Float totaltva8 = (totalht8 * Float.valueOf(jTextFieldCmdCliLg8Tva8.getText().replace(",", "."))) / 100;
jTextFieldCmdCliLg8TotalTva8.setText(mondecimal.format(totaltva8).replace(",", "."));
TOTALHT = TOTALHT + (totalht8);
TOTALTVA = TOTALTVA + (totaltva8);
TOTALTTC = TOTALTTC + (totalht8) + (totaltva8);
jTextFieldCommandeTotalHT.setText(mondecimal.format(TOTALHT).replace(",", "."));
jTextFieldComdClientTotalTva.setText(mondecimal.format(TOTALTVA).replace(",", "."));
//traitemnt pour affichage euro
BigDecimal TOTALGTTC = new BigDecimal(String.valueOf(TOTALTTC));
NumberFormat t1 = NumberFormat.getCurrencyInstance(Locale.FRANCE);
jTextFieldcmdClientTotalTtc.setText(t1.format(TOTALGTTC));
}
}//GEN-LAST:event_jTextFieldCmdCliQte8FocusLost |
c70cc998-1d98-494b-aa0a-92049d0aad75 | 5 | int alphaBetaMin(int alpha, int beta, int depthleft) {
if (depthleft == 0) {
return -eval(mPieces, oPieces);
}
for (Piece a : oPieces) {
Move[] possible = a.getMoves(board);
System.out.println("min, white : " + a.white + ", # nodes " + possible.length);
for (Move b : possible) {
b.make(board);
a.update(b.x2, b.y2);
score = alphaBetaMax(alpha, beta, depthleft - 1);
if (score <= alpha) {
return alpha; // fail hard alpha-cutoff
}
if (score < beta) {
beta = score; // beta acts like min in MiniMax
}
b.unmake(board);
a.update(b.x1, b.y1);
}
}
return beta;
} |
ca0b9faf-01f4-4634-b34d-7648996407d6 | 7 | public SegmentTreeMinCntSegAdd(int[] array){
int n = array.length, i;
for(d=1; d<n; d<<=1);
t = new int[d<<1];
add = new int[d<<1];
cntMin = new int[d<<1];
for(i=d; i<n+d; ++i){ t[i] = array[i-d]; cntMin[i] = 1; }
for(i=n+d; i<d+d; ++i){ t[i] = Integer.MAX_VALUE; cntMin[i] = 1; }
for(i=d-1; i>0; --i){
if(t[i*2]<t[i*2+1]){
t[i] = t[i*2];
cntMin[i] = cntMin[i*2] + (t[i*2]==t[i*2+1] ? cntMin[i*2+1] : 0);
}else{
t[i] = t[i*2+1];
cntMin[i] = cntMin[i*2+1] + (t[i*2]==t[i*2+1] ? cntMin[i*2] : 0);
}
}
} |
ac8a40ad-a84d-4a3b-bb75-43f62a542c64 | 9 | private static Term eval(Term term, HashMap<String, Term> env) throws ParseException {
if (Util.getOperators().contains(term.getPred())) {
Integer a = Integer.parseInt(eval(term.getArgs().get(0), env).getPred());
Integer b = Integer.parseInt(eval(term.getArgs().get(1), env).getPred());
if (term.getPred().equals("+")) {
return new Term(new Integer(a + b).toString(), null);
}
if (term.getPred().equals("-")) {
return new Term(new Integer(a - b).toString(), null);
}
if (term.getPred().equals("*")) {
return new Term(new Integer(a * b).toString(), null);
}
}
// TODO: How to set types for lt, eq, original uses booleans
if (isConstant(term)) {
return term;
}
if (isVariable(term)) {
Term ans = env.get(term.getPred());
if (ans == null) {
return null;
}
return eval(ans, env);
}
ArrayList<Term> args = new ArrayList<Term>();
for (Term arg : term.getArgs()) {
Term a = eval(arg, env);
if (a == null) {
return null;
}
args.add(a);
}
return new Term(term.getPred(), args);
} |
7666ec57-c491-4117-b816-a48f15763922 | 3 | @Override
public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException {
// 执行PreparedStatement
int rows = ps.executeUpdate();
// 根据是否存在KeyHolder判断是否需要从PreparedStatement中提取生成的主键
if (generatedKeyHolder != null) {
List<Map<String, Object>> generatedKeys = generatedKeyHolder.getKeyList();
generatedKeys.clear();
ResultSet keys = ps.getGeneratedKeys();
if (keys != null) {
try {
RowMapperResultSetExtractor<Map<String, Object>> rse = new RowMapperResultSetExtractor<Map<String, Object>>(
new ColumnMapRowMapper(), 1);
generatedKeys.addAll(rse.extractData(keys));
} finally {
JdbcUtils.closeResultSet(keys);
}
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("SQL更新操作更新了[" + rows + "]条记录,返回了[" + generatedKeys.size() + "]条主键");
}
}
return rows;
} |
d1b0ff27-77e4-4be4-a1d9-25acba0a61c2 | 3 | protected synchronized boolean reduceMemoryWithDelegates(boolean aggressively) {
int reductionPolicy = aggressively ? MemoryManagerDelegate.REDUCE_AGGRESSIVELY
: MemoryManagerDelegate.REDUCE_SOMEWHAT;
boolean anyReduced = false;
for (MemoryManagerDelegate mmd : delegates) {
if (mmd == null)
continue;
boolean reduced = mmd.reduceMemory(reductionPolicy);
anyReduced |= reduced;
}
return anyReduced;
} |
0bc9475e-cb8c-41c0-894e-fd4c559a3660 | 6 | public void run() {
try {
//Generate the image for the Fractal
f.generateImage();
//If we should perform filtering make sure the Fractal is not sparse
if (PERFORM_FILTERING) {
//Counts how many times the current Fractal has been mutated
int retries;
//Try to mutate a sparse Fractal to get a less sparse one. If that fails,
//then recreate the Fractal again.
do {
retries = 0;
//If the fractal is aesthetically unpleasing, mutate it
while (f.isSparseImage() && retries++ < MAX_RETRIES) {
f.discard();
f.inPlaceMutate();
f.generateImage();
}
//If the Fractal is still sparse after MAX_RETRIES attempts of mutation,
// recreate the Fractal again
if (f.isSparseImage()) {
f.discard();
f.redo();
f.generateImage();
}
} while (f.isSparseImage());
}
//Load the image file for the Fractal
f.loadImage();
} catch (InterruptedException e) {
System.err.println("Interrupted");
}
} |
409bb1e7-cf15-497e-adf5-713748cf89f0 | 2 | public String[] getTerminalsOnRHS() {
ProductionChecker pc = new ProductionChecker();
ArrayList list = new ArrayList();
for (int i = 0; i < myRHS.length(); i++) {
char c = myRHS.charAt(i);
if (ProductionChecker.isTerminal(c))
list.add(myRHS.substring(i, i + 1));
}
return (String[]) list.toArray(new String[0]);
} |
523ea70d-cf6f-40e7-9502-294b9843920a | 5 | public void LineSwap() {
if (caret.row == sel.row) {
if (caret.row == 0) {
return;
}
UndoPatch up = new UndoPatch(caret.row - 1, caret.row);
StringBuilder swb = code.getsb(caret.row - 1);
code.get(caret.row - 1).sbuild = code.get(caret.row).sbuild;
code.get(caret.row).sbuild = swb;
up.realize(caret.row);
storeUndo(up, OPT.SWAP);
if (sel.type != ST.RECT) {
sel.col = caret.col = line_offset_from(caret.row, caret.colw);
}
} else {
UndoPatch up = new UndoPatch();
int srow = Math.min(sel.row, caret.row), erow = Math.max(sel.row, caret.row);
StringBuilder swb = code.getsb(srow);
for (int i = srow; i < erow; i++) {
code.get(i).sbuild = code.get(i + 1).sbuild;
}
code.get(erow).sbuild = swb;
up.realize(erow);
if (sel.type != ST.RECT) {
sel.col = caret.col = line_offset_from(caret.row, caret.colw);
}
storeUndo(up, OPT.SWAP);
}
} |
aa25a82e-843b-43f4-9b22-0d16eb581291 | 6 | @Test
public void testAstarGraph() throws IOException{
HashMap<String,String[]> fromTo = new HashMap<String,String[]>();
fromTo.put("results_wolfeb_178816527_178816525_1_astar.txt", new String[]{"178816527", "178816525"});
fromTo.put("results_wolfeb_330767681_178817851_1_astar.txt", new String[]{"330767681", "178817851"});
fromTo.put("results_wolfeb_330767681_178826160_1_astar.txt", new String[]{"330767681", "178826160"});
for(String s : fromTo.keySet()){
String config[] = {"FtWayneNoDups_nodes.txt", "FtWayneNoDups_links.txt", fromTo.get(s)[0], fromTo.get(s)[1],
"testResults/"+s, "1", "astar"};
Searcher.main(config);
BufferedReader testFile = new BufferedReader(new FileReader("testResults/"+s));
BufferedReader correctFile = new BufferedReader(new FileReader("correctResults/"+s));
String testLine = testFile.readLine();
String correctLine = correctFile.readLine();
while(true){
if(correctLine == null || testLine == null)
break;
assertEquals(testLine, correctLine);
testLine = testFile.readLine();
correctLine = correctFile.readLine();
}
if(testLine == null && correctLine != testLine){
fail("Size of files differ");
}
testFile.close();
correctFile.close();
}
} |
cfc3989a-1895-4b2f-be2b-f207257bf573 | 8 | private void updateObject(Object changedObject){
String table = changedObject.getClass().getSimpleName();
switch(table){
case "User":
User user = (User) changedObject;
dataStorage.users().updateUser(user);
break;
case "Group":
Group group = (Group) changedObject;
dataStorage.groups().updateGroup(group);
break;
case "Room":
Room room = (Room) changedObject;
dataStorage.rooms().updateRoom(room);
break;
case "Meeting":
Meeting meeting = (Meeting) changedObject;
dataStorage.meetings().updateMeeting(meeting);
break;
case "ExternalUser":
ExternalUser externalUser = (ExternalUser) changedObject;
dataStorage.externalUsers().updateExternalUser(externalUser);
break;
case "GroupMembership":
GroupMembership groupMembership = (GroupMembership) changedObject;
dataStorage.groupMemberships().updateGroupMembership(groupMembership);
break;
case "MeetingInvite":
MeetingInvite meetingInvite = (MeetingInvite) changedObject;
dataStorage.meetingInvites().updateMeetingInvite(meetingInvite);
break;
case "MeetingAdmin":
MeetingAdmin meetingAdmin = (MeetingAdmin) changedObject;
dataStorage.meetingAdmins().updateMeetingAdmin(meetingAdmin);
break;
default:
break;
}
} |
0d87aa70-15c2-4d27-9d56-50c968bc0a51 | 8 | private boolean r_postlude() {
int among_var;
int v_1;
// repeat, line 70
replab0: while (true) {
v_1 = cursor;
lab1: do {
// (, line 70
// [, line 72
bra = cursor;
// substring, line 72
among_var = find_among(a_1, 3);
if (among_var == 0) {
break lab1;
}
// ], line 72
ket = cursor;
switch (among_var) {
case 0:
break lab1;
case 1:
// (, line 73
// <-, line 73
slice_from("i");
break;
case 2:
// (, line 74
// <-, line 74
slice_from("u");
break;
case 3:
// (, line 75
// next, line 75
if (cursor >= limit) {
break lab1;
}
cursor++;
break;
}
continue replab0;
} while (false);
cursor = v_1;
break replab0;
}
return true;
} |
30866e9b-8b07-4a12-a5ee-2c951c144061 | 8 | @Test
public void persistenceTest() throws Exception
{
PartitionedHashMap map = (PartitionedHashMap) getMapInstance( 16 );
long totalSize = 0;
int amount = 0;
for ( long i = -456; i < 1029; i++ )
{
amount++;
totalSize += Long.toString( i ).length();
assertTrue( map.put( Long.toString( i ), i ) );
}
for ( long i = -456; i < 1029; i++ )
{
assertEquals( new Long( i ), map.get( Long.toString( i ) ) );
}
map.persistSome( totalSize );
Field mapStore = PartitionedHashMap.class.getDeclaredField( "store" );
mapStore.setAccessible( true );
HashMap<WrappedString, ArrayHashMapOption> actualStore = (HashMap<WrappedString, ArrayHashMapOption>) mapStore.get( map );
for ( Map.Entry<WrappedString, ArrayHashMapOption> entry : actualStore.entrySet() )
{
assertNull( entry.getValue().getValue() );
assertFalse( entry.getValue().inMemory() );
}
map.get( "0" );
boolean foundOneInMemory = false;
for ( Map.Entry<WrappedString, ArrayHashMapOption> entry : actualStore.entrySet() )
{
if ( entry.getValue().inMemory() )
{
if ( foundOneInMemory )
{
fail( "There can be only one (in memory)" );
}
else
{
foundOneInMemory = true;
}
}
}
assertTrue( foundOneInMemory );
for ( long i = -456; i < 1029; i++ )
{
assertEquals( new Long( i ), map.get( Long.toString( i ) ) );
}
for ( Map.Entry<WrappedString, ArrayHashMapOption> entry : actualStore.entrySet() )
{
assertNotNull( entry.getValue().getValue() );
assertTrue( entry.getValue().inMemory() );
}
} |
a5debedc-3527-40fd-b102-949351c4b624 | 6 | public void add(){
OptionView temp=null;
SavedEntityState selected=null;
temp=((GrandView)getSuperview()).getOptions();
for(int i=0;i<getScrollables().size();i++)
if(getScrollables().get(i).getSelected())
selected=((SelectableLabel)getScrollables().get(i)).getSavedEntityState();
if(selected==null){
if(temp!=null&&!temp.getAddEntityState()){
System.out.println("Adding Saved Entity State");
temp.clearBools();
temp.setAddEntityState(true);
temp.setReferenceObject(savedStates);
temp.checkInitialization();
}else{
if(temp==null)
System.out.println("Major Error :: OptionView null 1 :: SavedEntityStateView");
else
System.out.println("Minor Error :: OptionView open :: SavedEntityStateView");
}
}
getAccept().setSelected(false);
} |
b187b10a-bf4b-4388-8b2f-2c5bb5bd99aa | 5 | private static void annotateSuperRegions(BotState state) {
for (SuperRegion superRegion : state.getVisibleMap().getSuperRegions()) {
boolean canSuperRegionBeTaken = canSuperRegionBeTaken(state, superRegion);
boolean canSuperRegionBeTakenByOpponent = canSuperRegionBeTakenByOpponent(state, superRegion);
boolean canGetPushedOutOfSuperRegion = canGetPushedOutOfSuperRegion(state, superRegion);
boolean canPushOpponentOutOfSuperRegion = canPushOpponentOutOfSuperRegion(state, superRegion);
List<SuperRegionAnnotations> annotations = new ArrayList<>();
if (canSuperRegionBeTaken) {
annotations.add(SuperRegionAnnotations.CAN_BE_TAKEN);
}
if (canSuperRegionBeTakenByOpponent) {
annotations.add(SuperRegionAnnotations.CAN_BE_TAKEN_BY_OPPONENT);
}
if (canPushOpponentOutOfSuperRegion) {
annotations.add(SuperRegionAnnotations.CAN_PUSH_OPPONENT_OUT);
}
if (canGetPushedOutOfSuperRegion) {
annotations.add(SuperRegionAnnotations.CAN_GET_PUSHED_OUT);
}
superRegion.setAnnotations(annotations);
}
} |
fb39d9ea-ad08-40e0-8dca-aa4954f817c5 | 2 | @Override
public void execute() {
final SceneObject cutRoot = SceneEntities.getNearest(Settings.CUT_CURL_FILTER);
if(cutRoot != null) {
doAction("Collect", cutRoot);
} else {
final SceneObject uncutRoot = SceneEntities.getNearest(Constants.CURLY_ROOT_ID);
if(uncutRoot != null) {
doAction("Chop", uncutRoot);
}
}
} |
286233ba-e017-4e7c-9515-7d12e9004d21 | 9 | public void checkAssignmentCorrect()
{
boolean checkAssign = true;
for(Integer m: this.Assignment.keySet())
{
Integer t = this.Assignment.get(m);
for(Integer cm: this.getConnectedMeetings(m))
{
if(t == this.Assignment.get(cm))
{
checkAssign = false;
break;
}
}
}
if(checkAssign)
{
for (Integer e: this.EmployeeMeetingMap.keySet())
{
ArrayList<Integer> meetingsForE = this.EmployeeMeetingMap.get(e);
for(Integer meeting: this.Assignment.keySet()){
if(meetingsForE.contains(meeting))
{
if(!checkValidForOneEmployee(meeting, this.Assignment.get(meeting), meetingsForE))
{
checkAssign = false;
break;
}
}
}
}
}
if(checkAssign)
System.out.println("TESTING: Assignment is Valid");
else
System.out.println("TESTING: Assignment is NOT valid");
} |
02d0af8f-1b8d-4db9-ae0a-c57269a4a0f7 | 7 | private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBox1ItemStateChanged
//getting values from jCombo box
//if the value dosn't change use the default values from the global variables
int selection = jComboBox1.getSelectedIndex();
switch (selection){
case 0: minPrice = 0; maxPrice = 1000000; break;
case 1: minPrice = 100000; maxPrice = 150000; break;
case 2: minPrice = 150000; maxPrice = 200000; break;
case 3: minPrice = 200000; maxPrice = 250000; break;
case 4: minPrice = 250000; maxPrice = 350000; break;
case 5: minPrice = 350000; maxPrice = 500000; break;
case 6: minPrice = 500000; maxPrice = 1000000; break;
}
}//GEN-LAST:event_jComboBox1ItemStateChanged |
bad9e8ab-53b1-4cf6-b1da-230333c265cc | 4 | @EventHandler(priority = EventPriority.LOW)
public void onBlockPlace(BlockPlaceEvent E)
{
Block B = E.getBlockPlaced();
if (B == null)
return;
//Alert the player when they create a printing press.
//If a base block is placed, check for the piston -
else if (B.getType() == M.conf.PressBlock)
{
PistonBaseMaterial piston = new PistonBaseMaterial(Material.PISTON_BASE, B.getRelative(0, 2, 0).getData());
if (B.getRelative(0, 2, 0).getType() == Material.PISTON_BASE)
if (piston.getFacing() == BlockFace.DOWN)
Language.msg(E.getPlayer(), M.lang.PrintingPressCreated);
}
} |
9416af1d-3e8f-4c70-bbf6-78da538e8129 | 5 | private static boolean[] primeBoolArray(int limit) {
boolean[] nums = new boolean[limit];
for (int i = 2; i < nums.length; i++)
nums[i] = true;
int nextPrime = 2;
while (nextPrime < nums.length / 2) {
int i = nextPrime;
for (; i < nums.length; i += nextPrime)
nums[i] = false;
nums[nextPrime] = true;
for (int j = nextPrime + 1; j < nums.length; j++) {
if (nums[j] == true) {
nextPrime = j;
break;
}
}
}
return nums;
} |
8ca9cbda-0293-46f5-b05b-d22cc23550e2 | 6 | private boolean isBinaryOp(String string)
{
if(string.equals("add") || string.equals("sub") || string.equals("mult") || string.equals("div") || string.equals("and") || string.equals("or"))
return true;
else
return false;
} |
b25c4b45-9781-4c9b-b75a-d83ab59f8aee | 8 | @Override
public void actionPerformed(ActionEvent e) {
DocUtils.buttonDoClick(e);
String txt = wordProcessor.area1.getText().replaceAll("\r\n", "\n");
String find = wordProcessor.findFld.getText();
if (find == null || find.isEmpty()) {
wordProcessor.findMsg.setText("Enter a term to find");
return;
}
if (!wordProcessor.findAndMatchCase) {
txt = txt.toLowerCase();
find = find.toLowerCase();
}
if (txt.contains(find)) {
int count = 0;
int start = txt.indexOf(find);
int end = start + find.length();
wordProcessor.area1.select(start, end);
String searchRange = txt;
while (searchRange != null && !searchRange.isEmpty() && searchRange.contains(find)) {
count++;
start = searchRange.indexOf(find);
end = start + find.length();
searchRange = searchRange.substring(end);
}
if (count != 1) wordProcessor.findMsg.setText(Integer.toString(count) + " matches found");
else wordProcessor.findMsg.setText(Integer.toString(count) + " match found");
}
else {
wordProcessor.findMsg.setText("No matches found");
Toolkit.getDefaultToolkit().beep();
}
} |
6e05fb0b-9217-4f95-a919-e60e58399c53 | 0 | ParticipantItf deserializeFromJson(String json) {
AutoBean<ParticipantItf> bean = AutoBeanCodex.decode(factory, ParticipantItf.class, json);
return bean.as();
} |
bff85bc6-0f33-46e5-b814-29447a831a22 | 6 | public void getList(int rep,String searchText)
{
String tempQuery = "";
if(rep == 0) {
tempQuery = DEFAULT_QUERY;
}
else if(rep == 1) {
searchText = searchText.toUpperCase();
tempQuery = "select * from (Select compid,compname,contactperson,contactno1,contactno2,email,compvname from company order by compname) where compvname like '"+searchText+"'";
System.out.println(tempQuery);
}
Statement stmt = null;
this.connect();
conn = this.getConnection();
try {
stmt = conn.createStatement();
}
catch (SQLException e) {
e.printStackTrace();
}
ResultSet rs;
try
{
rs = stmt.executeQuery(tempQuery);
try {
tableUtils.updateTableModelData((DefaultTableModel) listCompany.getModel(), rs, 6);
}
catch (Exception ex) {
Logger.getLogger(ViewMember.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch (SQLException e) {
e.printStackTrace();
}
finally {
this.disconnect();
}
try {
listCompany.setRowSelectionInterval(0, 0);
}
catch(Exception e) { }
} |
45b1812c-1986-4c43-bf12-4bc488933b2b | 5 | public static void main(String[] args){
if("SrcODS-Upload".matches("(?i)src-reset|srcOds|srcOds-upload")){
Log.Print("Ok");
}
try {
Class gsos=Class.forName("com.luxe.tools.util.MyReflection");
Class type=Class.forName("java.lang.String");
Constructor ct=gsos.getConstructor();
Method test=gsos.getMethod("test",type);
// Object cla=gsos.newInstance();
test.invoke(gsos,"init");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} |
ffafbbb5-12bc-44ca-81f6-0938577c4016 | 5 | private boolean checkNumber(int number, int[] numberCounter) {
if (number == 2 || number == 12 || number == 7) { // Si le nombre aux des est 2, 12 ou 7 (<=> les nombres presents qu'une fois sur la carte). Remarque : le 7 a deja ete place et son compteur deja incremente via la methode placeDesert(), il est necessaire dans ce test justement pour eviter qu'il ne soit place une deuxieme fois.
if (numberCounter[number-2] == 0) { // Si le compteur de nombre aux des correspondant est nul (<=> le nombre aux des n'a pas encore ete attribue a une tuile).
numberCounter[number-2]++; // Incremente le compteur de nombre aux des correspondant.
return true; // Retourne true : le nombre aux des choisi correspond a la creation d'une nouvelle tuile ressource.
}
} else { // Sinon, le nombre aux des est compris entre 3 et 11 inclus (<=> les nombres presents deux fois sur la carte).
if (numberCounter[number-2] < 2) { // Si le compteur de nombre aux des correspondant est inferieur a 2 (<=> le nombre aux des n'a pas encore ete attribue a deux tuiles).
numberCounter[number-2]++; // Incremente le compteur de nombre aux des correspondant.
return true; // Retourne true : le nombre aux des choisi correspond a la creation d'une nouvelle tuile ressource.
}
}
return false; // Retourne false car arrive a ce stade signifie que le nombre aux des choisi ne correspond pas a la creation d'une nouvelle tuile ressource (<=> le nombre choisi a deja ete place le nombre de fois impose par les regles).
} |
b1557a11-1100-48df-acc4-b17490d39d6f | 4 | public ArrayList<Block> getPredecessors() {
ArrayList<Block> predecessor = new ArrayList<Block>();
if (normalPre != null) {
predecessor.add(normalPre);
}
if (thenPre != null) {
predecessor.add(thenPre);
}
if (elsePre != null) {
predecessor.add(elsePre);
}
if (loopBack != null) {
predecessor.add(loopBack);
}
return predecessor;
} |
17002ae9-9043-4c64-887f-ec1488377b7a | 6 | public Predicate parsePredicate(String input) throws ParseException {
Matcher matcher = predicatePattern.matcher(input);
if (!matcher.matches()) {
throw new ParseException(
"The given input '" + input + "' is not a valid predicate.");
}
List<Term> arguments = new ArrayList<Term>();
for (int i = 2; i <= matcher.groupCount(); i++) {
String argument = matcher.group(i);
if (argument != null) {
if (argument.equals("_")) {
arguments.add(new Variable());
} else if (Character.isUpperCase(argument.charAt(0))) {
arguments.add(new Variable(argument));
} else {
try {
arguments.add(new uk.ac.ucl.cs.programming.coursework.terms.Number(
Integer.parseInt(argument)));
} catch (NumberFormatException ex) {
arguments.add(new Constant(argument));
}
}
}
}
return new Predicate(matcher.group(1), arguments);
} |
2e4d18f7-84ae-4747-9ef8-b854e2ffc099 | 1 | public JPanel getUsertilePWFieldMenu() {
if (!isInitialized()) {
IllegalStateException e = new IllegalStateException("Call init first!");
throw e;
}
return this.usermenuPWFieldMenu;
} |
f324d9df-cc2e-43b0-a60c-21f1b10a9010 | 7 | public static void readHash(String type_map, HashMap<String, String> typeMap) {
ArrayList<String> types = new ArrayList<String>();
ArrayList<String> tokens = new ArrayList<String>();
if (type_map != null) {
FileUtil.readLines(type_map, types);
for (int i = 0; i < types.size(); i++) {
if (!types.get(i).isEmpty()) {
ComUtil.tokenize(types.get(i), tokens);
if (tokens.size() != 0) {
if (tokens.size() != 2) {
for (int j = 0; j < tokens.size(); j++) {
System.out.print(tokens.get(j) + " ");
}
System.err
.println(type_map
+ " Error ! Not two elements in one line !");
return;
}
if (!typeMap.containsKey(tokens.get(0)))
typeMap.put(tokens.get(0), tokens.get(1));
else {
System.out.println(tokens.get(0) + " "
+ tokens.get(1));
System.err.println(type_map
+ " Error ! Same type in first column !");
return;
}
}
tokens.clear();
}
}
}
} |
12e93951-f3e2-4b68-bf8c-5fa29d1aab2c | 9 | private static Hand isPair(Card[] allCards) {
Hand h = new Hand();
int cardsALike = 0;
ArrayList<Card> pair = new ArrayList<>();
boolean found = false;
for (int j = 0; j < allCards.length; j++) {
Card firstCard = allCards[j];
if (!found) {
for (int k = 0; k < allCards.length; k++) {
Card secondCard = allCards[k];
if (firstCard.getNumber() == secondCard.getNumber() && firstCard.getColour() != secondCard.getColour()) {
if (pair.isEmpty()) {
pair.add(firstCard);
pair.add(secondCard);
cardsALike = 2;
}
}
}
if (cardsALike == 2) {
ArrayList<Card> cardsRemaining = new ArrayList<>();
for (int i = 0; i < allCards.length; i++) {
Card card = allCards[i];
if (pair.get(0).getNumber() != card.getNumber()) {
cardsRemaining.add(card);
}
}
Card[] temp = findHighestCards(listToArray(cardsRemaining), 3);
pair.add(temp[0]);
pair.add(temp[1]);
pair.add(temp[2]);
h.setHand(listToArray(pair));
h.setIndex(Hand.PAIR);
found = true;
} else {
cardsALike = 0;
pair = new ArrayList<>();
}
}
}
return h;
} |
9473eb62-ddef-4634-818c-15e4e9aa3607 | 8 | public void updateStat(){
int value = 0;
Iterator<Village> it = list.iterator();
List<Village> temp = new ArrayList<Village>();
Village v;
while(it.hasNext()){
v = it.next();
value += v.getPopulation();
v.updateHealth();
v.updateBaby();
if(v.getPopulation() == 0){
temp.add(v);
}
boolean collide = false;
for(Village v2 : list){
if(v != v2){
if(v.collide(v2)){
v.setGrowing(false);
v2.setGrowing(false);
collide = true;
}
}
}
if(!collide){
v.setGrowing(true);
}
}
if(!temp.isEmpty()){
Iterator<Village> it2 = temp.iterator();
while(it2.hasNext()){
list.remove(it2.next());
}
}
chartTotal.addValue(value);
} |
20d2246e-8cb1-4c12-ae7b-5993853a3c37 | 3 | @Override
public void caseAEstrCaso(AEstrCaso node)
{
inAEstrCaso(node);
{
List<PComando> copy = new ArrayList<PComando>(node.getComando());
Collections.reverse(copy);
for(PComando e : copy)
{
e.apply(this);
}
}
if(node.getValor() != null)
{
node.getValor().apply(this);
}
if(node.getCaso() != null)
{
node.getCaso().apply(this);
}
outAEstrCaso(node);
} |
1c173b2e-cb98-429c-b5b9-d6e73c233f02 | 1 | public long getReminderAhead(long uid) throws SQLException {
Reminder reminder = Reminder.findByApptAndUser(this.getId(), uid);
return reminder == null ? 0 : reminder.reminderAhead;
} |
31d22ad0-e41b-4bb2-a6fb-0cfcf832b99f | 1 | @Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int hScroll = mHSB.getValue();
if (mHeaderBounds.height > 0) {
Graphics2D gc = (Graphics2D) g.create();
try {
gc.clipRect(mHeaderBounds.x, mHeaderBounds.y, mHeaderBounds.width, mHeaderBounds.height);
gc.translate(mHeaderBounds.x - hScroll, mHeaderBounds.y);
drawHeader(gc);
} finally {
gc.dispose();
}
}
Graphics2D gc = (Graphics2D) g.create();
try {
gc.clipRect(mContentBounds.x, mContentBounds.y, mContentBounds.width, mContentBounds.height);
gc.translate(mContentBounds.x - hScroll, mContentBounds.y - mVSB.getValue());
drawContents(gc);
} finally {
gc.dispose();
}
} |
3949ed0f-adb7-42bc-b7fc-a26812db7ae2 | 6 | public static Schematic loadSchematic(File file) throws IOException {
FileInputStream stream = new FileInputStream(file);
@SuppressWarnings("resource")
NBTInputStream nbtStream = new NBTInputStream(stream);
CompoundTag schematicTag = (CompoundTag) nbtStream.readTag();
if (!schematicTag.getName().equals("Schematic")) {
throw new IllegalArgumentException("Tag \"Schematic\" does not exist or is not first");
}
Map<String, Tag> schematic = schematicTag.getValue();
if (!schematic.containsKey("Blocks")) {
throw new IllegalArgumentException("Schematic file is missing a \"Blocks\" tag");
}
short width = getChildTag(schematic, "Width", ShortTag.class).getValue();
short length = getChildTag(schematic, "Length", ShortTag.class).getValue();
short height = getChildTag(schematic, "Height", ShortTag.class).getValue();
// Get blocks
byte[] blockId = getChildTag(schematic, "Blocks", ByteArrayTag.class).getValue();
byte[] blockData = getChildTag(schematic, "Data", ByteArrayTag.class).getValue();
byte[] addId = new byte[0];
short[] blocks = new short[blockId.length]; // Have to later combine IDs
// We support 4096 block IDs using the same method as vanilla Minecraft, where
// the highest 4 bits are stored in a separate byte array.
if (schematic.containsKey("AddBlocks")) {
addId = getChildTag(schematic, "AddBlocks", ByteArrayTag.class).getValue();
}
// Combine the AddBlocks data with the first 8-bit block ID
for (int index = 0; index < blockId.length; index++) {
if ((index >> 1) >= addId.length) { // No corresponding AddBlocks index
blocks[index] = (short) (blockId[index] & 0xFF);
} else {
if ((index & 1) == 0) {
blocks[index] = (short) (((addId[index >> 1] & 0x0F) << 8) + (blockId[index] & 0xFF));
} else {
blocks[index] = (short) (((addId[index >> 1] & 0xF0) << 4) + (blockId[index] & 0xFF));
}
}
}
return new Schematic(blocks, blockData, width, length, height);
} |
86e5c703-fed8-441f-8559-5cc593d38096 | 6 | public void getCollidingBoundingBoxes(World par1World, int par2, int par3, int par4, AxisAlignedBB par5AxisAlignedBB, ArrayList par6ArrayList)
{
int var7 = par1World.getBlockMetadata(par2, par3, par4);
switch (getDirectionMeta(var7))
{
case 0:
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.25F, 1.0F);
super.getCollidingBoundingBoxes(par1World, par2, par3, par4, par5AxisAlignedBB, par6ArrayList);
this.setBlockBounds(0.375F, 0.25F, 0.375F, 0.625F, 1.0F, 0.625F);
super.getCollidingBoundingBoxes(par1World, par2, par3, par4, par5AxisAlignedBB, par6ArrayList);
break;
case 1:
this.setBlockBounds(0.0F, 0.75F, 0.0F, 1.0F, 1.0F, 1.0F);
super.getCollidingBoundingBoxes(par1World, par2, par3, par4, par5AxisAlignedBB, par6ArrayList);
this.setBlockBounds(0.375F, 0.0F, 0.375F, 0.625F, 0.75F, 0.625F);
super.getCollidingBoundingBoxes(par1World, par2, par3, par4, par5AxisAlignedBB, par6ArrayList);
break;
case 2:
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.25F);
super.getCollidingBoundingBoxes(par1World, par2, par3, par4, par5AxisAlignedBB, par6ArrayList);
this.setBlockBounds(0.25F, 0.375F, 0.25F, 0.75F, 0.625F, 1.0F);
super.getCollidingBoundingBoxes(par1World, par2, par3, par4, par5AxisAlignedBB, par6ArrayList);
break;
case 3:
this.setBlockBounds(0.0F, 0.0F, 0.75F, 1.0F, 1.0F, 1.0F);
super.getCollidingBoundingBoxes(par1World, par2, par3, par4, par5AxisAlignedBB, par6ArrayList);
this.setBlockBounds(0.25F, 0.375F, 0.0F, 0.75F, 0.625F, 0.75F);
super.getCollidingBoundingBoxes(par1World, par2, par3, par4, par5AxisAlignedBB, par6ArrayList);
break;
case 4:
this.setBlockBounds(0.0F, 0.0F, 0.0F, 0.25F, 1.0F, 1.0F);
super.getCollidingBoundingBoxes(par1World, par2, par3, par4, par5AxisAlignedBB, par6ArrayList);
this.setBlockBounds(0.375F, 0.25F, 0.25F, 0.625F, 0.75F, 1.0F);
super.getCollidingBoundingBoxes(par1World, par2, par3, par4, par5AxisAlignedBB, par6ArrayList);
break;
case 5:
this.setBlockBounds(0.75F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
super.getCollidingBoundingBoxes(par1World, par2, par3, par4, par5AxisAlignedBB, par6ArrayList);
this.setBlockBounds(0.0F, 0.375F, 0.25F, 0.75F, 0.625F, 0.75F);
super.getCollidingBoundingBoxes(par1World, par2, par3, par4, par5AxisAlignedBB, par6ArrayList);
}
this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
} |
b8ca883d-6161-4aef-b68a-9507773aeafa | 1 | public static String getAbstractSynCat(String synCat) throws Exception {
if (!abstractSynCat.containsKey(synCat))
throw new Exception("synCat " + synCat + " is unknown");
return abstractSynCat.get(synCat);
} |
ee81398e-b636-49ce-8708-701f6c4b4d6a | 0 | public void setUseDocumentSettings(boolean useDocumentSettings) {this.useDocumentSettings = useDocumentSettings;} |
f9eefc7d-f5c4-405b-9a6b-e3e7cc5171db | 5 | public String getContent(String urlString) throws MalformedURLException {
URL url = createURL(urlString);
URLConnection connection = createConnection(url);
if(connection == null) return "";
String content = "";
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
} catch (IOException e) {
e.printStackTrace();
return "";
}
String line;
try {
while( (line = reader.readLine()) != null ){
content = content + line + "\n";
}
} catch (IOException e) {
e.printStackTrace();
return "";
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
} |
56a3f8ce-d868-4567-a510-0d153c436eff | 3 | protected void openFiles(String indexDirectory_p) throws Exception{
// RandomAccessFile offsetFile=null;
// RandomAccessFile databaseFile=null;
//With persistent buffers
File offset_f=new File(indexDirectory+"/offsets.dat");
File database_f=new File(indexDirectory+"/database.dat");
File indexDirectory_f=new File(indexDirectory);
if(!indexDirectory_f.exists())
indexDirectory_f.mkdir();
if(offsetFile==null)
offsetFile=new RandomAccessFile(offset_f,"rw");
if(databaseFile==null)
databaseFile=new RandomAccessFile(database_f,"rw");/**/
// with MemoryMappedBuffers
/* if(offsets==null){
offsetFile=new RandomAccessFile(offset_f,"rw");
offsets=offsetFile.getChannel().map(java.nio.channels.FileChannel.MapMode.READ_WRITE,0,offsetFile.length());
}
if(database==null){
databaseFile=new RandomAccessFile(database_f,"rw");
database=databaseFile.getChannel().map(java.nio.channels.FileChannel.MapMode.READ_WRITE,0,databaseFile.length());
};/**/
} |
30495f7b-a1bd-40f3-908c-fd71616d8503 | 7 | private void merge(int left, int middle1, int middle2, int right)
{
int leftIndex= left;
int rightIndex = middle2;
int combIndex= left;
int[] combArray= new int[array.length];
// output two subarrays before merging
// System.out.println( "merge: " + subarray( left, middle1 ) );
// System.out.println( " " + subarray( middle2, right ) );
System.out.println( "merge: " + subarray( left, middle1 ) );
System.out.println( " " + subarray( middle2, right ) );
while(leftIndex <= middle1 && rightIndex <= right){
if(array[leftIndex] <= array[rightIndex]){
combArray[combIndex++]= array[leftIndex++];
} else{
combArray[combIndex++]= array[rightIndex++];
inversionCount = inversionCount + (middle1- leftIndex) + 1;
}
}// end while
// if the left array is empty
if(leftIndex == middle2){
while(rightIndex <= right){
combArray[combIndex++]= array[rightIndex++];
}
}else{// if the right array is empty
while(leftIndex <= middle1){
combArray[combIndex++]= array[leftIndex++];
}
}// end else
// copy the array back to the original array
for(int i=left; i<= right;i++){
array[i] = combArray[i];
}
// print the merged array
// System.out.println(" "+ subarray(left, right));
// System.out.println();
System.out.println(" "+ subarray(left, right));
System.out.println();
}// end method merge |
f95de4f6-e76b-4f5d-9fc9-0fdf32360ac8 | 4 | public static void main(String[] args) throws Exception
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String sNumber1 = reader.readLine();
String sNumber2 = reader.readLine();
String sNumber3 = reader.readLine();
int n1 = Integer.parseInt(sNumber1);
int n2 = Integer.parseInt(sNumber2);
int n3 = Integer.parseInt(sNumber3);
if (!(isMax(n1,n2,n3)) && !(isMin(n1,n2,n3)))
{
System.out.println(n1);
}
else if (!(isMax(n2,n1,n3)) && !(isMin(n2,n1,n3))) {
System.out.println(n2);
}
else System.out.println(n3);
} |
4dea53b3-f577-4aec-9eb3-42bd1cb1f300 | 5 | public AnimationTimer(int from, int to) {
loopCoef = 0;
toX = to;
fromX = from;
movex = 0 + MARGIN;
// 目的拡大率を算出
double xs = (getWidth() - 2.0d * MARGIN) / massRange;
tmpMassStart = massStart + ((toX - MARGIN) / xs);
tmpMassRange = 10 * (fromX / (10 * xs));
if (tmpMassRange < MASS_RANGE_MIN) {
tmpMassRange = MASS_RANGE_MIN;
}
// Intensityのレンジを設定
if ((peaks1 != null) && (massRange <= massRangeMax)) {
// 最大値を検出。
int max = 0;
double start = Math.max(tmpMassStart, 0.0d);
max = searchPage.getMaxIntensity(start, start + tmpMassRange);
if (peaks2 != null)
max = Math.max(max, peaks2.getMaxIntensity(start, start
+ tmpMassRange));
// 50単位に変換してスケールを決定
tmpIntensityRange = (int) ((1.0d + max / 50.0d) * 50.0d);
if (tmpIntensityRange > INTENSITY_MAX)
tmpIntensityRange = INTENSITY_MAX;
}
} |
9a39d12f-812b-4594-a534-6bfaa7ba469c | 0 | public static void main(String[] args) {
// メッセージダイアログ表示
JOptionPane.showMessageDialog(null, "ハロー!");
} |
f00a2c2f-7c61-4dd3-b0de-094f146cf949 | 4 | @Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
Document doc = fb.getDocument();
Element root = doc.getDefaultRootElement();
int count = root.getElementCount();
int index = root.getElementIndex(offset);
Element cur = root.getElement(index);
int promptPosition = cur.getStartOffset() + PROMPT.length();
if(index == count - 1 && offset - promptPosition >= 0) {
if(text.equals("\n")) {
String cmd = doc.getText(promptPosition, offset - promptPosition);
if(cmd.isEmpty()) {
text = "\n" + PROMPT;
}
else {
text = "\n" + PROMPT;
}
}
fb.replace(offset, length, text, attrs);
}
} |
b2927e2e-48f6-416d-a2ec-7e688362c76b | 3 | public static int getPlayerIDFromName(String inName) throws WrongNameException{
int n = 0;
boolean success = false;
for(int i = 0; i < NumPlayers; i++){
if(Players[i].equals(inName)){
n = i+1;
success = true;
break;
}
}
if(!success) throw new WrongNameException();
return (n);
} |
a75d0c1d-bd11-4b40-850a-82dd68988f31 | 4 | public boolean isOptOut() {
synchronized (optOutLock) {
try {
// Reload the metrics file
configuration.load(getConfigFile());
} catch (IOException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
} catch (InvalidConfigurationException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
}
return configuration.getBoolean("opt-out", false);
}
} |
0b97e2c2-2f79-4dd9-8239-09373d0c2697 | 8 | private static String initialise(Token currentToken,
int[][] expectedTokenSequences,
String[] tokenImage) {
String eol = System.getProperty("line.separator", "\n");
StringBuffer expected = new StringBuffer();
int maxSize = 0;
for (int i = 0; i < expectedTokenSequences.length; i++) {
if (maxSize < expectedTokenSequences[i].length) {
maxSize = expectedTokenSequences[i].length;
}
for (int j = 0; j < expectedTokenSequences[i].length; j++) {
expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');
}
if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
expected.append("...");
}
expected.append(eol).append(" ");
}
String retval = "Encountered \"";
Token tok = currentToken.next;
for (int i = 0; i < maxSize; i++) {
if (i != 0) retval += " ";
if (tok.kind == 0) {
retval += tokenImage[0];
break;
}
retval += " " + tokenImage[tok.kind];
retval += " \"";
retval += add_escapes(tok.image);
retval += " \"";
tok = tok.next;
}
retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
retval += "." + eol;
if (expectedTokenSequences.length == 1) {
retval += "Was expecting:" + eol + " ";
} else {
retval += "Was expecting one of:" + eol + " ";
}
retval += expected.toString();
return retval;
} |
b52c3ff1-cdee-4c10-85eb-50a397e2b2cc | 1 | public static void println(String string, int l) {
if (check(l)) {
toTerminal(string + "\n", l);
}
} |
1830d196-9306-4d48-9f18-f7e5e8ada8c5 | 7 | public static void drawMap()
{
for (int x=0;x<Square.xAmt();++x)
{
for (int y=0;y<Square.yAmt();++y)
{
if (Square.get(x,y).isFree())
{
int r=120-map.value[x][y]/10;
int b=map.value[x][y]/25;
if (r>120) r=120;
if (r<0) r=0;
if (b>255) b=255;
if (b<0) b=0;
Draw.draw(new Draw(Square.get(x,y),new Color(0,r,b),1));
}
}
}
} |
9321c24b-5a6e-4b14-acd9-acb6e4711e3a | 9 | public void start() {
ObjectName serverName = null;
HtmlAdaptorServer adaptor = null;
try {
serverName = new ObjectName("Http:name=HttpAdaptor");
adaptor = new HtmlAdaptorServer();
domain.registerMBean(adaptor, serverName);
} catch (MalformedObjectNameException e) {
e.printStackTrace();
} catch (NotCompliantMBeanException e) {
e.printStackTrace();
} catch (InstanceAlreadyExistsException e) {
e.printStackTrace();
} catch (MBeanRegistrationException e) {
e.printStackTrace();
}
try {
domain.setAttribute(serverName, new Attribute("Port", new Integer(port)));
} catch (InstanceNotFoundException e) {
e.printStackTrace();
} catch (AttributeNotFoundException e) {
e.printStackTrace();
} catch (InvalidAttributeValueException e) {
e.printStackTrace();
} catch (MBeanException e) {
e.printStackTrace();
} catch (ReflectionException e) {
e.printStackTrace();
}
adaptor.setPort(port);
System.out.println("Starting the HtmlAdaptor....on port:"+adaptor.getPort());
adaptor.start();
} |
3b034883-a2b7-4db5-947c-b88d7f89af0c | 0 | public void setLocation(double latitude, double longitude) {
putMergeVar("mc_location", new Location(latitude, longitude));
} |
6ecf3498-0bfb-43f3-bd1a-b00c1b6cf202 | 4 | public PrimitiveOperator combineLeftNLeft(PrimitiveOperator other) {
boolean[] newTruthTable = new boolean[4];
// the other gate is on the left side - on the LSB
newTruthTable[0] = truthTable[((other.truthTable[0]) ? 1 : 0) | 0]; //00
newTruthTable[1] = truthTable[((other.truthTable[1]) ? 1 : 0) | 0]; //01
newTruthTable[2] = truthTable[((other.truthTable[2]) ? 1 : 0) | 2]; //10
newTruthTable[3] = truthTable[((other.truthTable[3]) ? 1 : 0) | 2]; //11
return new PrimitiveOperator(newTruthTable);
} |
5edbd0cd-47f4-4f19-9563-90861ae8a3b2 | 1 | public PlayerStatsSummaryListDto getStatsBySummonerId(Region region, long summonerId, Season season) { //only one data set per queue type
String addon = (season == Settings.CURRENT_SEASON) ? "?api_key=" : ("?season=" + season.toString() + "&api_key=");
String requestURL = Settings.API_BASE_URL + region.toString().toLowerCase() + "/v" + getCategoryVersion() + "/" + getObjectCategory() + "/by-summoner/" + summonerId + "/summary" + addon + Settings.API_KEY_NO_FORMAT;
JsonObject json = Get.getJsonForURL(requestURL, errors);
Gson gson = new Gson();
PlayerStatsSummaryListDto stats = gson.fromJson(json.toString(), PlayerStatsSummaryListDto.class);
return stats;
} |
72a3e10b-52ae-4446-a724-be7c8cd88247 | 6 | @EventHandler
public void ZombieWeakness(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getZombieConfig().getDouble("Zombie.Weakness.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getZombieConfig().getBoolean("Zombie.Weakness.Enabled", true) && damager instanceof Zombie && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.WEAKNESS, plugin.getZombieConfig().getInt("Zombie.Weakness.Time"), plugin.getZombieConfig().getInt("Zombie.Weakness.Power")));
}
} |
fd8c2919-ed45-4619-b852-4d4c341813f9 | 1 | public void setAutomaton(Automaton newAuto) {
if (newAuto == null) {
//System.out.println("Setting automaton null");
return;
}
automaton = newAuto;
this.invalidate();
} |
e162def7-e90a-4c7d-b4fd-fc1e17016661 | 3 | public void setUsers(User[] users) {
usersModel.clear();
Runnable adder = new Runnable () {
@Override
public void run () {
usersModel.add( usersQueue.poll() );
}
};
try {
for (User user : users) {
usersQueue.add(user);
if ( SwingUtilities.isEventDispatchThread() )
SwingUtilities.invokeLater(adder);
else
SwingUtilities.invokeAndWait(adder);
}
} catch (InterruptedException | InvocationTargetException e) {
ClientLogger.log("Chyba pri nastavovani seznamu uzivatelu: " + e.getMessage(), ClientLogger.ERROR);
}
} |
927e7eab-2980-4aae-8a3e-fa2626b3306c | 8 | public static File isCommandPathViable(String path, File extraBinDir) {
if (path != null) {
File file = new File(path);
if (file.isFile()) {
return file;
}
if (path.indexOf(File.separatorChar) == -1) {
if (extraBinDir != null) {
file = new File(extraBinDir, path);
if (file.isFile()) {
return file;
}
}
String cmdPath = System.getenv("PATH"); //$NON-NLS-1$
if (cmdPath != null) {
StringTokenizer tokenizer = new StringTokenizer(cmdPath, File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
file = new File(tokenizer.nextToken(), path);
if (file.isFile()) {
return file;
}
}
}
}
}
return null;
} |
ec7c891a-1dbe-46a7-b44a-365b444c903d | 3 | public static Method getMethod(Class<?> cl, String method) {
for (Method m : cl.getMethods()) if (m.getName().equals(method)) return m;
return null;
} |
ac39e546-79cc-444d-bf2c-bfd22da4ddce | 4 | public ChannelMenu(String host, String pass, String nick, String user, String real) throws IOException {
super(host);
main = new IRCMain(host, new int[] {1024, 2048, 6667, 6669} , pass, nick, user, real);
main.addIRCEventListener(internalList);
//main.addIRCEventListener(new IRCLocalListener());
setBounds(100, 100, 450, 540);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(1, 1, 0, 0));
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
getContentPane().add(tabbedPane);
Panel joinChannel = new Panel();
tabbedPane.addTab("Join", null, joinChannel, null);
joinChannel.setLayout(null);
list = new List();
list.setMultipleMode(true);
list.setBounds(10, 10, 409, 212);
joinChannel.add(list);
txtPleaseWaitConnecting = new JTextField();
txtPleaseWaitConnecting.setText("Please wait, connecting...");
txtPleaseWaitConnecting.setBounds(10, 228, 409, 37);
txtPleaseWaitConnecting.setEditable(false);
joinChannel.add(txtPleaseWaitConnecting);
txtPleaseWaitConnecting.setColumns(10);
btnRefresh = new JButton("Refresh");
btnRefresh.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
try {
getChannelList();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
btnRefresh.setBounds(10, 333, 89, 46);
joinChannel.add(btnRefresh);
JButton btnJoin = new JButton("Join");
btnJoin.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
String[] selected = list.getSelectedItems();
System.out.println("Please wait...");
if(selected.length == 0){
System.out.println("Joining typed channel...");
isJoiningAChannel = true; numChannelFlag = 1;
main.doJoin("#" + txtPleaseWaitConnecting.getText());}
else
joinChannels(selected);
}
private void joinChannels(String[] selected){
System.out.println("Joining selected channels...");
String chanConcat = "";
numChannelFlag = selected.length;
for(int i = 0; i < selected.length; i++){
chanConcat += selected[i].split(" :")[0] + ",";}
chanConcat = chanConcat.substring(0, chanConcat.length()-1);
System.out.println(chanConcat);
isJoiningAChannel = true;
main.doJoin(chanConcat);}
});
btnJoin.setBounds(10, 276, 89, 46);
joinChannel.add(btnJoin);
Panel createChannel = new Panel();
tabbedPane.addTab("Create", null, createChannel, null);
createChannel.setLayout(null);
txtChannelNameHere = new JTextField();
txtChannelNameHere.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
if(initialClick)
txtChannelNameHere.setText("");
initialClick = false;
}
});
txtChannelNameHere.setFont(new Font("Tahoma", Font.PLAIN, 11));
txtChannelNameHere.setText("Set Topic Here");
txtChannelNameHere.setBounds(10, 11, 409, 28);
createChannel.add(txtChannelNameHere);
txtChannelNameHere.setColumns(10);
txtSetPasswordHere = new JTextField();
txtSetPasswordHere.setHorizontalAlignment(SwingConstants.CENTER);
txtSetPasswordHere.setText("set password here");
txtSetPasswordHere.setBounds(163, 255, 111, 20);
createChannel.add(txtSetPasswordHere);
txtSetPasswordHere.setColumns(10);
txtLimit = new JTextField();
txtLimit.setHorizontalAlignment(SwingConstants.CENTER);
txtLimit.setText("limit");
txtLimit.setBounds(95, 203, 58, 20);
createChannel.add(txtLimit);
txtLimit.setColumns(10);
chckbxPrivChan = new JCheckBox("private channel flag");
chckbxPrivChan.setBounds(10, 46, 121, 23);
createChannel.add(chckbxPrivChan);
chckbxSecretChannelFlag = new JCheckBox("secret channel flag");
chckbxSecretChannelFlag.setBounds(10, 72, 121, 23);
createChannel.add(chckbxSecretChannelFlag);
chckbxInviteOnly = new JCheckBox("invite only");
chckbxInviteOnly.setBounds(10, 98, 97, 23);
createChannel.add(chckbxInviteOnly);
chckbxTopicSettableBy = new JCheckBox("topic settable by channelop only");
chckbxTopicSettableBy.setBounds(10, 124, 181, 23);
createChannel.add(chckbxTopicSettableBy);
chckbxNoMessagesTo = new JCheckBox("no messages to channel from outside clients");
chckbxNoMessagesTo.setBounds(10, 150, 237, 23);
createChannel.add(chckbxNoMessagesTo);
chckbxModerated = new JCheckBox("moderated");
chckbxModerated.setBounds(10, 176, 97, 23);
createChannel.add(chckbxModerated);
chckbxSetUserLimit = new JCheckBox("set user limit");
chckbxSetUserLimit.setBounds(10, 202, 97, 23);
createChannel.add(chckbxSetUserLimit);
chckbxSetBanMask = new JCheckBox("set ban mask to keep users out");
chckbxSetBanMask.setBounds(10, 230, 175, 23);
createChannel.add(chckbxSetBanMask);
chckbxSetPasswordFor = new JCheckBox("set password for channel");
chckbxSetPasswordFor.setBounds(10, 254, 147, 23);
createChannel.add(chckbxSetPasswordFor);
JButton btnCreate = new JButton("Create");
btnCreate.setBounds(29, 354, 162, 91);
createChannel.add(btnCreate);
main.connect();
} |
25d09cbb-db3f-48ef-81de-ece6936362b9 | 6 | @EventHandler(priority = EventPriority.NORMAL)
public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
if (event.isCancelled())
return;
if (event.getEntity().getType() == EntityType.PLAYER) {
Player player = (Player) event.getEntity();
if (plugin.playerProtections.containsKey(player.getName())) {
Double recalled = plugin.playerProtections.get(player.getName());
if (recalled >= Lifestones.getUnixTime()) {
plugin.debug("Protecting recalled player " + player.getName());
plugin.sendMessage(player, GRAY + L("playerProtectedByLifestone"));
event.setCancelled(true);
return;
}
}
}else if (event.getDamager().getType() == EntityType.PLAYER){
Player player = (Player) event.getDamager();
if (plugin.playerProtections.containsKey(player.getName()))
plugin.playerProtections.remove(player.getName());
}
} |
67e87932-cae3-4990-81c8-33848f21664e | 9 | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tuple3 tuple3 = (Tuple3) o;
if (item != null ? !item.equals(tuple3.item) : tuple3.item != null) return false;
if (item2 != null ? !item2.equals(tuple3.item2) : tuple3.item2 != null) return false;
if (item3 != null ? !item3.equals(tuple3.item3) : tuple3.item3 != null) return false;
return true;
} |
410ca3af-aea8-4827-9ab3-3044a34ff529 | 2 | @Before
public void setUp() {
TestHelper.signon(this);
MongoHelper.setDB("fote");
MongoHelper.getCollection("suggestions").drop();
for(Suggestion suggestion : suggestions) {
if (!MongoHelper.save(suggestion, "suggestions")) {
TestHelper.failed("save suggestion failed");
}
}
} |
0a018dcf-598b-4f1c-a6c1-1aa8835ce455 | 2 | public Bag getDiscsWithGlide(int glide) {
LOGGER.log(Level.INFO, "Getting discs with glide " + glide);
Bag discBag = new Bag();
for (int i = 0; i < discs.size(); i++) {
if (discs.get(i).getGlide() == glide) {
discBag.addDisc(discs.get(i));
}
}
LOGGER.log(Level.INFO, "Found " + discBag.size() + " discs with glide " + glide);
return discBag;
} |
4f486006-59d4-46ed-81f5-3f3d7aac6ebc | 9 | public int motorUse(String[] prices, String[] purchases) {
int running = 0;
// Convert input prices
int cols = prices.length;
mInventory = new Inventory(prices.length);
for (int i=0; i<cols; i++) {
String temp[] = prices[i].split(" ");
int shelves = temp.length;
mInventory.columns[i] = new Column(shelves);
for (int j=0; j<shelves; j++) {
mInventory.columns[i].put(j, Integer.valueOf(temp[j]));
}
}
// Verify
if (LOGD) {
System.out.println("columns=" + mInventory.cols + " shelves=" + mInventory.columns[0].shelves);
for (int i=0; i<mInventory.cols; i++) {
Column col = mInventory.columns[i];
for (int j=0; j<col.shelves; j++) {
System.out.println("Column " + i + " Shelf " + j + " has " + col.get(j));
}
}
System.out.println("");
}
// Start
mCurrentColumn = 0;
// move to the most expensive columns after power on.
running = moveToExpensiveColumn();
// Convert input purchases
int purchase_length = purchases.length;
Purchase purchase[] = new Purchase[purchase_length];
for (int i=0; i<purchase_length; i++) {
purchase[i] = new Purchase(purchases[i]);
// Calculate.
int moved = buy(purchase[i]);
if (moved==-1) {
if (LOGD) System.out.println("Invalid. return -1");
return -1;
} else {
running += moved;
}
}
/*
// move to the most expensive columns at the end of the simulation
moveToExpensiveColumn();
*/
if (LOGD) {
System.out.println("");
System.out.println("running=" + running);
}
return running;
} |
67b96516-324a-427e-a125-3e9062eb790a | 9 | private static void testColorValueRange(int r, int g, int b, int a) {
boolean rangeError = false;
String badComponentString = "";
if (a < 0 || a > 255) {
rangeError = true;
badComponentString = badComponentString + " Alpha";
}
if (r < 0 || r > 255) {
rangeError = true;
badComponentString = badComponentString + " Red";
}
if (g < 0 || g > 255) {
rangeError = true;
badComponentString = badComponentString + " Green";
}
if (b < 0 || b > 255) {
rangeError = true;
badComponentString = badComponentString + " Blue";
}
if (rangeError == true) {
throw new IllegalArgumentException("Color parameter outside of expected range:" + badComponentString);
}
} |
57f7ff87-82d4-4830-a7d0-2aed92b42478 | 6 | public final int fetchBinaryUInt(int size) throws EParseError {
if ((size == 0) || (pos + size > length))
throw new EParseError("Out of range"); // TODO: special exception
int r = 0;
int b;
b = src[pos++];
r = (b & 0xFF);
if (size == 1) return r;
b = src[pos++] & 0xFF;
r = (r<<8) | b;
if (size == 2) return r;
b = src[pos++] & 0xFF;
r = (r<<8) | b;
if (size == 3) return r;
b = src[pos++] & 0xFF;
r = (r<<8) | b;
if (size == 4) return r;
throw
new EParseError("Invalid bytes length");
} |
faeeaea8-d3b5-43a4-85da-da7ed6907dfb | 7 | public boolean clickedSign(Player player, Sign state) {
for (Animation a : animations) {
if (player.equals(a.CurrentEditor)
&& state.getLine(0).endsWith("SUPERFRAME")) {
if (a.WaitingToAddFrame) {
a.WaitingToAddFrame = false;
state.setLine(0, ChatColor.DARK_AQUA + "SUPERFRAME");
state.setLine(1,
ChatColor.AQUA + "Frame " + a.Frames.size());
a.AddFrame(state.getBlock().getLocation());
state.update(true);
return true;
}
if (!state.getLine(1).startsWith(ChatColor.AQUA + "Frame "))
return false;
int frameInd = Integer.parseInt(ChatColor.stripColor(state
.getLine(1).replace(ChatColor.AQUA + "Frame ", "")));
if (a.CurrentModifyingFrameIndex == frameInd) {
player.sendMessage(ChatColor.AQUA
+ " You have completed modifying frame "
+ a.CurrentModifyingFrameIndex);
a.CurrentModifyingFrameIndex = -1;
updateDrawing(a.Frames.get(frameInd), a.CurrentFrameIndex>-1?a.Frames.get(a.CurrentFrameIndex):null);
return true;
}
a.CurrentModifyingFrameIndex = frameInd;
player.sendMessage(ChatColor.AQUA
+ " You are now modifying frame "
+ a.CurrentModifyingFrameIndex);
updateDrawing(a.Frames.get(frameInd), a.Frames.get(frameInd));
return true;
}
}
return false;
} |
c8201479-bbaf-4d85-9d1a-c5cc8d4f4d89 | 9 | private void updateStateTellOrigin(List<Keyword> keywords, List<String> terms) {
//Check if new Recipe was also passed as a keyword
if (keywords != null && !keywords.isEmpty()) {
for (Keyword kw : keywords) {
if (kw.getKeywordData().getType() == KeywordType.RECIPE) {
currRecipe = new Recipe((RecipeData)kw.getKeywordData().getDataReference().get(0));
return;
}
}
}
//If not, the recipe should've already been set, if not, we need a recipe Name.
if (currRecipe == null || currRecipe.getRecipeData() == null) {
getCurrentDialogState().setCurrentState(RecipeAssistance.RA_WAITING_FOR_RECIPE_NAME);
return;
}
if (keywords == null || keywords.isEmpty() && currRecipe != null) {
DialogManager.giveDialogManager().setInErrorState(true);
}
} |
6b478895-84a8-43bd-bf75-49510d24dda1 | 1 | public void clear() {
for (int i = 0; i < size; i++) {
data[i] = null;
}
size = 0;
} |
10f6b5fa-2d5f-4a85-8be5-f754636e50a6 | 5 | public SoundUtil() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try {
for (int i = 0; i < fileNames.length; i++) {
String name = fileNames[i];
URL url = classLoader.getResource("resources/" + name);
File audioFile = new File(url.toURI());
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
if (i == 0) {
lowShipBeep = (Clip) AudioSystem.getLine(info);
lowShipBeep.open(audioStream);
} else if (i == 1) {
highShipBeep = (Clip) AudioSystem.getLine(info);
highShipBeep.open(audioStream);
} else if (i == 2) {
explosion = (Clip) AudioSystem.getLine(info);
explosion.open(audioStream);
}
}
} catch (IOException | URISyntaxException |
UnsupportedAudioFileException | LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
0030c927-f421-4cbe-9a07-c2da30f6b890 | 0 | public int getStudentId() {
return studentId;
} |
9840c921-7384-4411-812f-ab55e32dc29a | 2 | public void keyPressed(KeyEvent e) {
if (e.getKeyCode() > 0 && e.getKeyCode() < 256) {
keys[e.getKeyCode()] = true;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.