method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
c7f08dd9-3d2d-4c40-8627-8687c963eb86
| 3
|
public void spawn(final Player p){
PlayerData data = PluginData.getPlayerData(p);
if(data == null) Broadcast.error("You cannot be spawned because your player data cannot be found. Report this error.", p);
else{
final ClassType classChoice = data.getNextClass();
if(classChoice == null){
MenuManager.sendPlayerClassMenu(p);
SchedulerManager.registerRepeatingTicks("SPAWN LOGIC", "GET " + p.getName() + " CLASS", 0, 1, new Runnable(){
public void run(){
final PlayerData pdata = PluginData.getPlayerData(p);
System.out.println("Looking in data for " + p.getName() + ", has class of " + pdata.getNextClass());
if(pdata.getNextClass() != null){
System.out.println("PLAYER " + p.getName() + " CHOSE CLASS " + pdata.getNextClass().toString());
continueSpawnLogic1(p, pdata);
SchedulerManager.endAllWithName("GET " + p.getName() + " CLASS");
}
}
});
}else continueSpawnLogic1(p, data);
}
}
|
412c7634-5476-4831-805f-29d5129b6862
| 8
|
public void setValueString(String newValueString)
{
valueString = newValueString;
// parse:
try
{
value = new Double(valueString);
isValid = true;
}
catch (NumberFormatException e)
{
isValid = false;
}
catch (NullPointerException e)
{
isValid = false;
}
// perform limit checking:
if( useLimits )
{
// sanity check:
if( value != null && min != null && max != null )
isValid = isValid && ( value <= max && value >= min );
else
isValid = false;
}
}
|
f3b0ae9e-686b-48f6-9fa0-4f703f32c395
| 2
|
public static void main(String args[]){
int headCount=0,tailCOunt=0;
GenericCoin GC=new GenericCoin();
for(int i=0;i<50;i++){
GC.toss();
if(GC.isHeadSide())
headCount++;
else
tailCOunt++;
}
System.out.println("HeadCount is: "+headCount);
System.out.println("TailCount is: "+tailCOunt);
}
|
6a038759-5c7d-4429-ae8c-f7db345dd49d
| 6
|
public Map<String, Object> findSimpleResult(String sql, List<Object> params)
throws SQLException {
Map<String, Object> map = new HashMap<String, Object>();
int index = 1;
pstmt = connection.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
resultSet = pstmt.executeQuery();//
ResultSetMetaData metaData = resultSet.getMetaData();
int col_len = metaData.getColumnCount();//
while (resultSet.next()) {
for (int i = 0; i < col_len; i++) {
String cols_name = metaData.getColumnName(i + 1);
Object cols_value = resultSet.getObject(cols_name);
if (cols_value == null) {
cols_value = "";
}
map.put(cols_name, cols_value);
}
}
return map;
}
|
eac35844-7b2f-4f90-b384-33e18c332069
| 9
|
public void mousePressed(MouseEvent e) {
//NIVEL 1 ............................................
if(bNivel1){
for(Object lnkProducto : lnkProductos1) {
Producto proObjeto = (Producto) lnkProducto;
// Si se selecciona un objeto
if(proObjeto.colisiona(e.getX(), e.getY())) {
proObjeto.setAgarrado(true);
mPosX = e.getX();
mPosY= e.getY();
break;
}
}
}
//NIVEL 2..................................................
if(bNivel2){
for(Object lnkProducto : lnkProductos2) {
Producto proObjeto = (Producto) lnkProducto;
// Si se selecciona un objeto
if(proObjeto.colisiona(e.getX(), e.getY())) {
proObjeto.setAgarrado(true);
mPosX = e.getX();
mPosY= e.getY();
break;
}
}
}
//NIVEL 3..................................................
if(bNivel3){
for(Object lnkProducto : lnkProductos3) {
Producto proObjeto = (Producto) lnkProducto;
// Si se selecciona un objeto
if(proObjeto.colisiona(e.getX(), e.getY())) {
proObjeto.setAgarrado(true);
mPosX = e.getX();
mPosY= e.getY();
break;
}
}
}
}
|
af77e87f-fa27-4b86-a1af-0e02a4e34649
| 7
|
public static void sendMail(EmailDetailsDto emailDto) throws SwingObjectException{
MultiPartEmail email=null;
try {
if(emailDto.isHtml()) {
email=new HtmlEmail();
((HtmlEmail)email).setHtmlMsg(emailDto.getBody());
}else {
email = new MultiPartEmail();
email.setMsg(emailDto.getBody());
}
if (emailDto.getAttachments()!=null) {
for(EmailAttachment attach : emailDto.getAttachments()){
FileDataSource fd=new FileDataSource(attach.getFileloc());
fd.setFileTypeMap(mimetypes);
email.attach(fd, attach.getFilename(),attach.getFilename());
}
}
setCommonAttributes(emailDto, email);
email.send();
}catch(SwingObjectException e) {
throw e;
}catch(EmailException e) {
if(e.getCause() instanceof AuthenticationFailedException) {
throw new SwingObjectException("swingobj.email.authfailed", e,ErrorSeverity.ERROR, EmailHelper.class);
}
throw new SwingObjectException("swingobj.emailnotsent",e, ErrorSeverity.SEVERE, EmailHelper.class);
} catch (Exception e) {
throw new SwingObjectException("swingobj.emailnotsent",e, ErrorSeverity.SEVERE, EmailHelper.class);
}
}
|
27967e02-ccca-4128-b2cd-53edd0c6028e
| 6
|
public void setPixel(int x, int y, int gray) throws Exception {
if (x < 0 || x >= width)
throw new Exception("x out of range");
if (y < 0 || y >= height)
throw new Exception("y out of range");
if (gray < 0)
gray = 0;
if (gray > 255)
gray = 255;
this.image[x][y] = gray;
}
|
a00ed7c7-52cb-4a23-bd4f-fd3b2c3b5fc8
| 8
|
public static void m68ki_set_sm_flag(long s_value, long m_value) {
/* ASG: Only do the rest if we're changing */
s_value = (s_value != 0) ? 1L : 0L;
m_value = (m_value != 0 && (m68k_cpu.mode & CPU_MODE_EC020_PLUS) != 0) ? 1 : 0 << 1;
if (get_CPU_S() != s_value || get_CPU_M() != m_value) {
/* Backup the old stack pointer */
m68k_cpu.sp[(int) (get_CPU_S() | (get_CPU_M() & (get_CPU_S() << 1)))] = get_CPU_A()[7];
/* Set the S and M flags */
set_CPU_S(s_value != 0 ? 1L : 0L);
set_CPU_M((m_value != 0 && (m68k_cpu.mode & CPU_MODE_EC020_PLUS) != 0) ? 1 : 0 << 1);
/* Set the new stack pointer */
set_CPU_A(7, m68k_cpu.sp[(int) (get_CPU_S() | (get_CPU_M() & (get_CPU_S() << 1)))]);
}
}
|
32c8883c-8f65-4377-816f-5546eb7ebade
| 8
|
public void colourGrid(int i, int j) {
if((i / 3 < 1 || i / 3 >= 2) && (j / 3 < 1 || j / 3 >= 2)
|| (i / 3 >= 1 && i / 3 < 2) && (j / 3 >= 1 && j / 3 < 2)) {
gridView[i][j].setBackground(Color.LIGHT_GRAY);
} else {
gridView[i][j].setBackground(Color.WHITE);
}
gridView[i][j].setOpaque(true);
}
|
fedd2e82-1e77-49de-aeeb-0d9ec9f85128
| 8
|
public static String[] getBadCharactersForPassingNamingValidation(String password) {
String[] badCharacters = new String[0];
//return badCharacters;
String badCharacter = "";
int j =0;
passwordValidation:
for (String character : password.split(""))
{
// fix for first empty character
System.out.println(character);
j++;
if (character != "") if (character.isEmpty() == false)
{
for (Integer i = 0; i < 127; i++) {
if (i == 48) i =123;
if (character.toCharArray()[0] == (char)i.intValue()) {
badCharacter = character;
}
}
if (badCharacter != "") if (badCharacter.isEmpty() == false) {
System.out.println("" + badCharacters.length);
badCharacters = Arrays.copyOf(badCharacters, badCharacters.length + 1);
badCharacters[badCharacters.length - 1] = badCharacter;
System.out.println("" + badCharacters.length);
}
continue passwordValidation;
}
}
System.out.println("" + j);
return badCharacters;
}
|
7b7bc9bf-a07e-432d-baa6-ed214645ec9e
| 4
|
public static boolean transform(InstructionContainer ic,
StructuredBlock last) {
if (!(last.outer instanceof SequentialBlock)
|| !(ic.getInstruction() instanceof StoreInstruction)
|| !(ic.getInstruction().isVoid()))
return false;
return (createAssignOp(ic, last) || createAssignExpression(ic, last));
}
|
27beaba7-24b5-4056-a1a2-40766a894639
| 1
|
public int treeDepth(BTPosition<T> current) throws InvalidPositionException {
if (current == root)
return 1;
return 1 + treeDepth(current.getParent());
}
|
9b0c7a4b-ba8a-4dee-9e04-3cc18c3052f6
| 0
|
@BeforeClass
public static void setUpClass() {
}
|
59898034-1e42-42f4-b7b6-b8c9d15bd667
| 2
|
public InnerClassInfo getOuterClassInfo(ClassInfo ci) {
if (ci != null) {
InnerClassInfo[] outers = ci.getOuterClasses();
if (outers != null)
return outers[0];
}
return null;
}
|
50108264-ca70-4957-bb9c-25293fcf315f
| 4
|
public void addDeploymentAlternativeIfNotPresent(DeploymentAlternative deploymentAlternative, SequenceAlternative sequenceAlternative) {
for (DeploymentAlternative da : project.getDeploymentAlternatives())
if (da.getId().equals(deploymentAlternative.getId())) {// deploymentAlternative
// already
// present
for (DeploymentAlternative sda : sequenceAlternative.getDeploymentAlternatives())
if (sda.getId().equals(da.getId()))
return;
sequenceAlternative.getDeploymentAlternatives().add(da);
return;
}
project.getDeploymentAlternatives().add(deploymentAlternative);
sequenceAlternative.getDeploymentAlternatives().add(deploymentAlternative);
}
|
1754d445-ed00-45b0-87e3-193d6ed19431
| 0
|
@Test
public void testSetNombre() {
System.out.println("setNombre");
String nombre = "";
Cuenta instance = new Cuenta();
instance.setNombre(nombre);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
|
dc82d531-0732-44b2-8d18-0e437b95ead2
| 9
|
public boolean hasPrimitivePeer() {
if (mObjectClass == Integer.class ||
mObjectClass == Boolean.class ||
mObjectClass == Byte.class ||
mObjectClass == Character.class ||
mObjectClass == Short.class ||
mObjectClass == Long.class ||
mObjectClass == Float.class ||
mObjectClass == Double.class ||
mObjectClass == Void.class) {
return true;
}
return false;
}
|
a6d09e0c-776c-4bf7-b709-6401aacd0921
| 6
|
protected boolean isPalindrome(int pNumber){
boolean check = false;
int[] digits = breakIntToDigitsArray(pNumber);
if (pNumber > 99999){
if(digits[0] == digits[5] && digits[1] == digits[4] && digits[2] == digits[3]){
check = true;
}
} else {
if(digits[0] == digits[4] && digits[1] == digits[3]){
check = true;
}
}
return check;
}
|
af78f734-20de-4b88-9a00-4e7b806b892b
| 4
|
public static void removeAdress(int memberID){
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
conn.setAutoCommit(false);
PreparedStatement stmnt = conn.prepareStatement("DELETE FROM Staff WHERE staff_id = ?");
stmnt.setInt(1, memberID);
stmnt.execute();
conn.commit();
conn.setAutoCommit(true);
}catch(SQLException e){
System.out.println("Remove fail: " + e);
}
}
|
b33924d4-0461-472e-8954-2623e732213b
| 7
|
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
String inputLine = scan.nextLine();
String[] words = inputLine.split("[^a-zA-Z]+");
// for (String string : words) {
// System.out.println(string);
// }
HashSet<String> cognateWords = new HashSet<>();
String cognateWord;
int a, b;
for (a = 0; a < words.length; a++) {
for (b = 0; b < words.length; b++) {
for (String c : words) {
boolean isCognateWords = a != b
&& words[a].concat(words[b]).equals(c);
if (isCognateWords) {
cognateWord = String.format("%s|%s=%s", words[a],
words[b], c);
cognateWords.add(cognateWord);
}
}
}
}
if (cognateWords.isEmpty()) {
System.out.println("No");
} else {
for (String wordsLine : cognateWords) {
System.out.println(wordsLine);
}
}
}
|
5f1fd6ba-284d-424d-8865-a7873e897cb0
| 2
|
@Override
public Color[][] getColors(double[][] heightmap, boolean[][] watermap) {
Color[][] color = new Color[heightmap.length][heightmap.length];
for (int x = 0; x < heightmap.length; x++)
for (int y = 0; y < heightmap[x].length; y++)
color[x][y] = getColor(heightmap, watermap, x, y);
return color;
}
|
e40bc8df-2f1e-4963-ad7c-9f1d531d72e6
| 5
|
@Test
public void deepMiddleTest() {
Array<Integer> arr = ObjectArray.from(
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26);
for(int i = 8; i >= 6; i--) {
arr = arr.remove(i);
}
for(int i = 15; i >= 9; i--) {
arr = arr.remove(i - 3);
}
assertEquals(
ObjectArray.from(0, 1, 2, 3, 4, 5, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26), arr);
Array<Integer> arr2 = ObjectArray.from(
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30);
for(int i = 4; i >= 0; i--) arr2 = arr2.cons(i);
for(int i = 31; i <= 35; i++) arr2 = arr2.snoc(i);
for(int i = 22; i >= 16; i--) arr2 = arr2.remove(i);
assertEquals(
ObjectArray.from(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35),
arr2);
}
|
e92dec7e-caaf-43b8-9c4f-da17d9296084
| 7
|
public void shoot(int dist, Point shooterPosition) {
int d6 = 42 + (6 * 6 * currentTime.getH() + 6 * currentTime.getM() +
currentTime.getS()) % 42;
int d7 = 42 + (7 * 7 * currentTime.getH() + 7 * currentTime.getM() +
currentTime.getS()) % 42;
int id = 0;
if (dist < d6)
id = 6;
if (dist >= d6 && (dist - d6) < d7 )
id = 7;
if (dist - d6 - d7 >= 0 )
id = 8;
if (id == 6) {
shooterPosition.trans(0, (int)Math.round(Math.cos(dist * Math.PI / 2)));
shapeChangingDist = -dist / 10 - 6;
shape = new Rhombus();
}
if (id == 7) {
shooterPosition.trans(0, (int)Math.round(Math.cos(d6 * Math.PI / 2)));
shooterPosition.trans((int)Math.round(Math.sin((dist - d6) * Math.PI / 2)),
(int)Math.round(Math.cos((dist - d6) * Math.PI / 2)));
shapeChangingDist = -d6 / 10 - 6 + ( -(dist -d6) / 10 - 7);
shape = new Rectangle();
}
if (id == 8) {
shooterPosition.trans(0, (int)Math.round(Math.cos(d6 * Math.PI / 2)));
shooterPosition.trans((int)Math.round(Math.sin(d7 * Math.PI / 2)),
(int)Math.round(Math.cos(d7 * Math.PI / 2)));
shapeChangingDist = -d6 / 10 - 6 + ( -d7 / 10 - 7);
shape = new Dot();
}
}
|
e6f49da4-46f2-4660-a7be-e81613dc9b9e
| 8
|
public int compare(Object o1, Object o2) {
o1 = ((Vector<?>) o1).elementAt(column);
o2 = ((Vector<?>) o2).elementAt(column);
if(o1 instanceof Double && o2 instanceof Double) {
return ((Double) o1).compareTo(((Double) o2));
}
if(o1 instanceof String && o2 instanceof String) {
return ((String) o1).compareTo(((String) o2));
}
if(o1 instanceof Integer && o2 instanceof Integer) {
return ((Integer) o1).compareTo(((Integer) o2));
}
throw new RuntimeException("Comparaison entre deux lignes du tableau impossible");
}
|
809525c4-f419-470c-aea4-99ab94ad9575
| 5
|
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Email)) {
return false;
}
Email other = (Email) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
|
eb84cd2c-380d-4cfe-b1ab-eba8322a7677
| 2
|
public void flatten(TreeNode root) {
if(root == null)
return;
List<TreeNode> list = new ArrayList<TreeNode>();
addTreeNode(list,root);
TreeNode node = root;
for(int i = 1 ;i < list.size();i++){
node.left = null;
node.right = list.get(i);
node = node.right;
}
}
|
bf364513-7bea-4052-a320-788b732ac0ef
| 4
|
public boolean insertNewCod(String cod, String nome){
out("Inserindo novo código...");
boolean isThere = false;
rs = responseQuery("SELECT cod FROM " + tableCodName + " WHERE cod = '" + cod + "';");
try
{
while(rs.next())
{
String str = rs.getString("cod");
if(str.equals(cod))
isThere = true;
}
if(!isThere)
sqlQuery("INSERT INTO " + tableCodName + " (cod, nome) VALUES ('"+ cod +"','"+ nome +"');", "Inserindo cod e nome.");
else
JOptionPane.showMessageDialog(null, "O código informado já foi cadastrado.", "ERRO", JOptionPane.ERROR_MESSAGE);
}
catch (SQLException ex)
{
Logger.getLogger(TrackingNumberWatcherDBConn.class.getName()).log(Level.SEVERE, null, ex);
}
return isThere;
}
|
1dd0b176-b35a-4d2a-bbb4-a0b191244c66
| 9
|
@Override
public boolean equals( Object otherObj )
{
try
{
// If same object, just quickly return true.
if ( this == otherObj )
{
return true;
}
// If other object is not same class as this object, quickly return false.
if ( otherObj == null || !otherObj.getClass().equals( getClass() ) )
{
return false;
}
Fauxjo other = (Fauxjo) otherObj;
List<Object> keys1 = getPrimaryKeyValues();
List<Object> keys2 = other.getPrimaryKeyValues();
// If the primary keys somehow are different lengths, they must not be the same.
if ( keys1.size() != keys2.size() )
{
return false;
}
// Check each key item, if ever different, return false;
for ( int i = 0; i < keys1.size(); i++ )
{
Object item1 = keys1.get( i );
Object item2 = keys2.get( i );
if ( item1 == null && item2 != null )
{
return false;
}
else if ( !item1.equals( item2 ) )
{
return false;
}
}
}
catch ( Exception ex )
{
throw new RuntimeException( ex );
}
return true;
}
|
f45cd22f-b0d3-4c4f-a74c-32dcb324567d
| 3
|
public ConfigFile() {
gson = new GsonBuilder().setPrettyPrinting().create();
File root = Constants.getRoot();
configurationFile = new File(root,"config.json");
if (configurationFile.exists())
config = gson.fromJson(readString(), Configuration.class);
else
{
config = new Configuration();
File sourceRoot = Constants.getRootOfSource();
int firstGoodOne = 0;
while (true)
{
File test = new File(sourceRoot,String.format("%d-timecode", firstGoodOne));
if (test.exists())
break;
firstGoodOne++;
}
config.currentInFile = firstGoodOne;
config.currentOutFile = 0;
config.currentFileLocation = 0;
}
}
|
e0df4707-fae1-403f-a833-4fd06e8bf34c
| 0
|
protected Class getTransitionClass() {
return automata.fsa.FSATransition.class;
}
|
5ee4c772-d989-4aa4-8784-952865902e1c
| 4
|
@Override
public void onDeleteDirectory(String arg0, DokanFileInfo arg1)
throws DokanOperationException {
try {
if (DEBUG)
System.out.println("SeleteDir: " + arg0);
fileSystem.deleteDirectoryRecursively(mapWinToUnixPath(arg0));
} catch (AccessDeniedException e) {
throw new DokanOperationException(net.decasdev.dokan.WinError.ERROR_ACCESS_DENIED);
} catch (PathNotFoundException e) {
throw new DokanOperationException(net.decasdev.dokan.WinError.ERROR_PATH_NOT_FOUND);
} catch (Exception e)
{
e.printStackTrace();
}
}
|
4191cc7c-eb80-4779-a162-2388b8d20152
| 5
|
@Override
public boolean equals(Object object) {
if (!(object instanceof Organization)) {
return false;
}
Organization other = (Organization) object;
if ((this.organizationName == null && other.organizationName != null) || (this.organizationName != null && !this.organizationName.equals(other.organizationName))) {
return false;
}
return true;
}
|
40aee9be-96af-4adc-a3ce-968ebcb09473
| 9
|
private List<Entry> createEntries(GoodsType goodsType) {
List<Entry> result = new ArrayList<Entry>();
if (goodsType.isFarmed()) {
for (ColonyTile colonyTile : colonyTiles) {
Tile tile = colonyTile.getWorkTile();
if (tile.potential(goodsType, null) > 0
|| (tile.hasResource()
&& !tile.getTileItemContainer().getResource().getType()
.getModifierSet(goodsType.getId()).isEmpty())) {
for (Unit unit : units) {
result.add(new Entry(goodsType, colonyTile, unit));
}
}
}
} else {
for (Building building : colony.getBuildingsForProducing(goodsType)) {
if (building.getType().getWorkPlaces() > 0) {
for (Unit unit : units) {
result.add(new Entry(goodsType, building, unit));
}
}
}
}
Collections.sort(result, defaultComparator);
entries.put(goodsType, result);
return result;
}
|
fc75bb05-652b-4826-ae0e-b425b7535ab5
| 0
|
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
|
0b4c9027-da28-4c83-9253-1c7db5bb40e7
| 8
|
public ImportXml(String fileName, String type) {
// Use the default (non-validating) parser
SAXParserFactory factory = SAXParserFactory.newInstance();
Debug.print("Using Sax Parser factory: " + factory.getClass() + "\n");
try {
// Parse the input
SAXParser saxParser = factory.newSAXParser();
if (type.equalsIgnoreCase("style")){
styleHandler = new XmlStyleHandler();
saxParser.parse(new File(fileName), styleHandler);
}
if (type.equalsIgnoreCase("beerXML")){
beerXmlHandler = new XmlBeerXmlHandler();
saxParser.parse(new File(fileName), beerXmlHandler);
}
else {
handler = new XmlHandler();
saxParser.parse(new File(fileName), handler);
}
} catch (SAXParseException spe) {
// Error generated by the parser
System.out.println("\n** Parsing error" + ", line "
+ spe.getLineNumber() + ", uri " + spe.getSystemId());
System.out.println(" " + spe.getMessage());
// Use the contained exception, if any
Exception x = spe;
if (spe.getException() != null)
x = spe.getException();
x.printStackTrace();
} catch (SAXException sxe) {
// Error generated by this application
// (or a parser-initialization error)
Exception x = sxe;
if (sxe.getException() != null)
x = sxe.getException();
x.printStackTrace();
} catch (ParserConfigurationException pce) {
// Parser with specified options can't be built
pce.printStackTrace();
} catch (IOException ioe) {
// I/O error
ioe.printStackTrace();
}
}
|
981d9295-402c-47a7-b564-e879b62826df
| 2
|
@Override
protected int getAvgIndex(ChannelType c) {
switch (c) {
case HUE:
return 0;
case SATURATION:
return 1;
default:
throw new IllegalArgumentException();
}
}
|
dab728bb-14c5-4ab8-98d5-7a2bb31ace8c
| 5
|
public int nextInt() {
do {
int cursorNow = bufferCursor.get() ;
int cursorNext = cursorNow+1 ;
if ( cursorNext < BUFFER_SIZE && bufferCursor.compareAndSet(cursorNow, cursorNext) ) {
return buffer[cursorNext] ;
}
else {
synchronized (bufferGen) {
cursorNow = bufferCursor.get() ;
cursorNext = cursorNow+1 ;
if ( cursorNext >= BUFFER_SIZE ) {
return fillBuffer() ;
}
else if ( bufferCursor.compareAndSet(cursorNow, cursorNext) ) {
return buffer[cursorNext] ;
}
}
}
}
while (true) ;
}
|
f5b104f4-019f-4c31-a78d-35b7482fec4d
| 0
|
public ClientHanldler(Socket client) {
this.client = client;
}
|
4ca9a5b5-a6fc-48e3-8c1e-96780583b472
| 7
|
@EventHandler
public void SkeletonBlindness(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("Skeleton.Blindness.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (damager instanceof Arrow) {
Arrow a = (Arrow) event.getDamager();
LivingEntity shooter = a.getShooter();
if (plugin.getSkeletonConfig().getBoolean("Skeleton.Blindness.Enabled", true) && shooter instanceof Skeleton && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, plugin.getSkeletonConfig().getInt("Skeleton.Blindness.Time"), plugin.getSkeletonConfig().getInt("Skeleton.Blindness.Power")));
}
}
}
|
94359272-a7c6-4b5a-a078-ef30a8952013
| 5
|
protected final void CreateConfirmWindow() {
sum = getTotalSumOfTheOrder();
try {
log.debug("Contents of the current basket:\n"
+ model.getCurrentPurchaseTableModel());
Object[] options = { "Accept", "Cancel" };
NumberFormat amountFormat = NumberFormat.getNumberInstance();
sumField = new JFormattedTextField(amountFormat);
sumField.setValue(new Double(sum));
sumField.setColumns(10);
sumField.setEditable(false);
paidField = new JFormattedTextField(amountFormat);
paidField.setValue(new Double(0.0));
paidField.setColumns(10);
paidField.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
log.debug(e.getKeyChar());
propertyChange();
}
});
changeField = new JFormattedTextField(amountFormat);
changeField.setValue(new Double(0.0));
changeField.setColumns(10);
changeField.setEditable(false);
changeAmount = ((Number) paidField.getValue()).doubleValue() - sum;
final JComponent[] inputs = new JComponent[] { new JLabel("Sum"),
sumField, new JLabel("Paid"), paidField,
new JLabel("Change"), changeField };
int n = JOptionPane.showOptionDialog(null, inputs, "Confirm",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
options, options[1]);
log.info(n);
// 0 Accept
if (n == 0) {
changeAmount = ((Number) paidField.getValue()).doubleValue()
- sum;
if (((Number) paidField.getValue()).doubleValue() < sum) {
JOptionPane.showMessageDialog(this, "Need more money!",
"Try again", JOptionPane.ERROR_MESSAGE);
changeField.setValue(new Double(0.0));
domainController.cancelCurrentPurchase();
dispose();
} else {
// actually submit item to history
List<SoldItem> a = model.getCurrentPurchaseTableModel()
.getTableRows();
HistoryItem item = new HistoryItem(a);
model.getHistoryTableModel().addItem(item);
Session session = HibernateUtil.currentSession();
session.getTransaction().begin();
for (SoldItem i : a) {
i.getStockItem().setQuantity(
i.getStockItem().getQuantity());
i.setHistoryItem(item);
session.update(i.getStockItem());
}
session.getTransaction().commit();
domainController.submitCurrentPurchase(a);
model.getCurrentPurchaseTableModel().clear();
endPurchaseAfterPaying();
}
} else {
// log.info(n);
domainController.cancelCurrentPurchase();
}
} catch (VerificationFailedException e1) {
log.error(e1.getMessage());
}catch(SessionException ee){
ee.getMessage();
}
finally {
model.getCurrentPurchaseTableModel().clear();
endPurchaseAfterPaying();
}
}
|
4d24744a-02a5-4fd3-9c58-7863f6ab661f
| 9
|
public static HashMap<String, Integer> readMileage(String path)
throws IOException
{
// Set up a HashMap to store the data
HashMap<String, Integer> mileageData = new HashMap<String, Integer>();
// Set up the reader from the text file
try
{
BufferedReader reader = new BufferedReader(new FileReader(path));
String input = reader.readLine();
//Source: http://stackoverflow.com/questions/15625629/regex-expressions-in-java-s-vs-s
String[] split = input.split("\\s+");
String[] keys = new String[121]; // Using 121 since there will be 11 * 11 keys
int keyIndex = 0;
Integer[] values = new Integer[121];
int valueIndex = 0;
if (input != null)
{
String[] getRowNames = new String[11];
String[] getColumnNames = new String[11];
// Store row and column names
for (int index = 1; index < 12; index++)
{
getRowNames[index - 1] = split[index];
getColumnNames[index - 1] = split[index];
}// for
// Concatenate both and use them as keys for the HashMap
for (int index = 0; index < 11; index++)
{
for (int index2 = 0; index2 < 11; index2++)
{
keys[keyIndex] =
getRowNames[index] + "," + getColumnNames[index2];
keyIndex++;
} // for
} // for
} // if
// Get the values from the table and store them in their respective hashkey
while (input != null)
{
input = reader.readLine();
if (input == null)
{
break;
} // if
String[] tmpArray = input.split("\\s+");
for (int index = 1; index < 12; index++, valueIndex++)
{
values[valueIndex] = Integer.valueOf(tmpArray[index]);
} // for
} // while
// Store them in the HashMap
for (int index = 0; index < 121; index++)
{
mileageData.put(keys[index], values[index]);
} // for
// Close reader
reader.close();
} // try
catch (FileNotFoundException e)
{
e.printStackTrace();
PrintWriter pen = new PrintWriter(System.out, true);
pen.print("Please specify valid and existing file path");
} // catch
return mileageData;
} // readMileage(String)
|
296ef82f-076d-4873-9a95-634e71aa8c42
| 5
|
public void drawMap(Graphics2D g){
for(int row = 0; row < numRowsToDraw; row++){
if(row >= numRows) break;
for(int col = 0; col < numColsToDraw; col++){
if(row >= numCols) break;
if(map[row][col] == 0) continue;
int rc = map[row][col];
int r = rc / numTilesAcross;
int c = rc % numTilesAcross;
g.drawImage(tiles[r][c].getImage(), (int)x + col * tileSize, (int)y + row * tileSize, null);
}
}
}
|
1b0477dc-51bf-4eaa-9ef5-5b24470f720c
| 2
|
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
return getSuppliercode() == ((SuppliersModel) obj).getSuppliercode() &&
getName() == ((SuppliersModel) obj).getName();
}
|
0aafb30e-eec8-451a-a1ea-1bd5d14da6ea
| 7
|
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final int newDressCode=1;
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
// now see if it worked
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> speak(s) exquisitely to <T-NAMESELF>.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
if(target.location()==mob.location())
{
//target.location().show(target,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> <S-IS-ARE> very well dressed."));
beneficialAffect(mob,target,asLevel,0);
final Ability A=target.fetchEffect(ID());
if(A!=null)
A.setMiscText(""+newDressCode);
}
}
}
else
return beneficialWordsFizzle(mob,target,L("<S-NAME> speak(s) exquisitely to <T-NAMESELF>, but nothing more happens."));
// return whether it worked
return success;
}
|
6c524d25-e69c-42b9-89bb-9c85f89f7bbd
| 2
|
private static void initMainMenuMask() {
String s = System.getProperty("os.name");
if ((s.lastIndexOf("Windows") != -1)
|| (s.lastIndexOf("windows") != -1))
MAIN_MENU_MASK = InputEvent.CTRL_MASK;
else
MAIN_MENU_MASK = InputEvent.META_MASK;
}
|
27f1df30-adf4-40cc-a6c5-c770d38915a7
| 1
|
public boolean suppressionFichier(ObjectInputStream input, ObjectOutputStream output) throws IOException
{
//lecture du pathname envoyé par le client
String pathnameFichier = input.readUTF();
try
{
boolean estSupprime = this.deleteDirOrFile(new File(pathnameFichier));
envoiConfirmation(output,estSupprime,pathnameFichier + " est supprimé.");
return estSupprime;
}
catch (IOException e)
{
envoiConfirmation(output, false ," Une erreur s'est produite, le fichier " + pathnameFichier + " n'est pas supprimé.");
return false;
}
}
|
d624e76e-99f2-4948-b7c6-36f61e3b4afa
| 2
|
public int getHealth(String userName){
try {
cs = con.prepareCall("{call returnPlayerHealth(?)}");
cs.setString(1, userName);
ResultSet rs = cs.executeQuery();
if(rs.next()){
return rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
|
2b80b742-d8f3-407e-9626-cafbec595bba
| 0
|
public void setListener(DollarListener listener)
{
this.listener = listener;
}
|
62a1b2e9-d810-4f71-a240-2a3b6a678446
| 6
|
@Test
public void testPropertiesFile() throws Exception
{
String filename = "temporary_test.prop";
//create a file for the properties
FileWriter fw = new FileWriter(filename);
// test all values correctly set
if (driver != null)
{
fw.write("com.github.conserveorm.driver=" + driver + "\n");
}
fw.write("com.github.conserveorm.connectionstring=" + database + "\n");
if(login!=null)
{
fw.write("com.github.conserveorm.username=" + login + "\n");
}
if(password != null)
{
fw.write("com.github.conserveorm.password=" + password + "\n");
}
fw.close();
PersistenceManager persist = new PersistenceManager(filename);
persist.saveObject(new Object());
assertEquals(1,persist.getCount(Object.class, new All()));
persist.dropTable(Object.class);
persist.close();
FileInputStream fis = new FileInputStream(filename);
persist = new PersistenceManager(fis);
persist.saveObject(new Object());
assertEquals(1,persist.getCount(Object.class, new All()));
persist.dropTable(Object.class);
persist.close();
fis.close();
Properties prop = new Properties();
fis = new FileInputStream(filename);
prop.load(fis);
persist = new PersistenceManager(prop);
persist.saveObject(new Object());
assertEquals(1,persist.getCount(Object.class, new All()));
persist.dropTable(Object.class);
persist.close();
fis.close();
File f = new File(filename);
f.delete();
//check if exeptions are thrown at the right place
boolean thrown = false;
//no database
fw = new FileWriter(filename);
if (driver != null)
{
fw.write("com.github.conserveorm.driver=" + driver + "\n");
}
fw.write("com.github.conserveorm.username="+login+"\n");
fw.write("com.github.conserveorm.password="+password+"\n");
fw.close();
try
{
persist = new PersistenceManager(filename);
}
catch(SQLException e)
{
thrown = true;
}
finally
{
if(persist != null)
{
persist.close();
persist = null;
}
}
assertTrue("No exception on non-existing database.",thrown);
thrown =false;
f = new File(filename);
f.delete();
}
|
cd1f80cb-be6e-4c12-ad31-c84e200ce6c7
| 4
|
public void test_22() {
initSnpEffPredictor();
VariantFileIterator snpFileIterator;
snpFileIterator = new SeqChangeTxtFileIterator("tests/chr_not_found.out", config.getGenome());
snpFileIterator.setIgnoreChromosomeErrors(false);
boolean trown = false;
try {
// Read all SNPs from file. Note: This should throw an exception "Chromosome not found"
for (Variant seqChange : snpFileIterator) {
Gpr.debug(seqChange);
}
} catch (RuntimeException e) {
trown = true;
String expectedMessage = "ERROR: Chromosome 'chrZ' not found! File 'tests/chr_not_found.out', line 1";
if (e.getMessage().equals(expectedMessage)) ; // OK
else throw new RuntimeException("This is not the exception I was expecting!\n\tExpected message: '" + expectedMessage + "'\n\tMessage: '" + e.getMessage() + "'", e);
}
// If no exception => error
if (!trown) throw new RuntimeException("This should have thown an exception 'Chromosome not found!' but it didn't");
}
|
9d617f16-f4ff-486c-8c66-2cf612705313
| 8
|
private int rank(GoodsType g) {
return (!g.isStorable() || g.isTradeGoods()) ? -1
: (g.isFoodType()) ? 1
: (g.isNewWorldGoodsType()) ? 2
: (g.isFarmed()) ? 3
: (g.isRawMaterial()) ? 4
: (g.isNewWorldLuxuryType()) ? 5
: (g.isRefined()) ? 6
: -1;
}
|
d66c3255-c658-4650-951e-afa33f0e928f
| 3
|
public CheckField(boolean initialValue, Color bg, String fieldTitle, String checkboxFunction) {
if (bg == null) {
setBackground(Color.WHITE);
}
if (fieldTitle == null) {
fieldTitle = "";
}
if (checkboxFunction == null) {
checkboxFunction = "";
}
create(initialValue, bg, fieldTitle, checkboxFunction);
}
|
2cc9c196-9ecb-407b-8c29-34709fb114fb
| 2
|
public void doA08(MsgParse mp)
throws SQLException {
if (!mp.visit.getPatient_class().isEmpty())
try {
PreparedStatement prepStmt = connection.prepareStatement(
"update patient set "
+ "last_name = ?"
+ ", first_name = ?"
+ ", birth_date = ?"
+ ", sex_code = ?"
+ ", ethnic_code = ?"
+ ", address_line1 = ?"
+ ", address_line2 = ?"
+ ", address_city = ?"
+ ", address_state = ?"
+ ", address_zip = ?"
+ ", home_phone = ?"
+ ", work_phone = ?"
+ ", marital_code = ?"
+ ", religion_code = ?"
+ ", ssn = ? "
+ "where mrn = ? ");
prepStmt.setString(1, mp.patient.getLastName());
prepStmt.setString(2, mp.patient.getFirstName());
prepStmt.setString(3, mp.patient.getBirthDate());
prepStmt.setString(4, mp.patient.getSexCd());
prepStmt.setString(5, mp.patient.getEthnicCd());
prepStmt.setString(6, mp.patient.getAddress1());
prepStmt.setString(7, mp.patient.getAddress2());
prepStmt.setString(8, mp.patient.getCity());
prepStmt.setString(9, mp.patient.getState());
prepStmt.setString(10, mp.patient.getZip());
prepStmt.setString(11, mp.patient.getHomePhone());
prepStmt.setString(12, mp.patient.getWorkPhone());
prepStmt.setString(13, mp.patient.getMaritalCd());
prepStmt.setString(14, mp.patient.getReligionCd());
prepStmt.setString(15, mp.patient.getSSN());
prepStmt.setString(16, mp.patient.getMRN());
prepStmt.executeUpdate();
prepStmt.close();
} catch (SQLException se) {
System.out.println("Error in DBLoader.doA08: " + se);
}
}//doA08 - update patient information
|
d2612d0a-6350-401e-b53f-57a8bb6589b1
| 1
|
private void initialiserHeuresAccumulees() {
heuresAccumulees = new HashMap<>();
for (String categoriesReconnue : categoriesReconnues) {
heuresAccumulees.put(categoriesReconnue, 0);
}
}
|
dabeb069-53ef-44ba-bbfa-da3ac14c3080
| 7
|
public boolean start() {
synchronized (this.optOutLock) {
// Did we opt out?
if (this.isOptOut()) {
return false;
}
// Is metrics already running?
if (this.task != null) {
return true;
}
// Begin hitting the server with glorious data
this.task = this.plugin.getServer().getScheduler().runTaskTimerAsynchronously(this.plugin, new Runnable() {
private boolean firstPost = true;
public void run() {
try {
// This has to be synchronized or it can collide with the disable method.
synchronized (Metrics.this.optOutLock) {
// Disable Task, if it is running and the server owner decided to opt-out
if (Metrics.this.isOptOut() && Metrics.this.task != null) {
Metrics.this.task.cancel();
Metrics.this.task = null;
// Tell all plotters to stop gathering information.
for (Graph graph : Metrics.this.graphs) {
graph.onOptOut();
}
}
}
// We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING!
Metrics.this.postPlugin(!this.firstPost);
// After the first post we set firstPost to false
// Each post thereafter will be a ping
this.firstPost = false;
}
catch (IOException e) {
if (Metrics.this.debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
}
|
20fb021c-24cd-47e0-9b0c-3694cdf1c258
| 2
|
public void addNoInstrumentReg(String arg) {
String patternString = arg.substring(NO_INSTRUMENT_REG_PREFIX.length());
if (patternString.startsWith("/"))
patternString = patternString.substring(1);
try {
patternMatchers.add(PatternMatcherRegEx.getExcludePatternMatcher(patternString));
} catch(PatternSyntaxException e) {
e.printStackTrace(System.err);
setInvalid(format("Invalid pattern '%s'", patternString));
}
}
|
39c5cec0-f19f-4264-9c34-cba4a89fb356
| 4
|
public TabbedPanel(final JFrame frame) {
setLayout(new BorderLayout());
this.frame = frame;
final JTabbedPane tabbedPane = new JTabbedPane();
CijferOverzichtPanel coPanel = new CijferOverzichtPanel();
tabbedPane.addTab("Cijfer overzicht", coPanel);
if (Sessie.getIngelogdeGebruiker().isDocent()
|| Sessie.getIngelogdeGebruiker().isSuperUser()) {
KlasPanel klasPanel = new KlasPanel();
tabbedPane.addTab("Klas overzicht", klasPanel);
VakPanel vakPanel = new VakPanel();
tabbedPane.addTab("Vak overzicht", vakPanel);
ToetsPanel toetsPanel = new ToetsPanel();
tabbedPane.addTab("Toets overzicht", toetsPanel);
}
if (Sessie.getIngelogdeGebruiker().isSuperUser()) {
UserPanel docentPanel = new UserPanel();
tabbedPane.addTab("User overzicht", docentPanel);
RechtenPanel rechtenPanel = new RechtenPanel();
tabbedPane.addTab("Rechten & Permissies", rechtenPanel);
}
tabbedPane.setUI(new BasicTabbedPaneUI() {
@Override
protected int calculateTabHeight(int tabPlacement, int tabIndex,
int fontHeight) {
return 35;
}
});
tabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
RefreshPanel panel = (RefreshPanel) tabbedPane
.getSelectedComponent();
panel.refreshPanel();
if (Sessie.getIngelogdeGebruiker() == null) {
JOptionPane
.showMessageDialog(
null,
"De sessie is verlopen, u wordt teruggebracht naar het loginscherm.",
"Sessie verlopen",
JOptionPane.ERROR_MESSAGE);
frame.removeAll();
frame.getContentPane().add(new LoginScherm(frame));
frame.revalidate();
frame.repaint();
}
}
});
NaamPanel npanel = new NaamPanel(frame);
npanel.setBorder(new EmptyBorder(10, 5, 5, 20));
add(npanel, BorderLayout.NORTH);
add(tabbedPane, BorderLayout.CENTER);
}
|
4cdf0efd-6351-4b07-a213-aaab4b5a3d7d
| 1
|
public int countRows(String tableName) throws SQLException {
if (conn != null) {
PreparedStatement stmt = conn.prepareStatement(String.format("SELECT COUNT(*) AS rowcount FROM %s", tableName));
ResultSet rs = stmt.executeQuery();
rs.next();
return rs.getInt("rowcount");
}
return 0;
}
|
66a4eb93-1858-4b3c-a1b4-f14db15fbf39
| 2
|
private static Element findElement( Element root, String tag ) throws IOException
{
NodeList elements = root.getElementsByTagName( tag );
if (elements.getLength() == 0)
{
throw new IOException( "Tag " + tag + " was expected and not found." );
}
else if (elements.getLength() != 1)
{
throw new IOException( "Tag " + tag + " cannot have multiple definitions." );
}
return (Element)elements.item( 0 );
}
|
c601c0af-8674-48f7-814e-59a0578e9ee9
| 4
|
private boolean canMakeDocument() {
if (!domaineExists()) {
return false;
}
if (domaine.getCategoriesMotClef().size() > 0) {
for (CategorieMotClef c : domaine.getCategoriesMotClef()) {
if (c.getMotClefs().size() > 0) {
return true;
}
}
javax.swing.JOptionPane.showMessageDialog(MainWindow.this.frmDocumentmanager,"Vous devez créer au moins un mot clef.");
} else {
javax.swing.JOptionPane.showMessageDialog(MainWindow.this.frmDocumentmanager,"Vous devez créer au moins une catégorie de mot clef.");
}
return false;
}
|
001b6420-6c62-47fc-813c-67fb46c4032e
| 0
|
public OperatingSeat getSeat() {
return this._seat;
}
|
eb149da7-a007-4948-a926-81f865061ebd
| 7
|
private final void escapeAndAdd(StringBuffer sb, String text) {
// TODO: On the move to 1.5 use StringBuffer append() overloads that
// can take a CharSequence and a range of that CharSequence to speed
// things up.
//int last = 0;
int count = text.length();
for (int i=0; i<count; i++) {
char ch = text.charAt(i);
switch (ch) {
case '\t':
// Micro-optimization: for syntax highlighting with
// tab indentation, there are often multiple tabs
// back-to-back at the start of lines, so don't put
// spaces between each "\tab".
sb.append("\\tab");
while ((++i<count) && text.charAt(i)=='\t') {
sb.append("\\tab");
}
sb.append(' ');
i--; // We read one too far.
break;
case '\\':
case '{':
case '}':
sb.append('\\').append(ch);
break;
default:
sb.append(ch);
break;
}
}
}
|
ee7d71ae-cc56-4816-a647-5fd72bbeb3ce
| 1
|
public boolean mouseup(Coord c, int button) {
if (dm) {
ui.grabmouse(null);
dm = false;
storepos();
} else {
super.mouseup(c, button);
}
return (true);
}
|
37dd3d03-ab35-4b6d-b78c-53c1a2a4fe17
| 9
|
public void move(int direction)
{
if(direction == NORTH)
{
if(row != 0)
row--;
}
else if(direction == SOUTH)
{
if(row != cells-1)
row++;
}
else if(direction == WEST)
{
if(column != 0)
column--;
}
else if(direction == EAST)
{
if(column != cells-1)
column++;
}
else if(direction == RANDOM_SPOT)
{
//check to see if they have safe jumps left.
row = (int)(Math.random()*cells);
column =(int)(Math.random()*cells);
}
}
|
a4de80b2-7309-4d23-b9e2-60fc99c001cc
| 2
|
public File verificaArquivoDeConfiguracao() {
File xml = new File("config.xml");
if (xml.isFile() && xml.exists()) {
return xml;
} else {
return null;
}
}
|
ef0d0744-d299-45ab-ad8f-52768bf80e8b
| 7
|
private ByteBuffer retrieveMessage(
RetrieveMessageRequest retrieveMessageRequest, String address) {
// TODO: P1
ClientConnectionLogRecord record = new ClientConnectionLogRecord(
address, SystemEvent.RETRIEVE_MESSAGE,
"Received request to retrieve a message by "
+ retrieveMessageRequest.getFilterType().toString()
+ " ordered by "
+ retrieveMessageRequest.getOrderBy().toString()
+ " from " + address + ".");
LOGGER.log(record);
Connection conn = null;
try {
conn = dbConnectionDispatcher.retrieveDatabaseConnection();
boolean byQueue = retrieveMessageRequest.getFilterType() == Filter.QUEUE;
boolean byPrio = retrieveMessageRequest.getOrderBy() == Order.PRIORITY;
boolean isPop = retrieveMessageRequest.isPopMessage();
Message msg = RetrieveMessage.execute(client.getClientId(),
retrieveMessageRequest.getFilterValue(), byPrio, byQueue,
conn);
if (msg == null) {
conn.commit();
// TODO: P2a
record = new ClientConnectionLogRecord(Level.INFO, address,
SystemEvent.RETRIEVE_MESSAGE,
"Responded with failure to a retrieve message request from "
+ address + " because no message was found.",
record);
record.setSuccess(false);
LOGGER.log(record);
RequestResponse errorResponse = new RequestResponse(
Status.NO_MESSAGE);
return ProtocolMessage.toBytes(errorResponse);
} else {
// TODO: P2b
record = new ClientConnectionLogRecord(address,
SystemEvent.RETRIEVE_MESSAGE, "Found message "
+ msg.getId()
+ " filtered by "
+ retrieveMessageRequest.getFilterType()
.toString()
+ " ordered by "
+ retrieveMessageRequest.getOrderBy()
.toString() + " for " + address + ".",
record);
LOGGER.log(record);
if (isPop) {
DeleteMessage
.execute(msg.getId(), msg.getQueueName(), conn);
conn.commit();
// TODO: P3
record = new ClientConnectionLogRecord(address, SystemEvent.RETRIEVE_MESSAGE,
"Popped message " + msg.getId() + " from queue "
+ msg.getQueueName() + " for " + address
+ ".", record);
LOGGER.log(record);
} else {
conn.commit();
}
LOGGER.log(new ClientConnectionLogRecord(Level.INFO, address,
SystemEvent.RETRIEVE_MESSAGE, "Found and returned message "
+ msg.getId()
+ " filtered by "
+ retrieveMessageRequest.getFilterType()
.toString()
+ " ordered by "
+ retrieveMessageRequest.getOrderBy()
.toString() + " for " + address + ".",
record));
RetrieveMessageResponse messageResponse = new RetrieveMessageResponse(
msg);
return ProtocolMessage.toBytes(messageResponse);
}
} catch (SQLException e) {
LOGGER.log(new ClientConnectionLogRecord(address,
SystemEvent.RETRIEVE_MESSAGE,
"Caught exception while trying to retrieve message for "
+ address + ".", record, e));
RequestResponse errorResponse = new RequestResponse(
Status.EXCEPTION, e.toString());
if (conn != null)
try {
conn.rollback();
} catch (SQLException e1) {
logRollbackException(e1);
}
return ProtocolMessage.toBytes(errorResponse);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
logCloseException(e);
}
}
}
}
|
08f8d34b-2668-4353-9f97-b86acd24c0dd
| 9
|
private void invoke(final ObjectName name)
throws Exception
{
log.debug("Invoke " + name);
MBeanServerConnection server = getMBeanServer();
// get mbean info for this mbean
MBeanInfo info = server.getMBeanInfo(name);
// does it even have an operation of this name?
MBeanOperationInfo[] ops = info.getOperations();
MBeanOp inputOp = new MBeanOp(opName, opArgs.size());
MBeanOp matchOp = null;
ArrayList opList = new ArrayList();
for (int i = 0; i < ops.length; i++)
{
MBeanOperationInfo opInfo = ops[i];
MBeanOp op = new MBeanOp(opInfo.getName(), opInfo.getSignature());
if (inputOp.equals(op) == true)
{
matchOp = op;
break;
}
opList.add(op);
}
if (matchOp == null)
{
// If there was not explicit match on type, look for a match on arg count
OpCountComparator comparator = new OpCountComparator();
Collections.sort(opList, comparator);
int match = Collections.binarySearch(opList, inputOp, comparator);
if (match >= 0)
{
// Validate that the match op equates to the input op
matchOp = (MBeanOp) opList.get(match);
match = comparator.compare(matchOp, inputOp);
if (match != 0)
{
throw new CommandException("MBean has no such operation named '" +
opName + "' with signature compatible with: " + opArgs);
}
}
else
{
throw new CommandException("MBean has no such operation named '" +
opName + "' with signature compatible with: " + opArgs);
}
}
// convert parameters with PropertyEditor
int count = matchOp.getArgCount();
Object[] params = new Object[count];
for (int i = 0; i < count; i++)
{
String argType = matchOp.getArgType(i);
PropertyEditor editor = PropertyEditors.getEditor(argType);
editor.setAsText((String) opArgs.get(i));
params[i] = editor.getValue();
}
log.debug("Using params: " + Strings.join(params, ","));
// invoke the operation
Object result = server.invoke(name, opName, params, matchOp.getSignature());
log.debug("Raw result: " + result);
if (!context.isQuiet())
{
// Translate the result to text
String resultText = null;
if (result != null)
{
try
{
PropertyEditor editor = PropertyEditors.getEditor(result.getClass());
editor.setValue(result);
resultText = editor.getAsText();
log.debug("Converted result: " + resultText);
}
catch (RuntimeException e)
{
// No property editor found or some conversion problem
resultText = result.toString();
}
}
else
{
resultText = "'null'";
}
// render results to out
PrintWriter out = context.getWriter();
out.println(resultText);
out.flush();
}
closeServer();
}
|
c961e1d4-dd85-43f8-9769-d906b64e07f1
| 5
|
public boolean equalsMat( MVMaterial mat ){
return (mat.ignoreData&&mat.id==id) || (ignoreData&&mat.id==id) || (mat.data==data && mat.id==id);
}
|
63510191-4efa-4c33-a5df-c8b54fe6cd35
| 5
|
*/
public byte[] getOriginator() {
//return mesh address if available
if(sixLoWPANpacket != null && sixLoWPANpacket.isMeshHeader()){
return sixLoWPANpacket.getOriginatorAddress();
//else look for an existing sixlowpan address
} else if(sixLoWPANpacket != null && sixLoWPANpacket.isIphcHeader() && sixLoWPANpacket.getSource() != null){
return sixLoWPANpacket.getSource();
//otherwise it's really just null
} else {
return null;
}
}
|
41e0551e-76f1-43e6-9cae-ca88f9a30b46
| 9
|
public void handEndHandler(){
if (player.didSplit == false){//if they didn't split
player.total = totalCards(player.cards, player.total, "player");
dealerTotal = totalCards(cards, dealerTotal, "dealer");
if (dealerTotal > player.total){
System.out.println("Dealer wins with " + dealerTotal + ". You had " + player.total + ".");
outOfMoney();//see if they are out of money
}else if(dealerTotal < player.total){
System.out.println("Congrats! You win!");
player.totalMoney += (player.bet * 2);//match their bet and add it to their total
}else {
System.out.println("You and the dealer tie at " + player.total + ".");
player.totalMoney += player.bet;
}
}else{//if they did split
player.h1Total = totalCards(player.hand1, player.h1Total, "player");
player.h2Total = totalCards(player.hand2, player.h2Total, "player");
//hand 1 calculation
if (player.h1Total > 21){
System.out.println("You bust on hand one with " + player.h1Total);
}else{
if (dealerTotal > player.h1Total){
System.out.println("Dealer wins on hand 1 with " + dealerTotal + ". You had " + player.h1Total + ".");
sleep(1000);
}else if(dealerTotal < player.h1Total){
System.out.println("Congrats! You win on hand 1!");
player.totalMoney += (player.bet * 2);//match their bet and add it to their total
sleep(1000);
}else {
System.out.println("You and the dealer tie at " + player.h1Total + ".");
player.totalMoney += player.bet;
sleep(1000);
}
}
//hand 2 calculation
if (player.h2Total > 21){
System.out.println("You bust on hand two with " + player.h2Total);
}else{
if (dealerTotal > player.h2Total){
System.out.println("Dealer wins on hand 2 with " + dealerTotal + ". You had " + player.h2Total + ".");
sleep(1000);
}else if(dealerTotal < player.h2Total){
System.out.println("Congrats! You win on hand 2!");
player.totalMoney += (player.bet * 2);//match their bet and add it to their total
sleep(1000);
}else {
System.out.println("You and the dealer tie at " + player.h2Total + ".");
player.totalMoney += player.bet;
sleep(1000);
}
}
}
playAgain();
}
|
0a1d5e5e-663c-4d8c-a855-34c4d6c70b0d
| 5
|
private void updateZebraColors( )
{
if ( (rowColors[0] = getBackground( )) == null )
{
rowColors[0] = rowColors[1] = java.awt.Color.white;
return;
}
final java.awt.Color sel = getSelectionBackground( );
if ( sel == null )
{
rowColors[1] = rowColors[0];
return;
}
final float[] bgHSB = java.awt.Color.RGBtoHSB(
rowColors[0].getRed( ), rowColors[0].getGreen( ),
rowColors[0].getBlue( ), null );
final float[] selHSB = java.awt.Color.RGBtoHSB(
sel.getRed( ), sel.getGreen( ), sel.getBlue( ), null );
rowColors[1] = java.awt.Color.getHSBColor(
(selHSB[1]==0.0||selHSB[2]==0.0) ? bgHSB[0] : selHSB[0],
0.1f * selHSB[1] + 0.9f * bgHSB[1],
bgHSB[2] + ((bgHSB[2]<0.5f) ? 0.05f : -0.05f) );
}
|
01579ffc-c106-487a-8cc3-3129390ec4bc
| 2
|
private URLConnection openClassfile0(String classname) throws IOException {
if (packageName == null || classname.startsWith(packageName)) {
String jarname
= directory + classname.replace('.', '/') + ".class";
return fetchClass0(hostname, port, jarname);
}
else
return null; // not found
}
|
004b408b-8350-474a-8cdb-91985417e7c3
| 6
|
public boolean isFeasible(Coordinate c) {
boolean validI = c.i >= 0 && c.i < size;
boolean validJ = c.j >= 0 && c.j < size;
boolean validCell = false;
if (validI && validJ) {
validCell = (maze.get(c.i).get(c.j).val == 0);
}
return validI && validJ && validCell;
}
|
eb4d6222-1114-4f95-9fe7-6a88cd33dc90
| 2
|
@Override
public boolean execute() {
try {
/* Always delete in reverse order */
int i = this.endAt;
while (i >= this.startFrom) {
this.document.remove(i);
i--;
}
return true;
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
|
c50af12d-4b17-42d9-bc54-bea3094cc6ce
| 2
|
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// counter.setSharedCounter(counter.getSharedCounter()+1);
int val = counter.incrementAndGet();
System.out.println("Thread name=" + Thread.currentThread().getName() +", id=" + Thread.currentThread().getId()+ ", counter = " + val);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
|
02125378-2de5-4336-92a8-fc5e662e37d5
| 4
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Item other = (Item) obj;
if (id != other.id)
return false;
return true;
}
|
695041fe-7030-4533-bbba-8f7b79772fd3
| 5
|
public static void main(String[] args) {
int valorx,valory,r;
valorx=Integer.parseInt(JOptionPane.showInputDialog("Ingrese el valor del entero X"));
valory=Integer.parseInt(JOptionPane.showInputDialog("Ingrese el valor del entero Y"));
if (valorx<=0 || valorx>255)
{
r=-1;
JOptionPane.showMessageDialog(null,"Resultado "+r);
}
else
{
int[] arreglo=new int[valory];
arreglo[0]=valorx;
for (int i = 1; i < arreglo.length; i++)
{
valorx = valorx*(i+1);
arreglo[i] = valorx;
System.out.println(i+" "+arreglo[i]);
}
for (int i = 0; i < arreglo.length; i++)
{
if(i==(valory-1))
{
r=arreglo[i];
JOptionPane.showMessageDialog(null,"Resultado "+r);
}
}
}
}
|
57fa948c-21ed-4992-92ae-438e41117efe
| 6
|
@Override
public Staff find(int id) {
Staff found = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst=this.connect().prepareStatement("select * from Staff where id= ?");
pst.setInt(1, id);
rs=pst.executeQuery();
System.out.println("recherche individuelle réussie");
if (rs.next()) {
found = new Staff(rs.getInt("id"), rs.getString("fonction"), rs.getString("nom"), rs.getString("prenom"), rs.getInt("age"));
}
} catch (SQLException ex) {
Logger.getLogger(StaffDao.class.getName()).log(Level.SEVERE, "recherche individuelle echoué", ex);
}finally{
try {
if (rs != null)
rs.close();
} catch (SQLException ex) {
Logger.getLogger(StaffDao.class.getName()).log(Level.SEVERE, "liberation result set echoué", ex);
}
try {
if (pst != null)
pst.close();
} catch (SQLException ex) {
Logger.getLogger(StaffDao.class.getName()).log(Level.SEVERE, "liberation prepared statement echoué", ex);
}
}
return found;
}
|
76a252d5-09a8-4656-94f9-02a591e6d680
| 6
|
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
vasen = true;
if (ensiksiPainettu == Painike.NULL) {
ensiksiPainettu = Painike.VASEN;
}
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
oikea = true;
if (ensiksiPainettu == Painike.NULL) {
ensiksiPainettu = Painike.OIKEA;
}
}
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
hyppy = true;
}
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
pelaaja.lopetaTaso();
}
kutsuMetodeja();
}
|
df81e05b-7c1a-4922-8a74-831893dc42bb
| 0
|
public static void main(String[] args){
new Lanceur();
}
|
746125c9-3db3-4b98-8732-d49e3f49cab4
| 1
|
public void setVolume(String soundName, double volume) {
Sound sound = sounds.get(soundName);
if (sound != null) {
sound.setVolume(volume);
}
}
|
5c3a197f-e5de-4b34-a4f4-bed358cd80ad
| 1
|
public String coder()
{
this.completeTabFrequence();
this.sortTabFrequence();
this.initTree();
this.buildTree();
this.tabBinary = this.lstArbre.get(0).codageTabBinary();
String chaineCoder = "";
for (int code : this.encoding) {
chaineCoder += this.codage(code);
}
return chaineCoder;
}
|
9c710dfb-b8f6-441d-84d1-5b209c6a1bc9
| 6
|
public void setSize(int new_size) {
if (item_names != null) {
String[] new_item_names = new String[new_size];
for (int i = 0; i < new_size; i++) {
if (i < size) {
new_item_names[i] = item_names[i];
} else {
new_item_names[i] = item_names[size - 1];
}
}
item_names = null;
item_names = new_item_names;
}
if (item_desc != null) {
String[] new_item_desc = new String[new_size];
for (int i = 0; i < new_size; i++) {
if (i < size) {
new_item_desc[i] = item_desc[i];
} else {
new_item_desc[i] = item_desc[size - 1];
}
}
item_desc = null;
item_desc = new_item_desc;
}
size = new_size;
}
|
4ba073dd-be39-4a56-bf1f-50099b48edea
| 2
|
public void update(GameContainer gc, StateBasedGame sbg, int delta) {
//Checks to see whether owner has reached end of path and needs to turn around.
distance += speed*delta;
if (distance > range){
distance = 0;
isForward = !isForward;
}
//Updates position based on current travel path.
if (isForward){
owner.addX((float)Math.cos(Math.toRadians(rotation))*speed*delta);
owner.addY((float)Math.sin(Math.toRadians(rotation))*speed*delta);
}
else{
owner.addX((float)Math.cos(Math.toRadians(rotation))*speed*delta*-1);
owner.addY((float)Math.sin(Math.toRadians(rotation))*speed*delta*-1);
}
}
|
d89bb12b-6505-47b1-8b13-de2e3bfd1796
| 5
|
public static void paintStory(BufferedImage image, Movie movie)
{
Graphics2D g2 = (Graphics2D) image.getGraphics();
g2.setFont(Constants.fontStory);
FontMetrics fm = g2.getFontMetrics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
String[] words = movie.getStory().split(" ");
int lineNumber = 1;
int xBase;
if (movie.getCover()==null) {
xBase = Constants.MARGIN;
} else {
xBase = Constants.MARGIN*2 + movie.getCover().getWidth();
}
int y =
Constants.MARGIN*3 +
g2.getFontMetrics(Constants.fontTitle).getHeight() +
Constants.INNER_MARGIN*2 +
g2.getFontMetrics(Constants.fontGenre).getHeight() - 15;
int x = xBase;
for (String word : words)
{
String work = word.trim();
if (work.length()>0)
{
String txt = word.replaceAll("\n","") + " ";
int width = fm.stringWidth(txt);
if ((x + width + Constants.MARGIN) > Constants.WIDTH)
{
lineNumber++;
x = lineNumber<5 ? xBase : Constants.MARGIN;
y += fm.getAscent() + Constants.INNER_MARGIN;
}
g2.drawString(txt, x, y);
x+=width;
}
}
}
|
c73e663b-7365-4d3c-8ea7-8847eeccaebc
| 9
|
public boolean skipPast(String to) throws JSONException {
boolean b;
char c;
int i;
int j;
int offset = 0;
int n = to.length();
char[] circle = new char[n];
/*
* First fill the circle buffer with as many characters as are in the
* to string. If we reach an early end, bail.
*/
for (i = 0; i < n; i += 1) {
c = next();
if (c == 0) {
return false;
}
circle[i] = c;
}
/*
* We will loop, possibly for all of the remaining characters.
*/
for (;;) {
j = offset;
b = true;
/*
* Compare the circle buffer with the to string.
*/
for (i = 0; i < n; i += 1) {
if (circle[j] != to.charAt(i)) {
b = false;
break;
}
j += 1;
if (j >= n) {
j -= n;
}
}
/*
* If we exit the loop with b intact, then victory is ours.
*/
if (b) {
return true;
}
/*
* Get the next character. If there isn't one, then defeat is ours.
*/
c = next();
if (c == 0) {
return false;
}
/*
* Shove the character in the circle buffer and advance the
* circle offset. The offset is mod n.
*/
circle[offset] = c;
offset += 1;
if (offset >= n) {
offset -= n;
}
}
}
|
e7d663ad-7125-4469-87e0-47f844f1081d
| 1
|
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
|
3a1e4d22-351d-453d-8ae7-5e8d8cbe4a26
| 2
|
@Override
public void mousePressed(MouseEvent mouseEvent) {
if(mouseEvent.getX()<100 && mouseEvent.getY() < 140)
daVisualizzare();
else visualizzata=null;
}
|
b370447b-6228-45ec-bacd-728156ec81c9
| 2
|
public Bernoulli(double p) throws ParameterException {
if (p < 0 || p > 1) {
throw new ParameterException("Bernoulli parameter 0 <= p <= 1.");
} else {
this.p = p;
}
}
|
9301ad04-1b1f-428d-90b3-3cfaf9ea66cb
| 1
|
public final void setCurrentServerIndex(int currentServer) {
if(currentServer < Settings.serversCount)
this.serverBox.setSelectedIndex(currentServer);
}
|
663b5af1-52dc-4785-9496-6fe1a13061f8
| 1
|
public Client() {
_scanner = new Scanner(System.in);
try {
UnicastRemoteObject.exportObject(this, 0);
_instance = this;
} catch(RemoteException ex) {
System.out.println(ex.getMessage());
}
_username = "";
_password = "";
}
|
4aa6249b-3d01-4eac-8e0d-19f84b9fd40b
| 4
|
public void reset() {
for (int x = 0; x < cells.length; x++) {
for (int y = 0; y < cells[x].length; y++) {
cells[x][y] = new Cell(x, y);
cells[x][y].setScreenX(10 + x * 13);
cells[x][y].setScreenY(10 + y * 13);
}
}
for (int x = 0; x < cells.length; x++) {
for (int y = 0; y < cells[x].length; y++) {
findNeighbors(cells[x][y], x, y);
}
}
}
|
b942b81e-91c5-45f9-b73f-eeab7125b6b4
| 7
|
public void run() {
onStart();
while (true) {
List<WebURL> assignedURLs = new ArrayList<>(50);
isWaitingForNewURLs = true;
frontier.getNextURLs(50, assignedURLs);
isWaitingForNewURLs = false;
if (assignedURLs.size() == 0) {
if (frontier.isFinished()) {
return;
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
for (WebURL curURL : assignedURLs) {
if (curURL != null) {
processPage(curURL);
frontier.setProcessed(curURL);
}
if (myController.isShuttingDown()) {
logger.info("Exiting because of controller shutdown.");
return;
}
}
}
}
}
|
92952800-c1e8-47d9-8698-d81f87fb9b69
| 6
|
public void setMode(int mode) throws ParserConfigurationException,
TransformerException, IOException, SAXException {
if (this.mode == GeneralDestruction.MODE_EDITOR && mode == MODE_GAME) {
this.mode = mode;
gui.setMode(mode);
if (currentPath != null) {
saveTo(currentPath);
initialize(currentPath);
}
} else if (this.mode == GeneralDestruction.MODE_GAME
&& mode == MODE_EDITOR) {
this.mode = mode;
gui.setMode(mode);
if (currentPath != null) {
initialize(currentPath);
}
}
}
|
fae4ad2b-a606-4e3f-9a9a-17a01e65d611
| 3
|
public void init() {
setSize(700, 400);
setLayout(new BorderLayout()); // JFrame layout
lblStatus = new JLabel(sMessage);
lblMoney = new JLabel(sMoney);
lblBet = new JLabel(sBet);
txtMoney = new JTextField("", 4);
arLblPlayer = new JLabel[6];
arLblDealer = new JLabel[6];
panBoard = new JPanel(new GridLayout(2, 6)); // 2 players - up to 6 cards each
panInput = new JPanel(); // defaults to FlowLayout
panEast = new JPanel();
add(lblStatus, BorderLayout.NORTH);
add(panEast, BorderLayout.EAST);
add(panBoard, BorderLayout.CENTER);
add(panInput, BorderLayout.SOUTH);
for (int i = 0; i < 6; i++) {
arLblPlayer[i] = new JLabel();
arLblDealer[i] = new JLabel();
}
for (int i = 0; i < 6; i++) {
panBoard.add(arLblDealer[i]);
}
for (int i = 0; i < 6; i++) {
panBoard.add(arLblPlayer[i]);
}
btnHit = new JButton("Hit!");
btnHit.addActionListener(new HitActionListener());
btnStand = new JButton("Stand!");
btnStand.addActionListener(new StandActionListener());
btnNewGame = new JButton("New game");
btnNewGame.addActionListener(new NewgameActionListener());
btnBet = new JButton("Bet");
btnBet.addActionListener(new BetActionListener());
panInput.add(btnBet);
panEast.add(txtMoney);
panEast.add(lblMoney);
panEast.add(lblBet);
sBet = "0";
sMoney = "Money: $" + nTotal;
}
|
2b664917-8c08-47ae-a28e-eb33b5e29bde
| 9
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Carnivoro other = (Carnivoro) obj;
if (anni != other.anni)
return false;
if (forza != other.forza)
return false;
if (livelloCibo != other.livelloCibo)
return false;
if (posizione == null) {
if (other.posizione != null)
return false;
} else if (!posizione.equals(other.posizione))
return false;
return true;
}
|
4cafbd6c-91a0-4ed4-a934-0dfe07efef61
| 5
|
public static String escape(String string) {
StringBuffer sb = new StringBuffer();
for (int i = 0, len = string.length(); i < len; i++) {
char c = string.charAt(i);
switch (c) {
case '&':
sb.append("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '"':
sb.append(""");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
|
5605cf50-0678-4d2b-8151-bb037ad61591
| 3
|
public void setAPasso(TNumeroInt node)
{
if(this._aPasso_ != null)
{
this._aPasso_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._aPasso_ = node;
}
|
4087505c-2904-42a4-8afe-414af4122274
| 2
|
public static boolean isUnderline(JTextPane pane)
{
AttributeSet attributes = pane.getInputAttributes();
if (attributes
.containsAttribute(StyleConstants.Underline, Boolean.TRUE))
{
return true;
}
if (attributes.getAttribute(CSS.Attribute.TEXT_DECORATION) != null)
{
Object fontWeight = attributes
.getAttribute(CSS.Attribute.TEXT_DECORATION);
return fontWeight.toString().equals("underline");
}
return false;
}
|
c589d05f-f249-43f0-9ac0-07af5e30bb82
| 5
|
public boolean right() {
for(boolean[] position : emplacement.getCoordoneeJeu())
if(position[emplacement.getNombreColonne()-1]==true)
return false;
for(boolean[] position : emplacement.getCoordoneeJeu())
for(int x=emplacement.getNombreColonne()-1; x>=0; x--)
if (position[x] == true){
position[x] = false;
position[x+1]= true;
}
return true;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.