text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public Set<Map.Entry<Float,Character>> entrySet() {
return new AbstractSet<Map.Entry<Float,Character>>() {
public int size() {
return _map.size();
}
public boolean isEmpty() {
return TFloatCharMapDecorator.this.isEmpty();
}
public boolean contains( Object o ) {
if (o instanceof Map.Entry) {
Object k = ( ( Map.Entry ) o ).getKey();
Object v = ( ( Map.Entry ) o ).getValue();
return TFloatCharMapDecorator.this.containsKey(k)
&& TFloatCharMapDecorator.this.get(k).equals(v);
} else {
return false;
}
}
public Iterator<Map.Entry<Float,Character>> iterator() {
return new Iterator<Map.Entry<Float,Character>>() {
private final TFloatCharIterator it = _map.iterator();
public Map.Entry<Float,Character> next() {
it.advance();
float ik = it.key();
final Float key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik );
char iv = it.value();
final Character v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv );
return new Map.Entry<Float,Character>() {
private Character val = v;
public boolean equals( Object o ) {
return o instanceof Map.Entry
&& ( ( Map.Entry ) o ).getKey().equals(key)
&& ( ( Map.Entry ) o ).getValue().equals(val);
}
public Float getKey() {
return key;
}
public Character getValue() {
return val;
}
public int hashCode() {
return key.hashCode() + val.hashCode();
}
public Character setValue( Character value ) {
val = value;
return put( key, value );
}
};
}
public boolean hasNext() {
return it.hasNext();
}
public void remove() {
it.remove();
}
};
}
public boolean add( Map.Entry<Float,Character> o ) {
throw new UnsupportedOperationException();
}
public boolean remove( Object o ) {
boolean modified = false;
if ( contains( o ) ) {
//noinspection unchecked
Float key = ( ( Map.Entry<Float,Character> ) o ).getKey();
_map.remove( unwrapKey( key ) );
modified = true;
}
return modified;
}
public boolean addAll( Collection<? extends Map.Entry<Float, Character>> c ) {
throw new UnsupportedOperationException();
}
public void clear() {
TFloatCharMapDecorator.this.clear();
}
};
}
| 8 |
public JSONArray getJSONArray(String key) throws JSONException {
Object object = this.get(key);
if (object instanceof JSONArray) {
return (JSONArray) object;
}
throw new JSONException("JSONObject[" + quote(key)
+ "] is not a JSONArray.");
}
| 1 |
public void setName(String name) {
this.name = name;
setDirty();
}
| 0 |
public void secureDatabase() {
logger.debug("<<<< DatabasePasswordSecurerBean is running!!! >>>>>");
getJdbcTemplate().query("select username, password, password_encrypted from r_user", new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
String username = rs.getString(1);
String password = rs.getString(2);
boolean passwordEncrypted = rs.getBoolean(3);
UserDetails user = userDetailsService.loadUserByUsername(username);
String encodedPassword = passwordEncoder.encodePassword(password, saltSource.getSalt(user));
if (encodedPassword != null && !encodedPassword.equals(password) && !passwordEncrypted) {
getJdbcTemplate().update(
"update r_user set password = ?, password_encrypted = ? where username = ?",
encodedPassword, Boolean.TRUE, username);
logger.debug("Updating password for username:" + username + " to: " + encodedPassword);
}
}
});
}
| 3 |
public int compare(String o1, String o2)
{
String s1 = (String)o1;
String s2 = (String)o2;
int thisMarker = 0;
int thatMarker = 0;
int s1Length = s1.length();
int s2Length = s2.length();
while (thisMarker < s1Length && thatMarker < s2Length)
{
String thisChunk = getChunk(s1, s1Length, thisMarker);
thisMarker += thisChunk.length();
String thatChunk = getChunk(s2, s2Length, thatMarker);
thatMarker += thatChunk.length();
// If both chunks contain numeric characters, sort them numerically
int result = 0;
if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0)))
{
// Simple chunk comparison by length.
int thisChunkLength = thisChunk.length();
result = thisChunkLength - thatChunk.length();
// If equal, the first different number counts
if (result == 0)
{
for (int i = 0; i < thisChunkLength; i++)
{
result = thisChunk.charAt(i) - thatChunk.charAt(i);
if (result != 0)
{
return result;
}
}
}
} else
{
result = thisChunk.compareTo(thatChunk);
}
if (result != 0)
return result;
}
return s1Length - s2Length;
}
| 8 |
public String echoIP(ClientInterface client) {
this.client = client;
//System.out.println(client.name);
try {
System.out.println("The score on the client is " + client.findScore());
} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String remoteClient = null;
try {
remoteClient = RemoteServer.getClientHost().toString();
} catch (ServerNotActiveException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return remoteClient;
}
| 2 |
public Collection<Category> getCategories() {
if (categories == null)
try {
execute();
} catch (SQLException e) {
e.printStackTrace();
}
TreeSet<Category> ret = new TreeSet<Category>();
if (categories != null)
ret.addAll(categories.values());
return ret;
}
| 3 |
public boolean hasCycle(ListNode head) {
if (head == null) {
return false;
}
ListNode fast = head, slow = head;
do {
if (fast.next == null || fast.next.next == null) {
return false;
}
fast = fast.next.next;
slow = slow.next;
} while (fast != slow);
return true;
}
| 4 |
@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 Teacher)) {
return false;
}
Teacher other = (Teacher) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
| 5 |
private boolean handleMaintenance() {
if (plugin.maintenanceEnabled != true) {
plugin.maintenanceEnabled = true;
plugin.config.set("maintenancemode", true);
for (ProxiedPlayer player : ProxyServer.getInstance().getPlayers()) {
if (!player.hasPermission("bungeeutils.bypassmaintenance")) {
player.disconnect(plugin.messages.get(EnumMessage.KICKMAINTENANCE));
}
}
return true;
} else {
plugin.maintenanceEnabled = false;
plugin.config.set("maintenancemode", false);
return false;
}
}
| 3 |
private static List<String> compactLines(List<String> srcLines, int requiredLineNumber) {
if (srcLines.size() < 2 || srcLines.size() <= requiredLineNumber) {
return srcLines;
}
List<String> res = new LinkedList<>(srcLines);
// first join lines with a single { or }
for (int i = res.size()-1; i > 0 ; i--) {
String s = res.get(i);
if (s.trim().equals("{") || s.trim().equals("}")) {
res.set(i-1, res.get(i-1).concat(s));
res.remove(i);
}
if (res.size() <= requiredLineNumber) {
return res;
}
}
// now join empty lines
for (int i = res.size()-1; i > 0 ; i--) {
String s = res.get(i);
if (s.trim().isEmpty()) {
res.set(i-1, res.get(i-1).concat(s));
res.remove(i);
}
if (res.size() <= requiredLineNumber) {
return res;
}
}
return res;
}
| 9 |
private boolean hasEveryLightGrenadePositionOnlyOneLightGrenade(Grid grid) {
List<LightGrenade> lightGrenades = getLightGrenadesOfGrid(grid);
for (LightGrenade lg : lightGrenades) {
final Position lgPos = grid.getElementPosition(lg);
for (Element e : grid.getElementsOnPosition(lgPos))
if (e instanceof LightGrenade && e != lg)
return false;
}
return true;
}
| 4 |
public static void readFileTest(){
List<String> list = new LinkedList<String>();
while(true){
list.add(java.util.UUID.randomUUID().toString());
}
}
| 1 |
private void run(){
int frames = 0;
double frameCounter = 0;
double lastTime = Time.getTime();
double unprocessedTime = 0;
while (running){
boolean render = false;
double startTime = Time.getTime();
double passedTime = startTime - lastTime;
lastTime = startTime;
unprocessedTime += passedTime;
frameCounter += passedTime;
while (unprocessedTime > frameTime){
render = true;
unprocessedTime -= frameTime;
if (Window.isCloseRequested())
stop();
Input.update();
screen.update((float)frameTime);
if (frameCounter >= 1.0){
System.out.println("FPS: " + frames);
frames = 0;
frameCounter = 0;
}
}
if (render){
glClearColor(0.7f, 0.7f, 0.7f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// glLoadIdentity();
screen.render();
Window.render();
frames++;
}else {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
cleanUp();
}
| 6 |
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
ArrayList<Integer> numList = new ArrayList<Integer>();
do {
numList.add(input.nextInt());
} while (numList.get(numList.size()-1) != 0);
numList.remove(numList.size()-1);
for (int i = 0; i < numList.size(); i++) {
boolean prime = true;
boolean perfect = true;
int number = numList.get(i);
prime = isPrime(number);
perfect = isPerfect(number, prime);
if(!prime && !perfect)
System.out.println("Dull");
else if(prime && !perfect)
System.out.println("Prime");
else if(!prime && perfect)
System.out.println("Perfect");
else
System.out.println("This program doesn't work");
}
return;
}
| 8 |
@Override
public void doChangeContrast(int contrastAmountNum) {
if (imageManager.getBufferedImage() == null)
return;
double c = contrastAmountNum;
double q = (c + 100) / 100;
WritableRaster raster = imageManager.getBufferedImage().getRaster();
double[][] newPixels = new double[raster.getWidth()][raster.getHeight()];
for (int x = 0; x < raster.getWidth(); x++) {
for (int y = 0; y < raster.getHeight(); y++) {
double[] pixel = new double[3];
raster.getPixel(x, y, pixel);
pixel[0] = q*q*q*q * (pixel[0] - 128) + 128;
if (pixel[0] > 255)
pixel[0] = 255;
else if (pixel[0] < 0)
pixel[0] = 0;
newPixels[x][y] = pixel[0];
}
}
for (int x = 1; x < raster.getWidth() - 1; x++) {
for (int y = 1; y < raster.getHeight() - 1; y++) {
double[] pixel = new double[3];
pixel[0] = pixel[1] = pixel[2] = newPixels[x][y];
raster.setPixel(x, y, pixel);
}
}
GUIFunctions.refresh();
}
| 7 |
public ResultSet ExecuteQuery(String query) {
Statement st;
if (!IsConnected) { return null; }
try {
st = Conn.createStatement();
plugin.Debug("SQL Query: " + query);
return st.executeQuery(query);
} catch (SQLException e) {
plugin.Warn("Query execution failed!");
plugin.Log("SQL: " + query);
e.printStackTrace();
return null;
}
}
| 2 |
private static void readMagicItemsFromFileToArray(String fileName,
Items[] items) {
File myFile = new File(fileName);
try {
int itemCount = 0;
Scanner input = new Scanner(myFile);
while (input.hasNext() && itemCount < items.length) {
// Read a line from the file.
String itemName = input.nextLine();
// Construct a new list item and set its attributes.
Items fileItem = new Items();
fileItem.setItemName(itemName);
fileItem.setCost(Math.random() * 10);
fileItem.setNext(null); // Still redundant. Still safe.
// Add the newly constructed item to the array.
items[itemCount] = fileItem;
itemCount = itemCount + 1;
}
// Close the file.
input.close();
} catch (FileNotFoundException ex) {
System.out.println("File not found. " + ex.toString());
}
}
| 3 |
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (first == null)
{
if (other.first != null)
return false;
} else if (!first.equals(other.first))
return false;
if (second == null)
{
if (other.second != null)
return false;
} else if (!second.equals(other.second))
return false;
return true;
}
| 9 |
public List<String> databaseMedicineInfo(String columnName) throws SQLException{
List<String> medicineName=new ArrayList();
List<Float> medicinePrice=new ArrayList();
try{
databaseConnector=myConnector.getConnection();
stmnt=(Statement) databaseConnector.createStatement();
SQLQuery="SELECT * FROM familydoctor.medicine";
dataSet=stmnt.executeQuery(SQLQuery);
while(dataSet.next()){
name=dataSet.getString(columnName);
medicineName.add(name);
}
}
catch(SQLException e){
System.out.println(e.getMessage());
}
finally{
if(stmnt!=null)
stmnt.close();
if(databaseConnector!=null)
databaseConnector.close();
}
return medicineName;
}
| 4 |
public int minDistance(String word1, String word2) {
// Start typing your Java solution below
// DO NOT write main() function
int m = word1.length();
int n = word2.length();
int[][] res = new int[m + 1][];
int i = 0, j = 0;
for (i = 0; i < m + 1; i++)
res[i] = new int[n + 1];
for (i = 0; i < m + 1; i++)
res[i][n] = m - i;
for (i = 0; i < n + 1; i++)
res[m][i] = n - i;
for (i = m - 1; i >= 0; i--) {
for (j = n - 1; j >= 0; j--) {
if (word1.charAt(i) == word2.charAt(j))
res[i][j] = res[i + 1][j + 1];
else {
int tmp = Math.min(res[i + 1][j], res[i + 1][j + 1]);
res[i][j] = 1 + Math.min(tmp, res[i][j + 1]);
}
}
}
return res[0][0];
}
| 6 |
public static SoundManager getInstance()
{
return ourInstance;
}
| 0 |
protected void prepare_sample_reading(Header header, int allocation,
//float[][] groupingtable,
int channel,
float[] factor, int[] codelength,
float[] c, float[] d)
{
int channel_bitrate = header.bitrate_index();
// calculate bitrate per channel:
if (header.mode() != Header.SINGLE_CHANNEL)
if (channel_bitrate == 4)
channel_bitrate = 1;
else
channel_bitrate -= 4;
if (channel_bitrate == 1 || channel_bitrate == 2)
{
// table 3-B.2c or 3-B.2d
groupingtable[channel] = table_cd_groupingtables[allocation];
factor[0] = table_cd_factor[allocation];
codelength[0] = table_cd_codelength[allocation];
c[0] = table_cd_c[allocation];
d[0] = table_cd_d[allocation];
}
else
{
// tables 3-B.2a or 3-B.2b
if (subbandnumber <= 2)
{
groupingtable[channel] = table_ab1_groupingtables[allocation];
factor[0] = table_ab1_factor[allocation];
codelength[0] = table_ab1_codelength[allocation];
c[0] = table_ab1_c[allocation];
d[0] = table_ab1_d[allocation];
}
else
{
groupingtable[channel] = table_ab234_groupingtables[allocation];
if (subbandnumber <= 10)
{
factor[0] = table_ab2_factor[allocation];
codelength[0] = table_ab2_codelength[allocation];
c[0] = table_ab2_c[allocation];
d[0] = table_ab2_d[allocation];
}
else if (subbandnumber <= 22)
{
factor[0] = table_ab3_factor[allocation];
codelength[0] = table_ab3_codelength[allocation];
c[0] = table_ab3_c[allocation];
d[0] = table_ab3_d[allocation];
}
else
{
factor[0] = table_ab4_factor[allocation];
codelength[0] = table_ab4_codelength[allocation];
c[0] = table_ab4_c[allocation];
d[0] = table_ab4_d[allocation];
}
}
}
}
| 7 |
private boolean convertYUV422toRGB(int[] y, int[] u, int[] v, int[] rgb)
{
if (this.upSampler != null)
{
// Requires u & v of same size as y
this.upSampler.superSampleHorizontal(u, u);
this.upSampler.superSampleHorizontal(v, v);
return this.convertYUV444toRGB(y, u, v, rgb);
}
final int half = this.width >> 1;
final int rgbOffs = this.offset;
int oOffs = 0;
int iOffs = 0;
int k = 0;
for (int j=0; j<this.height; j++)
{
for (int i=0; i<half; i++)
{
int r, g, b, yVal, uVal, vVal;
final int idx = oOffs + i + i;
// ------- toRGB 'Macro'
yVal = y[k++] << 16; uVal = u[iOffs+i] - 128; vVal = v[iOffs+i] - 128;
r = yVal + 91881*vVal;
g = yVal - 22554*uVal - 46802*vVal;
b = yVal + 116130*uVal;
if (r >= 16678912) r = 0x00FF0000;
else { r &= ~(r >> 31); r = (r + 32768) >> 16; r <<= 16; }
if (g >= 16678912) g = 0x0000FF00;
else { g &= ~(g >> 31); g = (g + 32768) >> 16; g <<= 8; }
if (b >= 16678912) b = 0x000000FF;
else { b &= ~(b >> 31); b = (b + 32768) >> 16; }
// ------- toRGB 'Macro' END
rgb[idx+rgbOffs] = r | g | b;
// ------- toRGB 'Macro'
yVal = y[k++] << 16;
r = yVal + 91881*vVal;
g = yVal - 22554*uVal - 46802*vVal;
b = yVal + 116130*uVal;
if (r >= 16678912) r = 0x00FF0000;
else { r &= ~(r >> 31); r = (r + 32768) >> 16; r <<= 16; }
if (g >= 16678912) g = 0x0000FF00;
else { g &= ~(g >> 31); g = (g + 32768) >> 16; g <<= 8; }
if (b >= 16678912) b = 0x000000FF;
else { b &= ~(b >> 31); b = (b + 32768) >> 16; }
// ------- toRGB 'Macro' END
rgb[idx+rgbOffs+1] = r | g | b;
}
oOffs += this.stride;
iOffs += half;
}
return true;
}
| 9 |
public static void initCommandLineParameters(String[] args,
LinkedList<Option> specified_options, String[] manditory_args) {
Options options = new Options();
if (specified_options != null)
for (Option option : specified_options)
options.addOption(option);
Option option = null;
OptionBuilder.withArgName("file");
OptionBuilder.hasArg();
OptionBuilder
.withDescription("A file containing command line parameters as a Java properties file.");
option = OptionBuilder.create("parameter_file");
options.addOption(option);
CommandLineParser command_line_parser = new GnuParser();
CommandLineUtilities._properties = new Properties();
try {
CommandLineUtilities._command_line = command_line_parser.parse(
options, args);
} catch (ParseException e) {
System.out.println("***ERROR: " + e.getClass() + ": "
+ e.getMessage());
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("parameters:", options);
System.exit(0);
}
if (CommandLineUtilities.hasArg("parameter_file")) {
String parameter_file = CommandLineUtilities.getOptionValue("parameter_file");
// Read the property file.
try {
_properties.load(new FileInputStream(parameter_file));
} catch (IOException e) {
System.err.println("Problem reading parameter file: " + parameter_file);
}
}
boolean failed = false;
if (manditory_args != null) {
for (String arg : manditory_args) {
if (!CommandLineUtilities.hasArg(arg)) {
failed = true;
System.out.println("Missing argument: " + arg);
}
}
if (failed) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("parameters:", options);
System.exit(0);
}
}
}
| 9 |
public String toLongString() {
if (flagsMap.isEmpty()) return Language.NO_PERMISSIONS_SET.getString();
String sFlags = "";
for (Map.Entry<PermissionFlag, Boolean> flag : flagsMap.entrySet()) {
if (!sFlags.isEmpty()) sFlags += " | ";
sFlags += flag.getKey().getName() + ": " + (flag.getValue() ? "T" : "F");
}
return sFlags;
}
| 4 |
public static int[] getLineLabels(double latitude, double longitude, int date, int dstFlag) {
int[] lineLabels = new int[13];
for(int i = 0; i <= 12; i++) {
lineLabels[i] = i + 6; //go from 6 am to 6 pm
if(isDayLightSavings(latitude, longitude, date, dstFlag))
lineLabels[i]++; //just increase labels by 1 hr to handle DST correction
if(lineLabels[i] > 12) //Convert military time (18:00) to civilian time (6:00)
lineLabels[i] -= 12;
}
return lineLabels;
}
| 3 |
@Override
public List<String> getPermissions(String world) {
List<String> perms = super.getPermissions(world);
TotalPermissions plugin = (TotalPermissions) Bukkit.getPluginManager().getPlugin("TotalPermissions");
for (String group : inheritence) {
try {
PermissionGroup permGroup = plugin.getDataManager().getGroup(group);
if (permGroup != null) {
perms.addAll(permGroup.getPermissions());
}
} catch (DataLoadFailedException ex) {
plugin.getLogger().log(Level.SEVERE, "An error occured on loading " + group, ex);
}
}
return perms;
}
| 3 |
public void actionPerformed(ActionEvent e) {
//String cmd = e.getActionCommand();
for(ConvertOption o : this.gui.options){
if(e.equals("option_" + o.toString().toLowerCase().replace(" ", "_"))){
if(this.gui.activeOptions.contains(o))
this.gui.activeOptions.remove(o);
else
this.gui.activeOptions.add(o);
}
}
}
| 3 |
public ArrayList<Librarian> searchLibrarian(String columnName, String cond) {
Connection conn = null;
Statement st=null;
ResultSet rs=null;
ArrayList<Librarian> Librarians = null;
try {
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/librarysystem?user=admin&password=123456");
String query = null;
// If columnName and cond is not null, select specified tuples, otherwise, select all rows
if (columnName != null && cond != null) {
if (columnName == "idNumber") {
query = "SELECT * FROM Librarian WHERE " + columnName + " = '" + cond + "'";
} else {
query = "SELECT * FROM Librarian WHERE lower(" + columnName + ") LIKE '%" + cond + "%'";
}
} else {
query = "SELECT * FROM Librarian";
}
st = conn.createStatement();
rs = st.executeQuery(query);
Librarians = new ArrayList<Librarian>();
// Convert tuples from ResultSet to list of Librarian objects
while (rs.next()) {
Librarian l = new Librarian();
l.setIdNumber(rs.getInt(1));
l.setName(rs.getString(2));
l.setAddress(rs.getString(3));
Librarians.add(l);
}
} catch (SQLException e) {
e.getMessage();
} finally {
try {
if (conn != null)
conn.close();
if (st != null)
st.close();
if (rs != null)
rs.close();
} catch (Exception e) {
}
}
return Librarians;
}
| 9 |
protected void move( GameObject obj, Location l1 ) {
Location l0 = obj.getLocation();
boolean movedBetweenContainers = l0.container != l1.container;
if( movedBetweenContainers ) {
// Disconnect anything attached to the exterior!
for( GameObject o : obj.getExterior().getContents() ) {
if( o instanceof Connector ) {
Connectors.forceDisconnect( (Connector<?>)o );
}
}
}
if( l0.container != null ) l0.container.removeItem(obj);
obj.setLocation(l1);
if( l1.container != null ) l1.container.addItem(obj);
}
| 6 |
public void keyPressed(KeyEvent e)
{
setTitle(""+ KeyEvent.getKeyText(e.getKeyCode()));
System.out.println("hit + "+ KeyEvent.getKeyText(e.getKeyCode()));
switch(e.getKeyCode())
{
case KeyEvent.VK_DOWN :player.setVelocityY( player.getSpeed());
player.setVelocityX(0);
player.setDir(2);
break; //Sets the player's movement
case KeyEvent.VK_UP :player.setVelocityY( -1* player.getSpeed());
player.setVelocityX(0);
player.setDir(0);
break; //Sets the player's movement
case KeyEvent.VK_RIGHT :player.setVelocityX( player.getSpeed());
player.setVelocityY(0);
player.setDir(1);
break; //Sets the player's movement
case KeyEvent.VK_LEFT :player.setVelocityX( -1*player.getSpeed());
player.setVelocityY(0);
player.setDir(3);
break; //Sets the player's movement
case KeyEvent.VK_END :
player.setVelocityY(0);
player.setVelocityX(0);
break; //Stops the player completly
case KeyEvent.VK_ESCAPE :gameNotOver = false;
break;
}
}
| 6 |
@Override
public User build() {
try {
User record = new User();
record.names = fieldSetFlags()[0] ? this.names : (java.util.Map<java.lang.CharSequence,java.lang.CharSequence>) defaultValue(fields()[0]);
record.name = fieldSetFlags()[1] ? this.name : (java.lang.CharSequence) defaultValue(fields()[1]);
record.favorite_number = fieldSetFlags()[2] ? this.favorite_number : (java.lang.Integer) defaultValue(fields()[2]);
record.favorite_color = fieldSetFlags()[3] ? this.favorite_color : (java.lang.CharSequence) defaultValue(fields()[3]);
return record;
} catch (Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
| 5 |
@SuppressWarnings("unchecked")
private IElement decorateElement(final ClassLoader loader, final Field field) {
final WebElement wrappedElement = proxyForLocator(loader,
createLocator(field));
return elementFactory.create(
(Class<? extends IElement>) field.getType(), wrappedElement);
}
| 1 |
private static int[] addBinary(int[] aa, int[] bb){
int n = aa.length;
int m = bb.length;
int lenMax = n;
int lenMin = m;
if(m>n){
lenMax = m;
lenMin = n;
}
int[] addition = new int[lenMax];
int carry = 0;
int sum = 0;
for(int i=0; i<lenMin; i++){
sum = aa[i] + bb[i] + carry;
switch(sum){
case 0: addition[i] = 0;
carry = 0;
break;
case 1: addition[i] = 1;
carry = 0;
break;
case 2: addition[i] = 0;
carry = 1;
break;
case 3: addition[i] = 1;
carry = 1;
break;
}
}
return addition;
}
| 6 |
private static List<Region> calculateBestRegionsToTransferTo(BotState state, Region transferRegion) {
List<Region> closestNeighborsToBorder = DistanceToBorderCalculator.getClosestOwnedNeighborsToBorder(state,
transferRegion);
Region closestNeighborToOpponent = transferRegion.getClosestOwnedNeighborToOpponentBorder(state);
List<Region> out = new ArrayList<>();
if (closestNeighborsToBorder.size() == 0 && closestNeighborToOpponent == null) {
return out;
}
if (closestNeighborToOpponent == null) {
return closestNeighborsToBorder;
}
if (closestNeighborsToBorder.size() == 0) {
out.add(closestNeighborToOpponent);
return out;
}
int distanceToBorder = closestNeighborsToBorder.get(0).getDistanceToBorder();
int distanceToOpponentBorder = closestNeighborToOpponent.getDistanceToOpponentBorder();
// heuristic when to transfer to opponent border instead of closest
// border
if (distanceToOpponentBorder <= distanceToBorder + 3) {
out.add(closestNeighborToOpponent);
} else {
out.addAll(closestNeighborsToBorder);
}
return out;
}
| 5 |
@Override
public void update(long deltaMs) {
super.update(deltaMs);
// cool! if we have bought an update, we first flag that as done and at the next update, when the research event has been triggered, we update the tree!
if(updateResearch) {
itemSlots.clear();
int indx = 0;
for(ResearchItem ri : Application.get().getLogic().getGame().getResearch().getRoots()) {
ResearchScreenFactory.createTrees(this);
indx++;
}
updateResearch = false;
}
if(researchDone) {
updateResearch = true;
researchDone = false;
}
for(ResearchItemButton rib : itemSlots) {
rib.update(deltaMs);
}
}
| 4 |
@Override
public synchronized boolean equals(Object obj) {
if (obj == null)
return false;
if (this == obj)
return true;
if (getClass() != obj.getClass())
return false;
WayOsm other = (WayOsm) obj;
if (nodos == null) {
if (other.nodos != null)
return false;
} else if (this.sortNodes().size() == other.sortNodes().size()){
boolean equal = true;
for(int x = 0; equal && x < this.sortNodes().size(); x++)
equal = this.sortNodes().get(x).equals(other.sortNodes().get(x));
return equal;
}
else
return false;
return true;
}
| 8 |
public SQLResult process() throws Exception {
Matcher createTable = Pattern.compile("[cC][rR][eE][aA][tT][eE][\\s\\t]+[tT][aA][bB][lL][eE][\\s\\t]+(\\w+)[\\s\\t]+\\([\\s\\t]*(.*)[\\s\\t]*;").matcher(command);
if (createTable.find()) {
// TABLENAME
String tableName = createTable.group(1);
Table table = new Table(this.database, tableName);
// IDENTIFYING INDIVIDUAL COLUMNS
Matcher columns = Pattern.compile("([^,\\)]+)").matcher(createTable.group(2));
if (columns.find()) {
columns.reset();
// FOR EVERY COLUMN
while (columns.find()) {
System.out.println("\t"+columns.group(1));
Matcher fieldInfo = Pattern.compile("[\\s\\t]*(\\w+)[\\s\\t]+([^\\s]+)[\\s\\t]*(.*)").matcher(columns.group(1));
System.out.println("\tCreateTable.java: Fields");
while (fieldInfo.find()) {
System.out.println("\t\t"+fieldInfo.group(1));
System.out.println("\t\t"+fieldInfo.group(2));
System.out.println("\t\t"+fieldInfo.group(3));
String fieldname = fieldInfo.group(1);
String fieldtype = null;
int fieldsize = 0;
if (fieldInfo.group(2).equals("int")) {
fieldtype = fieldInfo.group(2);
fieldsize = 4;
} else if (fieldInfo.group(2).equals("double")) {
fieldtype = fieldInfo.group(2);
fieldsize = 8; // FIXME: Certo?
} else {
Matcher charInfo = Pattern.compile(
"[\\s\\t]*(\\w+)\\[{0,1}([0-9]*)\\]{0,1}.*").matcher(
fieldInfo.group(2));
if (charInfo.find()) {
System.out.println("CharInfo: "+
charInfo.group(1)+
" "+charInfo.group(2));
fieldtype = charInfo.group(1);
if (charInfo.group(2).trim().length()
> 0) {
fieldsize = Integer.parseInt(
charInfo.group(2));
} else {
fieldsize = 1;
}
}
}
table.getFields().add(new Field(fieldname,
fieldtype, fieldsize,
false, false, false));
}
}
}
System.out.println(table);
this.database.getRelationList().add(table);
return new SQLOk("OK");
}
return new SQLFailed("FAILED");
}
| 8 |
public int compare(Person p1,Person p2)
{
int result = p1.getName().compareTo(p2.getName());
if( 0 == result)
{
return p1.getId() - p2.getId(); //若姓名相同则按id排序
}
return result;
}
| 1 |
private static boolean formQueryCity(Criteria crit, List params, StringBuilder sb, StringBuilder sbw, Boolean f23) {
List list = new ArrayList<>();
StringBuilder str = new StringBuilder(" ( ");
String qu = new QueryMapper() {
@Override
public String mapQuery() {
Appender.appendArr(DAO_DIRCITY_ID_CITY, DB_DIRCITY_ID_CITY, crit, list, str, OR);
return str.toString() + " ) ";
}
}.mapQuery();
if (!list.isEmpty()) {
if (!f23) {
sb.append(LOAD_QUERY_DIRECT);
}
sb.append(LOAD_QUERY_CITY);
if (!params.isEmpty()) {
sbw.append(AND);
}
sbw.append(qu);
params.addAll(list);
return true;
} else {
return false;
}
}
| 3 |
public boolean isMetal()
{
int row = getRow(), col = getCol();
if(getOrbitalLetter() == 'p' && col <= 6 && row >= col-11)
return true;
return false;
}
| 3 |
public void shakeComponent(final JComponent component) {
if(t == null || !t.isAlive()) {
t = new Thread(this);
t.start();
}
}
| 2 |
public static void handleButtons(Player player, int buttonId, int packetId,
InputStream stream) {
String username = player.getDisplayName();
String clanName = "Feather";
if (buttonId == 85 && packetId == 61) {
player.getPackets().sendJoinClanChat(username, clanName);
}
if (buttonId == 80 && packetId == 61) {
if (player.inClanChat == false) {
player.getPackets().sendGameMessage(
"You need to be in a clan chat to view the settings");
} else if (player.inClanChat == true) {
player.getInterfaceManager().sendInterface(1096);
}
}
}
| 6 |
private void decremDealCounter(){
dealCounter--;
}
| 0 |
private void processLabors(int year, List<Man> mankind, List<Woman> womankind) {
List<Man> fathers = calculateFathers(mankind);
List<Human> children = new ArrayList<Human>();
for (Iterator<Woman> it = womankind.iterator(); it.hasNext(); ) {
Woman woman = it.next();
if (woman.isLaborAccepted()) {
Man father = findFather(fathers, woman);//подбор потенциального отца
if (father != null) {
Human child = processLabor(father, woman);
if (child == null) {//смерть во время родов
it.remove();
} else {
children.add(child);//сразу в mankind или womankind добавлять нельзя, т.к. получим ConcurrentModificationException при итерации по womankind
}
}
}
}
int mans = 0;
int womans = 0;
for (Human child: children) {
if (child.getSex() == Human.Sex.MALE) {
mankind.add((Man)child);
mans++;
} else if (child.getSex() == Human.Sex.FEMALE) {
womankind.add((Woman)child);
womans++;
}
}
if (year % debugFactor == 0) {LOGGER.debug("Year: " + year + ", newborns: " + (mans + womans) + "(" + mans + "/" + womans + ")");}
}
| 8 |
@Override
public void run()
{
//TODO collect statistics on users for fun:
//1. # of standups attended/missed
//2. speed of response after called on
//3. avg length of standup response?
//4. # of out of turn comments
//2 ways in:
//1. is a poll check and the user spoke
//2. is not a poll, timer expired then
if ( (isPoll && room_bot.did_user_speak) || (!isPoll))
{
StringBuilder sb = new StringBuilder();
if ( room_bot.current_standup_user != null )
{
if ( room_bot.did_user_speak )
{
sb.append("Thanks " + getFirstName(room_bot.current_standup_user.getName()) + "! ");
}
else
{
if ( room_bot.did_user_say_anything )
sb.append(getFirstName(room_bot.current_standup_user.getName()) + " spoke but didn't say terminating word, burned on a technicality! ");
else
sb.append(getFirstName(room_bot.current_standup_user.getName()) + " must be sleepy! ");
}
Date end_time = new Date();
user_time_ran.put(room_bot.current_standup_user.getMentionName(), end_time.getTime()-room_bot.curr_users_start_time.getTime());
}
//reset checks
room_bot.current_standup_user = null;
room_bot.did_user_speak = false;
room_bot.did_user_say_anything = false;
//turn off timers always
cancelAllTimers();
//poll_timer.cancel();
//timeout_timer.cancel();
HipchatUser next_user = room_bot.getNextStandupUser();
if ( next_user != null )
{
//choose a person to go
//bot.current_standup_user = remaining_users.remove( new Random().nextInt(remaining_users.size()) );
sb.append("Your turn @" + next_user.getMentionName());
hippy_bot.sendMessage(sb.toString(), room_bot.current_room);
//set poll timer
Date next_poll_time = new Date();
next_poll_time.setTime(next_poll_time.getTime() + 1000);
poll_timer = new Timer();
poll_timer.schedule(new NextStandupTask(hippy_bot, room_bot, true, false), next_poll_time, room_bot.bot_data.speaking_poll_secs*1000);
timers.add(poll_timer);
//set 20s timeout
Date next_user_time = new Date();
next_user_time.setTime(next_user_time.getTime() + (room_bot.bot_data.max_secs_between_turns*1000));
timeout_timer = new Timer();
timeout_timer.schedule(new NextStandupTask(hippy_bot, room_bot, false, false), next_user_time);
timers.add(timeout_timer);
room_bot.curr_users_start_time = new Date();
}
else
{
//all done
sb.append("That's everyone!");
sb.append("\nRuntime stats:");
for ( Map.Entry<String, Long> entry : user_time_ran.entrySet() )
{
double run_time = (entry.getValue())/1000.0;
sb.append("\n@" + entry.getKey() + ": " + run_time + "s");
}
room_bot.users_early_standup.clear();
hippy_bot.sendMessage(sb.toString(), room_bot.current_room);
room_bot.endStandup();
}
}
}
| 8 |
static boolean check_lon_overlap( Double arg_min_lon, Double arg_max_lon,
Double min_lon, Double max_lon )
{
boolean return_value = false;
if ( arg_min_lon < min_lon )
{
if ( arg_max_lon > min_lon )
{
if ( arg_debug >= Log_Informational_2 )
{
System.out.println( "In 1: " + arg_min_lon + " " + arg_max_lon + " " + min_lon + " " + max_lon);
}
return_value = true;
}
else
{
if ( arg_debug >= Log_Informational_2 )
{
System.out.println( "Out because arg lon is too small: " + arg_min_lon + " " + arg_max_lon + " " + min_lon + " " + max_lon );
}
return_value = false;
}
}
else
{
if ( arg_min_lon < max_lon )
{
if ( arg_debug >= Log_Informational_2 )
{
System.out.println( "In 2: " + arg_min_lon + " " + arg_max_lon + " " + min_lon + " " + max_lon);
}
return_value = true;
}
else
{
if ( arg_debug >= Log_Informational_2 )
{
System.out.println( "Out because arg lon is too big: " + arg_min_lon + " " + arg_max_lon + " " + min_lon + " " + max_lon );
}
return_value = false;
}
}
return return_value;
}
| 7 |
private int compareSync (String comp) {
// Inverse sync 0x82ED4F19
final String INVSYNC="10000010111011010100111100011001";
// Sync 0x7D12B0E6
final String SYNC="01111101000100101011000011100110";
// If the input String isn't the same length as the SYNC String then we have a serious problem !
if (comp.length()!=SYNC.length()) return 32;
int a,dif=0,invdif=0;
for (a=0;a<comp.length();a++) {
if (comp.charAt(a)!=SYNC.charAt(a)) dif++;
if (comp.charAt(a)!=INVSYNC.charAt(a)) invdif++;
}
// If the inverted difference is less than 2 the user must have things the wrong way around
if (invdif<2) {
if (theApp.isInvertSignal()==true) theApp.setInvertSignal(false);
else theApp.setInvertSignal(true);
return invdif;
}
return dif;
}
| 6 |
public void testSafeAddInt() {
assertEquals(0, FieldUtils.safeAdd(0, 0));
assertEquals(5, FieldUtils.safeAdd(2, 3));
assertEquals(-1, FieldUtils.safeAdd(2, -3));
assertEquals(1, FieldUtils.safeAdd(-2, 3));
assertEquals(-5, FieldUtils.safeAdd(-2, -3));
assertEquals(Integer.MAX_VALUE - 1, FieldUtils.safeAdd(Integer.MAX_VALUE, -1));
assertEquals(Integer.MIN_VALUE + 1, FieldUtils.safeAdd(Integer.MIN_VALUE, 1));
assertEquals(-1, FieldUtils.safeAdd(Integer.MIN_VALUE, Integer.MAX_VALUE));
assertEquals(-1, FieldUtils.safeAdd(Integer.MAX_VALUE, Integer.MIN_VALUE));
try {
FieldUtils.safeAdd(Integer.MAX_VALUE, 1);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Integer.MAX_VALUE, 100);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Integer.MAX_VALUE, Integer.MAX_VALUE);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Integer.MIN_VALUE, -1);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Integer.MIN_VALUE, -100);
fail();
} catch (ArithmeticException e) {
}
try {
FieldUtils.safeAdd(Integer.MIN_VALUE, Integer.MIN_VALUE);
fail();
} catch (ArithmeticException e) {
}
}
| 6 |
public LifeFrame nextFrame() {
LifeFrame next = new LifeFrame(new String[frame.height()][frame.width()]);
for (int i = 0; i < frame.height(); i++) {
for (int j = 0; j < frame.width(); j++) {
LifePosition lifePosition = new LifePosition(i, j);
if (shouldALive(lifePosition).equals(LifeStatus.alive))
next.changeStatusToAlive(lifePosition);
else
next.changeStatusToDead(lifePosition);
}
}
refreshFrame(next);
return frame;
}
| 3 |
private void writeAssociativeArray(List<Byte> ret, Map<String, Object> val) throws EncodingException, NotImplementedException
{
ret.add((byte)0x01);
for (String key : val.keySet())
{
writeString(ret, key);
encode(ret, val.get(key));
}
ret.add((byte)0x01);
}
| 1 |
public double calculateSalary() {
double salary = 0;
if (paymentType == "Base") {
if (paymentCurrency == "Dollar") {
salary = baseRate * dollarRate;
}
if (paymentCurrency == "British Pound") {
salary = baseRate * gbpRate;
}
if (paymentCurrency == "Rupee"){
salary = baseRate * rupeeRate;
}
}
if (paymentType == "BasePlusCommission"){
if (paymentCurrency == "Dollar") {
salary = baseRate * (1 + commissionRate) * dollarRate;
}
if (paymentCurrency == "British Pound") {
salary = baseRate * (1 + commissionRate)* gbpRate;
}
if (paymentCurrency == "Rupee"){
salary = baseRate * (1 + commissionRate)* rupeeRate;
}
}
return salary;
}
| 8 |
@RequestMapping("/{id}")
public String view(@PathVariable String id, Model model) {
model.addAttribute("model", userRepository.findOne(id));
return "users/form";
}
| 0 |
public SchlangenKopf(Rectangle masse, IntHolder unit, Color color) {
super(masse, unit, color);
direction = DIRECTION_START;
}
| 0 |
public void dash()
{
}
| 0 |
public void bannir(String _loginBan, boolean banni, String _login) throws UserAlreadyBannedException, IncompatibleUserLevelException, RemoteException
{
if(!_login.equals(this.getAuteur()) || !GestionnaireUtilisateurs.getUtilisateur(_login).isAdmin())
throw new IncompatibleUserLevelException();
if(banni)
{
if(this.bannis.contains(_loginBan))
{
throw new UserAlreadyBannedException();
}
else
{
this.bannis.add(_loginBan);
}
}
else if(this.bannis.contains(_loginBan))
{
this.bannis.remove(_loginBan);
}
}
| 5 |
private int ways(int currentVal, int add, int goal) {
if(currentVal == goal) {
return 1;
} else if(currentVal > goal) {
return 0;
} else {
int sum = 0;
for(Integer m : money) {
if(m >= add)
sum += ways(currentVal + m, m, goal);
}
return sum;
}
}
| 4 |
public static int pushAdjacent(Queue<Pair<Integer, Integer>> myQueue, int[][] canTravel, Pair<Integer, Integer> curr, Map<String, String> myMap){
int currX = curr.getFirst();
int currY = curr.getSecond();
if(currX+1<canTravel.length && canTravel[currX+1][currY]==0){
Pair<Integer, Integer> rightChild = new Pair(currX+1, currY);
String parent = ""+currX+","+currY+"";
String child = ""+(currX+1)+","+currY+"";
myMap.put(child, parent);
myQueue.offer(rightChild);
}
if(currY+1<canTravel[0].length && canTravel[currX][currY+1]==0){
Pair<Integer, Integer> upChild = new Pair(currX, currY+1);
String parent = ""+currX+","+currY+"";
String child = ""+(currX)+","+(currY+1)+"";
myMap.put(child, parent);
myQueue.offer(upChild);
}
if(currX-1>=0 && canTravel[currX-1][currY]==0){
Pair<Integer, Integer> leftChild = new Pair(currX-1, currY);
String parent = ""+currX+","+currY+"";
String child = ""+(currX-1)+","+currY+"";
myMap.put(child, parent);
myQueue.offer(leftChild);
}
if(currY-1>=0 && canTravel[currX][currY-1]==0){
Pair<Integer, Integer> downChild = new Pair(currX, currY-1);
String parent = ""+currX+","+currY+"";
String child = ""+(currX)+","+(currY-1)+"";
myMap.put(child, parent);
myQueue.offer(downChild);
}
return myQueue.size();
}
| 8 |
@Test
public void testDeregisterWorkers() throws LuaScriptException {
String jid = addJob();
popJob();
List<Map<String, Object>> workers = _client.Workers().counts();
for (Map<String, Object> worker : workers) {
if (worker.get("name").equals(TEST_WORKER)) {
assertEquals("1", worker.get("jobs").toString());
}
assertEquals("0", worker.get("stalled").toString());
}
_client.deRegisterWorkers(TEST_WORKER);
workers = _client.Workers().counts();
assertEquals(null, workers);
_client.cancel(jid);
}
| 2 |
private HashSet<String> getMatchesOutputSet(Vector<String> tagSet, String baseURL) {
HashSet<String> retSet=new HashSet<String>();
Iterator<String> vIter=tagSet.iterator();
while (vIter.hasNext()) {
String thisCheckPiece=vIter.next();
Iterator<Pattern> pIter=patternSet.iterator();
boolean hasAdded=false;
while (!hasAdded && pIter.hasNext()) {
Pattern thisPattern=pIter.next();
Matcher matcher=thisPattern.matcher(thisCheckPiece);
if (matcher.find() && (matcher.groupCount() > 0)) {
String thisMatch=getNormalizedContentURL(baseURL, matcher.group(1));
if (HTTP_START_PATTERN.matcher(thisMatch).matches()) {
if (!retSet.contains(thisMatch) && !baseURL.equals(thisMatch)) {
retSet.add(thisMatch);
hasAdded=true;
} // end if (!retSet.contains(thisMatch))
} // end if (HTTP_START_PATTERN.matcher(thisMatch).matches())
} // end if (matcher.find() && (matcher.groupCount() > 0))
matcher.reset();
} // end while (!hasAdded && pIter.hasNext())
} // end while (vIter.hasNext())
return retSet;
}
| 8 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (divisionName == null) {
if (other.divisionName != null)
return false;
} else if (!divisionName.equals(other.divisionName))
return false;
if (empId == null) {
if (other.empId != null)
return false;
} else if (!empId.equals(other.empId))
return false;
return true;
}
| 9 |
public boolean subsumes(Object general, Object specific)
{
HGRelType grel = (HGRelType)general;
HGRelType srel = (HGRelType)specific;
if (general == null || specific == null)
return general == specific;
if (!grel.getName().equals(srel.getName()) || grel.getArity() != srel.getArity())
return false;
for (int i = 0; i < grel.getArity(); i++)
{
HGHandle g = grel.getTargetAt(i);
HGHandle s = srel.getTargetAt(i);
if (g.equals(s))
continue;
else
{
HGAtomType gt = graph.getTypeSystem().getAtomType(g);
HGAtomType st = graph.getTypeSystem().getAtomType(s);
if (!gt.equals(st) || !gt.subsumes(graph.get(g), graph.get(s)))
return false;
}
}
return true;
}
| 8 |
private static String loadShader( String fileName )
{
StringBuilder shaderSource = new StringBuilder();
BufferedReader shaderReader = null;
final String INCLUDE_DIRECTIVE = "#include";
try
{
shaderReader = new BufferedReader( new FileReader( "./res/shaders/" + fileName ) );
String line;
while ( ( line = shaderReader.readLine() ) != null )
{
if ( line.startsWith( INCLUDE_DIRECTIVE ) )
{
shaderSource.append( loadShader( line.substring( INCLUDE_DIRECTIVE.length() + 2, line.length() - 1 ) ) );
}
else
shaderSource.append( line ).append( "\n" );
}
shaderReader.close();
}
catch ( Exception e )
{
e.printStackTrace();
System.exit( 1 );
}
return shaderSource.toString();
}
| 3 |
private void buildStatsPerDay(HashMap<Component, DayStats> to, HashMap<Component, List<Interval> > from){
Iterator componentsIterator = from.entrySet().iterator();
while (componentsIterator.hasNext()) {
Map.Entry pairs = (Map.Entry)componentsIterator.next();
Component node = (Component)pairs.getKey();
DayStats componentStats = to.containsKey(node)? to.get(node): new DayStats();
HashMap<Component, DayStats> parents = new HashMap<Component, DayStats>();
Component parent = node;
while ((parent = parent.getParent()) != null){
DayStats parentStats = to.containsKey(parent)? to.get(parent): new DayStats();
parents.put(parent, parentStats);
}
/* Convert intervals to DayStats*/
Iterator<Interval> intervalsIterator = ((List<Interval>)pairs.getValue()).iterator();
while (intervalsIterator.hasNext()) {
Interval interval = intervalsIterator.next();
/*Set stats for first day*/
Calendar calInit = interval.startTime;
Calendar calEnd = Calendar.getInstance();
Calendar calTemp = Calendar.getInstance();
/*Set stats for other days*/
while(calInit.get(Calendar.DAY_OF_MONTH) < interval.endTime.get(Calendar.DAY_OF_MONTH)){
calTemp.clear();
calEnd.clear();
calTemp.set(calInit.get(Calendar.YEAR), calInit.get(Calendar.MONTH), calInit.get(Calendar.DAY_OF_MONTH));
calEnd.set(calInit.get(Calendar.YEAR), calInit.get(Calendar.MONTH), calInit.get(Calendar.DAY_OF_MONTH +1));
componentStats.add(calTemp, Time.getPeriod(calInit, calEnd));
calInit = calEnd;
}
calTemp.clear();
calTemp.set(calInit.get(Calendar.YEAR), calInit.get(Calendar.MONTH), calInit.get(Calendar.DAY_OF_MONTH));
componentStats.add(calTemp, Time.getPeriod(calInit, interval.endTime));
Iterator parentsIterator = parents.entrySet().iterator();
while (parentsIterator.hasNext()) {
Map.Entry parentsPair = (Map.Entry)parentsIterator.next();
((DayStats)parentsPair.getValue()).add(calTemp, Time.getPeriod(calInit, interval.endTime));
}
}
to.put(node, componentStats);
Iterator parentsIterator = parents.entrySet().iterator();
while (parentsIterator.hasNext()) {
Map.Entry parentsPair = (Map.Entry)parentsIterator.next();
to.put((Component)parentsPair.getKey(), (DayStats)parentsPair.getValue());
}
}
}
| 8 |
@Override
public EntidadBancaria read(Integer idEntidadBancaria) {
try {
EntidadBancaria entidadBancaria;
Connection conexion = connectionFactory.getConnection();
String selectSQL = "SELECT * FROM entidadbancaria WHERE idEntidadBancaria = ?";
PreparedStatement preparedStatement = conexion.prepareStatement(selectSQL);
preparedStatement.setInt(1, idEntidadBancaria);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next() == true) {
entidadBancaria = new EntidadBancaria();
entidadBancaria.setCodigoEntidad(rs.getString("codigoEntidad"));
entidadBancaria.setNombre(rs.getString("nombreEntidad"));
entidadBancaria.setIdEntidadBancaria(rs.getInt("idEntidadBancaria"));
if (rs.next() == true) {
throw new RuntimeException("ERROR. Existe mas de una entidad." + idEntidadBancaria);
}
return entidadBancaria;
} else {
}
conexion.close();
System.out.println("Conexion creada y datos mostrados.");
return null;
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
| 3 |
public void gameUpdated(GameUpdateType type)
{
switch (type)
{
case GAMEOVER:
finalTime = engine.getCurrentRound();
finalN = engine.getBoard().mosquitosCaught;
break;
case MOVEPROCESSED:
break;
case STARTING:
break;
case MOUSEMOVED:
default:
// nothing.
}
}
| 4 |
public static boolean shouldBuild() {
int starports = UnitCounter.getNumberOfUnits(buildingType);
if (TerranFactory.getNumberOfUnitsCompleted() >= 3 && starports == 0
&& TerranSiegeTank.getNumberOfUnits() >= 5
&& !TechnologyManager.isSiegeModeResearchPossible()) {
return ShouldBuildCache.cacheShouldBuildInfo(buildingType, true);
}
if (starports == 1 && xvr.canAfford(600, 400)) {
return ShouldBuildCache.cacheShouldBuildInfo(buildingType, true);
}
return ShouldBuildCache.cacheShouldBuildInfo(buildingType, false);
}
| 6 |
public void tire(int x, int y) {
for (int i = 0; i < flotte.size(); i++) {
vaisseau tmp = flotte.get(i);
if (tmp.isSelected && tmp.isAlive()) {
tmp.nbTir++;
if (tmp.nbTir < 10) {
tir.add(new laser((int) tmp.posx + tmp.milieuX, (int) tmp.posy + tmp.milieuY, x, y, false,estRepublic));
} else {
tir.add(new laser((int) tmp.posx + tmp.milieuX, (int) tmp.posy + tmp.milieuY, x, y, true,estRepublic));
tmp.nbTir = 0;
}
//System.out.println((tmp.posx+tmp.milieuX)+" "+(tmp.posy+tmp.milieuY)+" "+ x+" "+ y);
}
}
}
| 4 |
@Override
public boolean valid() {
if (ctx.players.local().animation() == -1 && (!ctx.players.local().inMotion() || ctx.movement.distance(ctx.players.local(), ctx.movement.destination()) < 4)) {
if (npc().valid()) {
return true;
}
final GameObject rock = rock(TIN_FILTER);
if (rock.valid()) {
LogicailArea area = new LogicailArea(rock.tile().derive(-1, -1), rock.tile().derive(1, 1));
Set<Tile> tiles = area.getReachable(ctx);
return !tiles.isEmpty();
}
}
return false;
}
| 5 |
@Override
public void update(GameContainer gc, StateBasedGame sbg, int Delta) throws SlickException {
if(handle.Up() == true) {
System.out.println("test");
gc.exit();
System.exit(0);
}
}
| 1 |
private void runServer() throws IOException {
// pre startup message
ServerSocket serverSocket = new ServerSocket(PORTNUM);
serverSocket.setSoTimeout(TIMEOUT);
serverDirectoryCheck();
System.out.println("Server: Server has started broadcast on port " + PORTNUM + " and is waiting for connections...");
System.out.println("Server: Type '-q' or 'quit' or 'exit' anytime to shutdown server");
// Set up variables for reading quit message
BufferedReader bufferedPromptReader = new BufferedReader(new InputStreamReader(System.in));
EXIT_COMMAND cmd = EXIT_COMMAND.CONTINUE;
// Input / client accepting loop
do {
try {
Socket socket = serverSocket.accept();
ServerThread thread = new ServerThread(socket);
thread.start();
threadList.add(thread);
} catch (SocketTimeoutException e) {;} // Do nothing
if(bufferedPromptReader.ready()) {
cmd = EXIT_COMMAND.getCommand(bufferedPromptReader.readLine());
if(cmd.equals(EXIT_COMMAND.CONTINUE)) {
System.out.println("Server: Type 'exit', '-q' or 'quit' to close server");
}
}
} while(cmd.equals(EXIT_COMMAND.CONTINUE));
// server close message
System.out.println("Server: Closing all client connections...");
for(ServerThread thread: threadList) {
thread.close();
}
serverSocket.close();
System.out.println("Server: Server shut down...");
}
| 5 |
public boolean authenticate(String username, String password) throws LoginException
{
if (debug)
{
LOG.debug("Trying to authenticate user: " + username);
}
boolean authenticated = false;
UserData result = authenticationDao.loadUserData(username);
if (result.getSalt() != null && result.getPassword() != null)
{
if (debug)
{
LOG.debug("Salt and password loaded from database");
}
authenticated = checkPasswordMatching(password, result);
}
return authenticated;
}
| 4 |
public static ArrayList<int[]> getGoalLocations(State state) {
ArrayList<int[]> goalList = new ArrayList<int[]>();
int[] goalPosition = {0, 0};
ArrayList<ArrayList<String>> temp;
temp = copy(state.getData());
for (int k = 0; k < temp.size(); k++) {
for(int m = 0; m < temp.get(k).size(); m++) {
if (temp.get(k).get(m).equals(".")) {
goalPosition[0] = k;
goalPosition[1] = m;
goalList.add(goalPosition);
continue;
}
}
for(int m = 0; m < temp.get(k).size(); m++) {
if (temp.get(k).get(m).equals("*")) {
goalPosition[0] = k;
goalPosition[1] = m;
goalList.add(goalPosition);
continue;
}
}
}
return goalList;
}
| 5 |
@Override
public void getOptions() {
for (Component p : getParent().getComponents()) {
if (p instanceof OptionsPanel) {
fixedSpeed = ((OptionsPanel) p).isFixedSpeed();
player1.setLives(((OptionsPanel) p).getLives());
player2.setLives(((OptionsPanel) p).getLives());
player1.setWinningScore(((OptionsPanel) p).getWinningScore());
player2.setWinningScore(((OptionsPanel) p).getWinningScore());
}
}
}
| 2 |
private void trierDocuments(ArrayList<Document> documents,
ArrayList<Critere> criteres, ArrayList<MotClef> motClefs,
FileListModel flm) {
for (Document d : documents) {
if (d.matches(criteres, motClefs)) {
flm.add(d);
}
}
}
| 2 |
public Attribute getAttribute(String name)
{
for( int n = 0; n< attributes.size(); n++ )
{
Attribute item = attributes.get(n);
if( item.getName().equals(name) )
{
return item;
}
}
Attribute attribute = new Attribute();
attribute.setName(name);
attributes.add(attribute);
return attribute;
}
| 2 |
public boolean containsAtLeast(Inventory inventory, int minimumAmount) {
int foundItems = 0;
if (inventory instanceof PlayerInventory) {
PlayerInventory playerInventory = (PlayerInventory) inventory;
if (equals(playerInventory.getBoots()) || equals(playerInventory.getLeggings()) || equals(playerInventory.getChestplate()) || equals(playerInventory.getHelmet())) {
foundItems++;
}
}
for (ItemStack itemStack : inventory.getContents()) {
if (equals(itemStack)) {
foundItems++;
}
}
return foundItems >= minimumAmount;
}
| 7 |
@Override
public void run() {
while (serverIsRaning) {
try {
clientSocket = socket.accept();
ClientList.add(new Client(clientSocket));
Frame.println("Client connected.");
} catch (Exception e) {
serverIsRaning = false;
e.printStackTrace();
}
}
}
| 2 |
public void updateStats(){
int totalArmor = 0;
int minDmg = 0;
int maxDmg = 0;
int totalHealth = 0;
ArrayList<InventoryBox> equipped = inv.getEquipment();
InventoryBox weapon = equipped.get(0); //weapon
InventoryBox ring = equipped.get(1); //ring
InventoryBox neck = equipped.get(2); //necklace
if (weapon.hasItem()){
minDmg += weapon.getItem().getMinDamage();
maxDmg += weapon.getItem().getMaxDamage();
}
if (ring.hasItem()){
minDmg += ring.getItem().getMod();
}
if (neck.hasItem()){
totalHealth += neck.getItem().getMod();
}
for (int i = 3; i < equipped.size(); i++){
if (equipped.get(i).hasItem()){
totalArmor += equipped.get(i).getItem().getMod();
}
}
stats.equippedStats(minDmg, maxDmg, totalArmor, totalHealth);
}
| 5 |
void processChemCompLoopBlock() throws Exception {
parseLoopParameters(chemCompFields);
while (tokenizer.getData()) {
String groupName = null;
String hetName = null;
for (int i = 0; i < fieldCount; ++i) {
String field = loopData[i];
if (field.length() == 0)
continue;
char firstChar = field.charAt(0);
if (firstChar == '\0')
continue;
switch (fieldTypes[i]) {
case NONE:
break;
case CHEM_COMP_ID:
groupName = field;
break;
case CHEM_COMP_NAME:
hetName = field;
break;
}
}
if (groupName == null || hetName == null)
return;
addHetero(groupName, hetName);
}
}
| 9 |
public void tick() {
peersManager.tick();
choker.tick();
Long waitTime = activeTracker.getInterval();
if (incomingPeerListener.getReceivedConnection() == 0 || peersManager.getActivePeersNumber() < 4) {
waitTime = activeTracker.getMinInterval() != null ? activeTracker.getMinInterval() : 60;
}
long now = System.currentTimeMillis();
if (now - activeTracker.getLastRequestTime() >= waitTime * 1000) {
if (!stopped) {
try {
Object peers = trackerRequest(null).get(ByteBuffer.wrap("peers".getBytes()));
if (peers != null) {
addPeers(peers);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| 7 |
public String toString() {
Object obj;
String result = "[ ";
SListNode cur = getHead();
while (cur != null) {
obj = cur.red;
result += "{";
result = result + obj.toString() + ",";
obj = cur.green;
result = result + obj.toString() + ",";
obj = cur.blue;
result = result + obj.toString() + ",";
obj = cur.runlength;
result = result + obj.toString() + "} , ";
cur = cur.next;
}
result = result + "]";
return result;
}
| 1 |
public void writeTermList(Expression list) {
boolean first = true;
for (Term t : list.list) {
if (first) {
writer.print((t.constant == 1f ? "" : (t.constant == -1f ? "-"
: t.constant == Math.ceil(t.constant) ? Integer
.toString((int) t.constant) : t.constant))
+ " " + t.variable + " ");
first = false;
continue;
}
writer.print((t.constant < 0 ? " -" : " +")
+ " "
+ (Math.abs(t.constant) == 1f ? "" : t.constant == Math
.ceil(t.constant) ? Integer.toString((int) Math
.abs(t.constant)) : Math.abs(t.constant)) + " "
+ t.variable);
}
}
| 8 |
public static UserSettingsClient getInstance(){
if(instance == null){
instance = new UserSettingsClient();
}
return instance;
}
| 1 |
public static boolean cambioUnaLetra(char[] pActual, char[] pNueva) throws Exception {
boolean [] comprobar = new boolean[pActual.length];
int contador = 0;
for (int i = 0; i < pActual.length; i++) {
if (pActual[i] == pNueva[i]) {
comprobar[i] = true;
}
}
for (int i = 0; i < comprobar.length; i++) {
if (!comprobar[i]) {
contador++;
}
}
if (contador == 1) {
puntuacion = puntuacion + 3;
return true;
}
return false;
}
| 5 |
private Point getRowColOfSelectedCard(Point pressPt) {
Point p;
for(int i =0; i < A1Constants.NUMBER_OF_ROWS; i++){
for(int j = 0; j < A1Constants.NUMBER_OF_COLS; j++){
if(cards[i][j] != null){
if(cards[i][j].getCardArea().contains(pressPt) && cards[i][j].isActive()){
p = new Point(i, j);
return p;
}
}
}
}
return null;
}
| 5 |
@SuppressWarnings("unchecked")
public List<OfficeSpace> seachOfficeSpace(HashMap<String, Object> criteria){
Criteria c = new Criteria();
List<OfficeSpace> finalList = new ArrayList<OfficeSpace>();
// Create instance of Criteria object.
try {
if(criteria.containsKey("searchCriteria")){
c.poppulateCriteria((HashMap<String, Object>) criteria.get("searchCriteria"));
}
// Use this instance to create query triples.
c.queryBuilder(c);
// run these queries against KG
ArrayList<String> matchingOfficesID = c.processQueryCollection();
if(matchingOfficesID.size() == 0) throw new BusinessException("No OfficeSpace matches your criteria");
for(int i=0; i<matchingOfficesID.size(); i++){
OfficeSpace os = tempGetOfficeByID("abcd1234", matchingOfficesID.get(i));
if(Booking.checkAvailability(os, c.getStrtDate(), c.getEndDate()))
finalList.add(os);
}
if(finalList.size() == 0) throw new BusinessException("No OfficeSpace available from dates: "+ c.getStrtDate() +" to "+ c.getEndDate());
} catch(BusinessException b){
System.out.println(b);
}
return finalList;
}
| 6 |
@Override
public void logout(String username, int sentBy) {
_userStore.remove(username);
notifyUserListChanged();
if((sentBy == ServerInterface.CLIENT) && (backupServer != null)) {
try {
backupServer.ping();
backupServer.logout(username, ServerInterface.SERVER);
} catch(Exception ex) {
System.out.println("backup Server not responding");
resetBackupServer();
}
}
}
| 3 |
private Type createArray(Type rootComponent, int dims) {
if (rootComponent instanceof MultiType)
return new MultiArrayType((MultiType) rootComponent, dims);
String name = arrayName(rootComponent.clazz.getName(), dims);
Type type;
try {
type = Type.get(getClassPool(rootComponent).get(name));
} catch (NotFoundException e) {
throw new RuntimeException(e);
}
return type;
}
| 2 |
public char nextClean() throws JSONException {
for (;;) {
char c = next();
if (c == 0 || c > ' ') {
return c;
}
}
}
| 3 |
private static boolean modifyDrug(Drug bean, PreparedStatement stmt, String field) throws SQLException{
String sql = "UPDATE drugs SET "+field+"= ? WHERE drugname = ?";
stmt = conn.prepareStatement(sql);
if(field.toLowerCase().equals("description"))
stmt.setString(1, bean.getDescription());
if(field.toLowerCase().equals("quantity"))
stmt.setInt(1, bean.getQuantity());
if(field.toLowerCase().equals("sideefect"))
stmt.setString(1, bean.getSideEffect());
stmt.setString(2, bean.getDrugName());
int affected = stmt.executeUpdate();
if (affected == 1) {
System.out.println("drug info updated");
return true;
} else {
System.out.println("error: no update applied");
return false;
}
}
| 4 |
*/
private int[] getWhatNeedsDone() {
ArrayList list = new ArrayList();
for (int i = 0; i < editingGrammarModel.getRowCount() - 1; i++)
if (!converter.isChomsky(editingGrammarModel.getProduction(i)))
list.add(new Integer(i));
int[] ret = new int[list.size()];
for (int i = 0; i < ret.length; i++)
ret[i] = ((Integer) list.get(i)).intValue();
return ret;
}
| 3 |
public void transmitTextFile(final File file, final LoggedDataOutputStream dos) throws IOException {
if ((file == null) || !file.exists()) {
throw new IllegalArgumentException("File is either null or " + "does not exist. Cannot transmit.");
}
File fileToSend = file;
final TransmitTextFilePreprocessor transmitTextFilePreprocessor = getTransmitTextFilePreprocessor();
if (transmitTextFilePreprocessor != null) {
fileToSend = transmitTextFilePreprocessor.getPreprocessedTextFile(file);
}
BufferedInputStream bis = null;
try {
// first write the length of the file
long length = fileToSend.length();
dos.writeBytes(getLengthString(length), "US-ASCII");
bis = new BufferedInputStream(new FileInputStream(fileToSend));
// now transmit the file itself
final byte[] chunk = new byte[CHUNK_SIZE];
while (length > 0) {
final int bytesToRead = (length >= CHUNK_SIZE) ? CHUNK_SIZE : (int) length;
final int count = bis.read(chunk, 0, bytesToRead);
if (count == -1) {
throw new IOException("Unexpected end of stream from " + fileToSend + ".");
}
length -= count;
dos.write(chunk, 0, count);
}
dos.flush();
} finally {
if (bis != null) {
try {
bis.close();
} catch (final IOException ex) {
// ignore
}
}
if (transmitTextFilePreprocessor != null) {
transmitTextFilePreprocessor.cleanup(fileToSend);
}
}
}
| 9 |
public boolean objectEqualP(Stella_Object y) {
{ Set x = this;
if (Surrogate.subtypeOfP(Stella_Object.safePrimaryType(y), Stella.SGT_STELLA_SET)) {
{ Set y000 = ((Set)(y));
{ boolean testValue000 = false;
testValue000 = x.length() == y000.length();
if (testValue000) {
{ boolean alwaysP000 = true;
{ Stella_Object eltx = null;
ListIterator iter000 = ((ListIterator)(x.allocateIterator()));
loop000 : while (iter000.nextP()) {
eltx = iter000.value;
{ boolean testValue001 = false;
{ boolean foundP000 = false;
{ Stella_Object elty = null;
ListIterator iter001 = ((ListIterator)(y000.allocateIterator()));
loop001 : while (iter001.nextP()) {
elty = iter001.value;
if (Stella_Object.equalP(eltx, elty)) {
foundP000 = true;
break loop001;
}
}
}
testValue001 = foundP000;
}
testValue001 = !testValue001;
if (testValue001) {
alwaysP000 = false;
break loop000;
}
}
}
}
testValue000 = alwaysP000;
}
}
{ boolean value000 = testValue000;
return (value000);
}
}
}
}
else {
}
return (false);
}
}
| 6 |
public static void testValidity(Object o) throws JSONException {
if (o != null) {
if (o instanceof Double) {
if (((Double)o).isInfinite() || ((Double)o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
} else if (o instanceof Float) {
if (((Float)o).isInfinite() || ((Float)o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
}
}
}
| 7 |
public static int countNeighbours(boolean[][] world, int col, int row) {
int c = 0;
if (getCell(world, col - 1, row - 1) == true) {
c += 1;
}
if (getCell(world, col, row - 1) == true) {
c += 1;
}
if (getCell(world, col + 1, row - 1) == true) {
c += 1;
}
if (getCell(world, col - 1, row) == true) {
c += 1;
}
if (getCell(world, col + 1, row) == true) {
c += 1;
}
if (getCell(world, col - 1, row + 1) == true) {
c += 1;
}
if (getCell(world, col, row + 1) == true) {
c += 1;
}
if (getCell(world, col + 1, row + 1) == true) {
c += 1;
}
return c;
}
| 8 |
public boolean fichierRename(File ancien_nom, File nouveau_nom) {
if (ancien_nom.renameTo(nouveau_nom))
return true;
else
return false;
}
| 1 |
public void setHasBackground(boolean hasBackground) {
if(hasBackground && !this.hasBackground)
this.setColor(this.backgroundColor);
else if(!hasBackground && this.hasBackground)
this.setColor(Colors.TRANSPARENT.getGlColor());
this.hasBackground = hasBackground;
if(!this.hasBackground && !this.hasBorder)
{
this.text.setPosition(this.getTextX(), this.getTextY());
this.setTextClipping();
}
}
| 6 |
public double augmentFrontEndCharges(double capacity, int reactor_type, int year_count, PrintWriter output_writer) { // front end cost calculation
int i;
double charge=0;
double pvf;
if (year_count > FRONTENDREFYEAR[0] - START_YEAR) { // if past the reference date, total NU use must be calculated
TotalFrontEndUse[0][year_count] = TotalFrontEndUse[0][year_count-1]; // the value of the previous year is taken
for (int j = 0; j < REACTORNAMES.length; j++) { //and all reactor use in current year is added to that
TotalFrontEndUse[0][year_count] += NatUraniumUse[j][year_count];
}
} else { // else total NU usage is just the reference amount
TotalFrontEndUse[0][year_count] = FRONTENDREFAMOUNT[0];
}
for(i = 0; i < FRONTENDTECH.length; i++) {
pvf = Math.exp(TIMELAG_FRONTEND[i]*DiscountRate);
if (year_count > FRONTENDREFYEAR[i] - START_YEAR) {
double timeprice = Math.pow(year_count + START_YEAR - FRONTENDREFYEAR[i], FRONTENDTIMEEXP[i]); //price increase due to time
double amountprice = Math.pow(TotalFrontEndUse[i][year_count] / FRONTENDREFAMOUNT[i], FRONTENDAMOUNTEXP[i]); //price increase due to comsumption
FrontEndPriceModifier[i][year_count] = timeprice * amountprice; //total price increase
}
charge += getFECharge(reactor_type, i, capacity, year_count) * pvf * FrontEndPriceModifier[i][year_count];
if(add_to_integrals) integratedCosts[reactor_type][1+i] += getFECharge(reactor_type, i, capacity, year_count) * pvf * socialPVF;
if(print_cost_coefficients) if(printOutputFiles) output_writer.print((getFECharge(reactor_type, i, capacity, year_count) * pvf) + " ");
}
return(charge);
}
| 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.