text stringlengths 14 410k | label int32 0 9 |
|---|---|
public static byte[] decryptByPublicKey(byte[] data, String key)
throws Exception {
// 对密钥解密
byte[] keyBytes = SecurityCoder.base64Decoder(key);
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicKey = keyFactory.generatePublic(x509KeySpec);
// 对数据解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(data);
} | 0 |
public static CvTermReference getDefaultCvTerm(String name) {
if (name != null) {
name = name.toUpperCase();
if ("MASCOT".equals(name) || "MATRIX SCIENCE MASCOT".equals(name))
return MASCOT.getSearchEngineScores().get(0);
if ("XTANDEM".equals(name)) return XTANDEM.getSearchEngineScores().get(0);
if ("SEQUEST".equals(name)) return SEQUEST.getSearchEngineScores().get(0);
if ("SPECTRUM_MILL".equals(name)) return SPECTRUM_MILL.getSearchEngineScores().get(0);
if ("OMSSA".equals(name)) return OMSSA.getSearchEngineScores().get(0);
}
return null;
} | 7 |
private Role intToRole(int r) {
if (r == 3) {
return Role.administrator;
} else if (r == 2) {
return Role.scout;
} else if (r == 1) {
return Role.team_member;
}
return null;
} | 3 |
private void aliveOrderInit() {
this.aliveOrder = null;
this.rsizone = false;
} | 0 |
public static boolean closingIn( Point a1, Point a2, Point b1, Point b2 ){
Point cut = intersection( a1, plus( a1, new Point( a2.y - a1.y, a1.x - a2.x )), b1, b2 );
int cx = b1.x - cut.x;
int cy = b1.y - cut.y;
int dx = b1.x - b2.x;
int dy = b1.y - b2.y;
boolean sx = (cx < 0) == (dx < 0);
boolean sy = (cy < 0) == (dy < 0);
return sx && sy;
} | 1 |
public void mouseWheelMoved(MouseWheelEvent e) {
StdScrollPane scrollpane = StdScrollPane.this;
if (scrollpane.isWheelScrollingEnabled()
&& e.getScrollAmount() != 0) {
JScrollBar toScroll;
int direction = 0;
// find which scrollbar to scroll, or return if none
if ((e.getModifiersEx() & MouseWheelEvent.SHIFT_DOWN_MASK) == 0) {
toScroll = scrollpane.getVerticalScrollBar();
} else {
toScroll = scrollpane.getHorizontalScrollBar();
}
if (toScroll == null || !toScroll.isVisible()) {
return;
}
direction = e.getWheelRotation() < 0 ? -1 : 1;
if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) {
scrollByUnits(toScroll, direction, e.getScrollAmount());
} else if (e.getScrollType() == MouseWheelEvent.WHEEL_BLOCK_SCROLL) {
scrollByBlock(toScroll, direction);
}
}
} | 8 |
public void setDescription(String description) {
this.description = description;
} | 0 |
private void finishConnectingAt( int x, int y ){
if( connection == null ){
return;
}
startConnectingAt( false );
connectAt( x, y, false );
if( targetArray == null ){
cancelConnecting();
}
else{
connected( connection, sourceItem, targetItem );
connection = null;
targetArray = null;
sourceArray = null;
sourceItem = null;
}
openEnded.endConnecting();
} | 2 |
@Override
public Collection<Lot> searchLots (Map<String,String>params, boolean activeOnly, int maxResults) {
long requestId = this.findFreeKey(this.foundLotStatuses);
this.foundLotStatuses.put(requestId, false);
MsgFindLot msg = new MsgFindLot(this.address, this.ms.getAddressService().getAccountService(), params, requestId);
this.ms.sendMessage(msg);
while (!this.foundLotStatuses.get(requestId)){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (!this.foundLots.get(requestId).isEmpty()){
HashSet<Lot> rez = foundLots.get(requestId);
//removing used values
this.foundLotStatuses.remove(requestId);
this.foundLots.remove(requestId);
return rez;
}
//removing used values
this.foundLotStatuses.remove(requestId);
this.foundLots.remove(requestId);
return null;
} | 3 |
public QueueElement dequeue (AbstractQueue<QueueElement> queue)
throws InterruptedException {
logger.entering(loggerName, "dequeue", queue);
QueueElement qe = null;
while (qe == null) {
if ((qe = queue.poll()) == null)
Thread.currentThread().sleep(200);
}
logger.exiting(loggerName, "dequeue", qe);
return qe;
} | 2 |
void filterValues(double minValue, double maxValue) throws IOException {
for(int i = 0; i < rows; i++) {
double value = values.get(i);
if(!Double.isNaN(minValue) && !Double.isNaN(value) && minValue > value) {
values.set(i, Double.NaN);
}
if(!Double.isNaN(maxValue) && !Double.isNaN(value) && maxValue < value) {
values.set(i, Double.NaN);
}
}
} | 7 |
@Override
/**
* Runs in the background, timing fade in and fade out, changing the sequence,
* and issuing the appropriate volume change messages.
*/
public void run() {
while (!dying()) {
// if not currently fading in or out, put the thread to sleep
if (fadeOutGain == -1.0f && fadeInGain == 1.0f)
snooze(3600000);
checkFadeOut();
// only update every 50 miliseconds (no need to peg the cpu)
snooze(50);
}
// Important!
cleanup();
} | 3 |
public static void walk(final Tile... path) {
if(!Walking.isRunEnabled()) {
if (Walking.getEnergy() > Random.nextInt(30, 50)) {
Walking.setRun(true);
Task.sleep(400, 500);
}
}
for (int i = path.length - 1; i >= 0; i --) {
if (Calculations.distanceTo(path[i]) >= 15) {
continue;
}
if (Walking.walk(path[i])) {
break;
}
}
} | 5 |
public void edit(Link link) throws NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
link = em.merge(link);
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = link.getId();
if (findLink(id) == null) {
throw new NonexistentEntityException("The link with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
} | 5 |
@Override
public int getBomberNumber() {
return this.number;
} | 0 |
void releaseChildren(boolean destroy) {
if (items != null) {
for (int i = 0; i < items.length; i++) {
TreeItem item = items[i];
if (item != null && !item.isDisposed()) {
item.release(false);
}
}
items = null;
}
if (columns != null) {
for (int i = 0; i < columnCount; i++) {
TreeColumn column = columns[i];
if (column != null && !column.isDisposed()) {
column.release(false);
}
}
columns = null;
}
super.releaseChildren(destroy);
} | 8 |
public InputStream next()
{
if (closed || (next == null && !initial)) return null;
setNext();
if (next == null) return null;
return new InputStreamWrapper(jar);
} | 4 |
private TetrisStateBuffer search(TetrisStateBuffer in) {
stateDistQueue.clear();
veryFirstPiece = withVeryFirstPiece;
TetrisStateBuffer result = null;
addState(search.stateSet.get(search.getInitialState()), in);
int counter = 0;
while (!stateDistQueue.isEmpty()) {
StateDist stateDist = stateDistQueue.poll();
SearchState oldState = stateDist.state;
int oldDist = stateDistMap.get(oldState);
if (stateDist.dist > oldDist + estimateDistToGoal(oldState))
continue;
if (counter++ % 1 == 0) {
System.out.println("Board:");
oldState.board.print();
System.out.println("Est: " + stateDist.dist + " Dist: " + oldDist + " size: " + stateDistMap.size() + " unexplored: " + stateDistQueue.size());
}
if (oldState.rowsToGo <= 0 && search.isExpectedBoard(oldState.board)) {
// return stateBufferMap.get(oldState);
if (result == null)
result = stateBufferMap.get(oldState);
} else {
expandChildren(oldState, oldDist);
stateBufferMap.put(oldState, null);
}
veryFirstPiece = false;
}
return result;
} | 6 |
public void init(String startLine) {
data = null;
performSeparationOfCommonEdges = true;
if (startLine != null && (startLine.contains("-E") || startLine.contains("--no-separation"))) {
performSeparationOfCommonEdges = false;
}
dropShadows = true;
if (startLine != null && (startLine.contains("-S") || startLine.contains("--no-shadows"))) {
dropShadows = false;
}
if (diagramType == DiagramType.UML) {
first = true;
} else if (diagramType == DiagramType.DITAA) {
first = false;
data = new StringBuilder();
} else {
throw new IllegalStateException(diagramType.name());
}
} | 8 |
final void method3677(Canvas canvas) {
try {
anObject8020 = null;
anInt7936++;
aCanvas7910 = null;
if (canvas != null && canvas != ((NativeToolkit) this).aCanvas7925) {
if (aHashtable8014.containsKey(canvas)) {
anObject8020 = aHashtable8014.get(canvas);
aCanvas7910 = canvas;
}
} else {
anObject8020 = ((NativeToolkit) this).anObject7919;
aCanvas7910 = ((NativeToolkit) this).aCanvas7925;
}
if (aCanvas7910 == null || anObject8020 == null)
throw new RuntimeException();
method3881(anObject8020, (byte) 99, aCanvas7910);
method3917(false);
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
"wga.MF(" + (canvas != null
? "{...}"
: "null") + ')');
}
} | 7 |
public BulletHandler(GameWindow w){
window = w;
panel = window.panel;
initBulletHandler();
controls = window.controls;
player = window.player;
firerate =0;
try{
int index =0;
bulletpics = new BufferedImage[8];
BufferedImage bulletset = ImageIO.read(getClass().getResource("resources/bulletversuch.gif"));
for(int a = 0;a <= 2; a++){
for(int b = 0; b <= 2; b++){
if(((a==1)&&(b==1))==false){
BufferedImage i = bulletset.getSubimage(a*3, b*3, 3,3);
bulletpics[index] = i;
index++;
}
}
}
}catch(IOException e){
e.printStackTrace();
}
} | 5 |
public Set<Literal> getSameStartLiterals(Literal literal, ProvabilityLevel provability) {
Set<Literal> relatedLiterals = getRelatedLiterals(literal, provability);
if (null == relatedLiterals) return null;
Set<Literal> sameStartLiterals = new TreeSet<Literal>();
Temporal literalTemporal = literal.getTemporal();
for (Literal l : relatedLiterals) {
Temporal t = l.getTemporal();
if (null == t) {
if (null == literalTemporal || Long.MIN_VALUE == literalTemporal.getStartTime()) sameStartLiterals.add(l);
} else {
if (null == literalTemporal) {
if (Long.MIN_VALUE == t.getStartTime()) sameStartLiterals.add(l);
} else {
if (t.sameStart(literalTemporal)) sameStartLiterals.add(l);
}
}
}
return sameStartLiterals.size() == 0 ? null : sameStartLiterals;
} | 9 |
protected Behaviour getNextStep() {
if (restPoint == null) return null ;
if (restPoint instanceof Tile) {
if (((Tile) restPoint).blocked()) return null ;
}
if (restPoint instanceof Venue && menuFor((Venue) restPoint).size() > 0) {
if (actor.health.hungerLevel() > 0.1f) {
final Action eats = new Action(
actor, restPoint,
this, "actionEats",
Action.BUILD, "Eating at "+restPoint
) ;
currentMode = MODE_DINE ;
if (verbose) I.sayAbout(actor, "Returning eat action...") ;
return eats ;
}
}
//
// If you're tired, put your feet up.
if (actor.health.fatigueLevel() > 0.1f) {
final Action relax = new Action(
actor, restPoint,
this, "actionRest",
Action.FALL, "Resting at "+restPoint
) ;
currentMode = MODE_SLEEP ;
return relax ;
}
return null ;
} | 8 |
public void jouerCarte(){
if (!(main.isEmpty())){
boolean carteposee=false;
while(!(carteposee)){
System.out.println("quelle carte voulez vous poser parmi : ");
System.out.println("main :");
int i;
for (i=0;i<main.size();i++){
System.out.println("numero "+ (i+1) +" "+ main.get(i));
//System.out.println("numero "+ (i+1) +" "+ main.get(i).getCouleur() + " " + main.get(i).getValeur());
}
Scanner sc = new Scanner(System.in);
System.out.println("combien de cartes à poser ?");
int nombrecarteaposer=sc.nextInt();
carteaposer = new ArrayList<Carte>();
if (nombrecarteaposer==0){
Partie.partie.getTasDeCarte().donnerTalon(this);
}
else {
for(i=0;i<nombrecarteaposer;i++){
System.out.println("numéro de la carte n° "+(i+1)+" :");
int numerocarte = sc.nextInt();
carteaposer.add(main.get(numerocarte-1));
}
boolean identique=false;
if(carteaposer.size()==1){
identique=true;
}
//System.out.println(carteaposer.size());
if(carteaposer.size()>1){
identique=verifierCarteIdentique(carteaposer);
}
if (!(identique)){
System.out.println("cartes non identiques, veuillez recommencer");
}
//->exception identique=false
if (identique){
carteposee = poserCarte(carteaposer,main);
}
}
}}
} | 9 |
private static boolean isValidShuffleRecursiveDynamicProgramming(String str1, String str2, String str3, int i, int j, int k, Set<Triplet> cache) {
if(cache.contains(new Triplet(i, j, k))) {
return false;
}
if(k == str3.length()) {
return true;
}
char c = str3.charAt(k);
if(i < str1.length() && str1.charAt(i) == c && isValidShuffleRecursiveDynamicProgramming(str1, str2, str3, i+1, j, k+1, cache)) {
return true;
}
if(j < str1.length() && str2.charAt(j) == c && isValidShuffleRecursiveDynamicProgramming(str1, str2, str3, i, j+1, k+1, cache)) {
return true;
}
cache.add(new Triplet(i,j,k));
return false;
} | 8 |
@Override
public EventSet run(EventSetContext context, EventSet eventSetInUse, Object data) {
if (eventSetInUse != null
&& eventSetInUse.getStatus() == EventSetStatus.COLLECTION_IN_PROGRESS) {
return eventSetInUse;
}
List<EventSet> correlatingEventSets = context.findCorrelatingEventSets(
variableName, data, inboundCorrelationToken);
Iterator<EventSet> iter = correlatingEventSets.iterator();
while (iter.hasNext()) {
EventSet eventSet = iter.next();
if (eventSet.getStatus() != EventSetStatus.COLLECTION_IN_PROGRESS) {
iter.remove();
}
}
if (outboundCorrelationToken != null && outboundCorrelationToken.length() > 0) {
context.addCorrelationToken(outboundCorrelationToken, correlatingEventSets);
return eventSetInUse;
}
if (correlatingEventSets.size() != 1) {
return eventSetInUse;
}
EventSet correlatingEventSet = correlatingEventSets.get(0);
if (eventSetInUse != null
&& eventSetInUse.getStatus() == EventSetStatus.NEW) {
context.abortAndPublishEventSet(correlatingEventSet);
return eventSetInUse;
}
return correlatingEventSet;
} | 9 |
private int loadShader(String file, int type) {
System.out.println("Loading shader <" + file + ">");
StringBuilder source = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null)
source.append(line).append("\n");
} catch (IOException e) {
e.printStackTrace();
System.err.println("Error: Could not read shader file: " + file);
System.exit(1);
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
int shaderID = GL20.glCreateShader(type);
GL20.glShaderSource(shaderID, source);
GL20.glCompileShader(shaderID);
if (GL20.glGetShaderi(shaderID, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) {
System.err.println("Error: Could not comple shader");
System.err.println(GL20.glGetShaderInfoLog(shaderID, 500));
System.exit(1);
}
return shaderID;
} | 5 |
@Override
public int compareTo(Spot sp) {
if (candidates.size() < sp.getCandidates().size()) return -1;
if (candidates.size() == sp.getCandidates().size()) return 0;
return 1;
} | 2 |
public String getCode(){
String str = element.getCode();
if(program != null)
str += program.getCode();
return str;
} | 1 |
public void loadFields() {
HashMap<String,String> allFields = readFielldsFromFile();
Field [] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
String name = field.getName();
if (allFields.containsKey(name)) {
if (field.getType() == JCheckBox.class) {
try {
((JCheckBox)field.get(this)).setSelected(allFields.get(name).equalsIgnoreCase("true"));
} catch (Exception e) {
log.warning("Error setting the field '"+name+"' with the value: " + allFields.get(name));
}
} else if (field.getType() == JTextField.class) {
try {
((JTextField)field.get(this)).setText(allFields.get(name));
} catch (Exception e) {
log.warning("Error setting the field '"+name+"' with the value: " + allFields.get(name));
}
}
}
}
} | 6 |
protected void setSinglePreserved() {
if (parent != null)
parent.setPreserved();
} | 1 |
private void processInput(KeyEvent e) {
Integer keyNum = e.getKeyCode();
Character keyChar = Character.toLowerCase(e.getKeyChar());
if (ACCEPTED_KEYS.contains(keyChar.toString())) {
decodeInput(keyChar);
}
for(int i=0;i<ACCEPTED_NUM_KEYS.length;i++){
if(ACCEPTED_NUM_KEYS[i] == keyNum){
decodeNumberInput(keyNum);
}
}
} | 3 |
private static String name(PeekReader in) throws IOException {
StringBuilder buf = new StringBuilder();
while(true) {
int c = in.peek();
if(c < 0) {
break;
} else if(namechar((char)c)) {
buf.append((char)in.read());
} else {
break;
}
}
if(buf.length() == 0)
throw(new FormatException("Expected name, got `" + (char)in.peek() + "'"));
return(buf.toString());
} | 4 |
@Test
public void testRandomness() throws Exception {
// RandomUtils.useTestSeed(); allows you to create stable unit test
// but in reality one should make a decision on several different test results in order to know the variance
// check how with the default pearson similarity and the top 300 users as neighborhood
// the results might change between different runs with the same configuration
for (int i = 0; i < 10; i++) {
Assert.fail();
}
} | 1 |
public CodecInfo(String strInfo) {
_isDecoder = _isAudioCodec = _isDecoder = _isSubtitleCodec = _isVideoCodec = _supportDirectRenderingMethod = _supportDrawHorizBand = _supportWeirdFrameTruncation = false;
char[] tagBit = strInfo.substring(1, 8).toCharArray();
if (tagBit[0] != '.')
_isDecoder = true;
if (tagBit[1] != '.')
_isEncoder = true;
switch(tagBit[2]) {
case 'V':
_isVideoCodec = true;
break;
case 'A':
_isAudioCodec = true;
break;
case 'S':
_isSubtitleCodec = true;
break;
}
if (tagBit[4] != '.')
_supportDrawHorizBand = true;
if (tagBit[5] != '.')
_supportDirectRenderingMethod = true;
if (tagBit[6] != '.')
_supportWeirdFrameTruncation = true;
strInfo = strInfo.substring(8).trim();
String[] strParses = strInfo.split(" ");
_name = strParses[0];
description = strInfo.substring(_name.length()).trim();
// System.out.println(_name + "\t\t" + description);
} | 8 |
public Point CheckTiles(int mouseX, int mouseY, int mButton)
{
int row = FindTileRow(mouseY);
int col = FindTileCol(mouseX);
Point p = new Point(row, col);
if(row != -1 && col != -1)
{
if (mButton == MouseEvent.BUTTON1)
{
ChangeTile(row, col);
}
}
return p;
} | 3 |
@Override
public void update() {
for (GUI child:children){
child.update();
}
} | 1 |
public String adminUpdateProduct() {
this.product = this.userFacade.getProductById(this.id);
setProductFromProperty();
this.adminFacade.updateProduct(this.product);
return "adminProductDetails";
} | 0 |
public Shell open(Display display) {
// Load the images
Class clazz = HoverHelp.class;
try {
if (images == null) {
images = new Image[imageLocations.length];
for (int i = 0; i < imageLocations.length; ++i) {
InputStream stream = clazz.getResourceAsStream(imageLocations[i]);
ImageData source = new ImageData(stream);
ImageData mask = source.getTransparencyMask();
images[i] = new Image(display, source, mask);
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (Exception ex) {
System.err.println(getResourceString("error.CouldNotLoadResources",
new Object[] { ex.getMessage() }));
return null;
}
// Create the window
Shell shell = new Shell();
createPartControl(shell);
shell.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
/* Free resources */
if (images != null) {
for (int i = 0; i < images.length; i++) {
final Image image = images[i];
if (image != null) image.dispose();
}
images = null;
}
}
});
shell.pack();
shell.open();
return shell;
} | 7 |
@Override
public void run(){
try{
synchronized(this){
BufferedWriter bw=new BufferedWriter(
new OutputStreamWriter(s.getOutputStream()));
BufferedReader br=new BufferedReader(
new InputStreamReader(s.getInputStream()));
String inputLine;
while((inputLine=br.readLine())!=null){
break;
}
StringTokenizer st=new StringTokenizer(inputLine);
String userName=null, password=null;
int count=0;
while(st.hasMoreTokens()){
if(count==0) userName=st.nextToken();
else if(count==1) password=st.nextToken();
else if(count==2) break;
count++;
}
File file=new File("G:\\"+userName);
if(file.exists()){
FileReader fr=new FileReader("G:\\"+userName+"\\data.txt");
br=new BufferedReader(fr);
String savedPassword=br.readLine();
fr.close();
String trimmedPassword= password.trim();
String trimmedSavedPassword=savedPassword.trim();
if(trimmedPassword.equals(trimmedSavedPassword)){
bw.write("Successfully Signed in.");
bw.newLine();
bw.flush();
}
else{
bw.write("Wrong Username! Try Again.!");
bw.newLine();
bw.flush();
}
}
else{
bw.write("Wrong Username! Try Again.");
bw.newLine();
bw.flush();
}
bw.close(); br.close();
}
} catch(IOException e){
System.out.println(e.getMessage());
}
} | 8 |
public int getAantalpaginas() {
return aantalpaginas;
} | 0 |
public static void combSort11(double arrayToSort[], int linkedArray[]) {
int switches, j, top, gap;
double hold1; int hold2;
gap = arrayToSort.length;
do {
gap=(int)(gap/1.3);
switch(gap) {
case 0:
gap = 1;
break;
case 9:
case 10:
gap=11;
break;
default:
break;
}
switches=0;
top = arrayToSort.length-gap;
for(int i=0; i<top; i++) {
j=i+gap;
if(arrayToSort[i] > arrayToSort[j]) {
hold1=arrayToSort[i];
hold2=linkedArray[i];
arrayToSort[i]=arrayToSort[j];
linkedArray[i]=linkedArray[j];
arrayToSort[j]=hold1;
linkedArray[j]=hold2;
switches++;
}//endif
}//endfor
} while(switches>0 || gap>1);
} | 7 |
protected static URL getURL(String classpathPart, String pkgname) {
String urlStr;
URL result;
File classpathFile;
File file;
JarFile jarfile;
Enumeration enm;
String pkgnameTmp;
result = null;
urlStr = null;
try {
classpathFile = new File(classpathPart);
// directory or jar?
if (classpathFile.isDirectory()) {
// does the package exist in this directory?
file = new File(classpathPart + pkgname);
if (file.exists())
urlStr = "file:" + classpathPart + pkgname;
}
else {
// is package actually included in jar?
jarfile = new JarFile(classpathPart);
enm = jarfile.entries();
pkgnameTmp = pkgname.substring(1); // remove the leading "/"
while (enm.hasMoreElements()) {
if (enm.nextElement().toString().startsWith(pkgnameTmp)) {
urlStr = "jar:file:" + classpathPart + "!" + pkgname;
break;
}
}
}
}
catch (Exception e) {
// ignore
}
// try to generate URL from url string
if (urlStr != null) {
try {
result = new URL(urlStr);
}
catch (Exception e) {
System.err.println(
"Trying to create URL from '" + urlStr
+ "' generates this exception:\n" + e);
result = null;
}
}
return result;
} | 7 |
public Border findBorder(int locx, int locy, boolean opt) {
int top = 0, left = 0, bottom = 0, right = 0;
int val;
if (opt) {
val = newRun.getMazeVal(locx, locy);
} else {
val = newRun.getTravVal(locx, locy);
}
if ((val & 0x01) == 0x01) top = 5;
if ((val & 0x02) == 0x02) right = 5;
if ((val & 0x04) == 0x04) bottom = 5;
if ((val & 0x08) == 0x08) left = 5;
return BorderFactory.createMatteBorder(top, left, bottom, right, Color.black);
} | 5 |
private static Object nextValue(String jsonStr, AtomicInteger offset) {
while (offset.get() < jsonStr.length()) {
char c = jsonStr.charAt(offset.getAndIncrement());
if (Character.isWhitespace(c)) {
continue;
}
if (c == '"') {
offset.decrementAndGet();
return nextString(jsonStr, offset);
}
if (c == '{') {
offset.decrementAndGet();
return nextObject(jsonStr, offset);
}
if (Character.isDigit(c) || c == '-') {
offset.decrementAndGet();
return nextNumber(jsonStr, offset);
}
if (c == 't') {
offset.set(offset.get() + 3);
return new JsonKeyTFN("true");
}
if (c == 'f') {
offset.set(offset.get() + 4);
return new JsonKeyTFN("false");
}
if (c == 'n') {
offset.set(offset.get() + 3);
return new JsonKeyTFN("null");
}
}
return null;
} | 9 |
public ServerThread(IPacketProcessor packetProcessor, int port) {
super();
this.packetProcessor = packetProcessor;
try {
socket = new DatagramSocket(port);
start();
} catch (java.lang.IllegalArgumentException e) {
packetProcessor.onError(ModelNotification.CONNECTION_ERROR);
} catch (SocketException e) {
packetProcessor.onError(ModelNotification.CONNECTION_ERROR);
}
} | 2 |
private Rectangle calculatePixelPerfect(VGDLSprite sprite1, VGDLSprite sprite2)
{
Vector2d sprite1v = new Vector2d(sprite1.rect.getCenterX() - sprite1.lastrect.getCenterX(),
sprite1.rect.getCenterY() - sprite1.lastrect.getCenterY());
sprite1v.normalise();
Direction sprite1Dir = new Direction(sprite1v.x, sprite1v.y);
if(sprite1Dir.equals(Types.DDOWN))
{
int overlay = (sprite1.rect.y + sprite1.rect.height) - sprite2.rect.y;
return new Rectangle(sprite1.rect.x, sprite1.rect.y - overlay,
sprite1.rect.width, sprite1.rect.height);
}
else if(sprite1Dir.equals(Types.DRIGHT))
{
int overlay = (sprite1.rect.x + sprite1.rect.width) - sprite2.rect.x;
return new Rectangle(sprite1.rect.x - overlay, sprite1.rect.y,
sprite1.rect.width, sprite1.rect.height);
}
else if(sprite1Dir.equals(Types.DUP))
{
return new Rectangle(sprite1.rect.x, sprite2.rect.y + sprite2.rect.height,
sprite1.rect.width, sprite1.rect.height);
}
else if(sprite1Dir.equals(Types.DLEFT))
{
return new Rectangle(sprite2.rect.x + sprite2.rect.width, sprite1.rect.y,
sprite1.rect.width, sprite1.rect.height);
}
return sprite1.lastrect;
} | 4 |
protected void mismatch()
{
// first test: are we long enough?
if ( pathLen >= MUM.MIN_LEN )
{
// second test: are we unique in the suffix tree?
if ( pos.node.isLeaf() )
{
// third test
if ( isMaximal() )
{
addToPath( arc );
// if we matched at least one byte of the current arc
mum.update( start, offset, versions,
pos.edgePos-pathLen, pathLen, travelled );
}
// else it's a substring of the maximum match
}
// else it can't be a unique match
}
// else it's a tiddler: throw it back!
} | 3 |
public static File[] chooseFiles(JFrame frame, String Button, int mode) {
JFileChooser jfc = new JFileChooser();
jfc.setFileSelectionMode(mode);
jfc.setMultiSelectionEnabled(false);
jfc.setAcceptAllFileFilterUsed(true);
int success = jfc.showDialog(frame, Button);
if(success == JFileChooser.APPROVE_OPTION) {
return jfc.getSelectedFiles();
}
return null;
} | 1 |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (obj instanceof Image) {
if (image.equals((Image) obj)) {
return true;
}
}
if (!(obj instanceof ImagePanel)) {
return false;
}
ImagePanel other = (ImagePanel) obj;
return image.equals(other.image);
} | 5 |
public BirthdayStats getBirthdayStats() throws SQLException {
if (!dbcon.IsConnected) { return null; }
BirthdayStats stats = new BirthdayStats();
ResultSet res;
String year = new SimpleDateFormat("YYYY").format(new Date());
String month = new SimpleDateFormat("MM").format(new Date());
// Total birthday records
res = dbcon.ExecuteQuery("SELECT COUNT(*) FROM birthdaygift");
if ((res != null) && (res.next())) {
stats.TotalBirthdays = res.getInt(1);
}
// Total birthdays this month
res = dbcon.ExecuteQuery("SELECT COUNT(*) FROM birthdaygift WHERE strftime('%m', BirthdayDate) = '" + month + "'");
if ((res != null) && (res.next())) {
stats.MonthBirthdays = res.getInt(1);
}
// Total claimed gifts this year
res = dbcon.ExecuteQuery("SELECT COUNT(*) FROM birthdaygift WHERE strftime('%Y', lastGiftDate) = '" + year + "'");
if ((res != null) && (res.next())) {
stats.ClaimedGiftsThisYear = res.getInt(1);
}
// Total unclaimed gifts this year
res = dbcon.ExecuteQuery("SELECT COUNT(*) FROM birthdaygift WHERE strftime('%Y', lastAnnouncedDate) = '" + year + "' AND strftime('%Y', lastGiftDate) IS NOT '" + year + "'");
if ((res != null) && (res.next())) {
stats.UnclaimedGiftsThisYear = res.getInt(1);
}
return stats;
} | 9 |
public XMLElement save() {
XMLElement arrowLink = new XMLElement();
arrowLink.setName("arrowlink");
if (style != null) {
arrowLink.setAttribute("STYLE", style);
}
if (getUniqueId() != null) {
arrowLink.setAttribute("ID", getUniqueId());
}
if (color != null) {
arrowLink.setAttribute("COLOR", Tools.colorToXml(color));
}
if (getDestinationLabel() != null) {
arrowLink.setAttribute("DESTINATION", getDestinationLabel());
}
if (getReferenceText() != null) {
arrowLink.setAttribute("REFERENCETEXT", getReferenceText());
}
if (getStartInclination() != null) {
arrowLink.setAttribute("STARTINCLINATION",
Tools.PointToXml(getStartInclination()));
}
if (getEndInclination() != null) {
arrowLink.setAttribute("ENDINCLINATION",
Tools.PointToXml(getEndInclination()));
}
if (getStartArrow() != null)
arrowLink.setAttribute("STARTARROW", (getStartArrow()));
if (getEndArrow() != null)
arrowLink.setAttribute("ENDARROW", (getEndArrow()));
return arrowLink;
} | 9 |
public void render(){
texture.bind();
if(!isDead()){
int xChange = (change-1) % 3;
super.render();
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(xChange * 0.25f,yChange * 0.25f + 0.25f);
GL11.glVertex2f(x, y);
GL11.glTexCoord2f(xChange * 0.25f + 0.25f,yChange * 0.25f + 0.25f);
GL11.glVertex2f(x+64, y);
GL11.glTexCoord2f(xChange * 0.25f + 0.25f,yChange * 0.25f);
GL11.glVertex2f(x+64, y+64);
GL11.glTexCoord2f(xChange * 0.25f,yChange * 0.25f);
GL11.glVertex2f(x, y+64);
GL11.glEnd();
}else{
renderItemBag();
}
} | 1 |
public User[] loadUsers(ChatChannel channel){
User[] users = null;
try {
Socket socket = new Socket(SERVER_ADDRESS_CHAT, CHAT_PORT);
socket.setSoTimeout(TIMEOUT);
OutputStream outputStream = socket.getOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
outputStream);
objectOutputStream.writeObject("LOAD_USERS");
objectOutputStream.writeObject(channel);
objectOutputStream.flush();
InputStream inputStream = socket.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
users = (User[])objectInputStream.readObject();
socket.close();
}catch (SocketException e){
new ErrorFrame("Server unreachable!");
} catch (SocketTimeoutException e){
new ErrorFrame("Connection timed out");
} catch (Exception e) {
new ErrorFrame("An unknown Error occoured");
}
return users;
} | 3 |
public void run() {
try {
//create socket
tcpSocket = new Socket();
// Create remote bind-point
System.out.println("Connecting to " + host + ":" + port + ". Interval: " + interval);
SocketAddress remoteBindPoint = new InetSocketAddress(host, port);
tcpSocket.connect(remoteBindPoint);
//wait for the connection to be established
Thread.sleep(2000);
OutputStream os = tcpSocket.getOutputStream();
DataOutputStream oos = new DataOutputStream(os);
if (dbg) System.out.println("OutputStream established");
System.out.println("Sending...");
//few performance counters
long delaySum = 0;
long time = 0, lastPackTime = 0;
for (int i = 0; i < dataList.size(); i++) {
if (dbg) System.out.println("try to send file " + i + " => " + fileList.get(i));
FilePacket pack = dataList.get(i);
// write data
oos.writeInt(pack.size); // write file size
if (dbg) System.out.println("sent size of " + i);
oos.writeInt(i); // write counter
pack.count = i;
if (dbg) System.out.println("sent count => " + i);
oos.write(pack.content); // write all bytes of the file
if (dbg) System.out.println("sent data of " + i + " => " + pack.content.length);
time = System.currentTimeMillis();
pack.startTime = time;
//measure real delay between blocks
if (lastPackTime != 0) { //ignore first packet
delaySum += time - lastPackTime;
}
lastPackTime = time;
System.out.println("Finished " + i);
//System.out.println("Start time " + sent + ": " + time);
Thread.sleep(interval);
}
// send last message to finish connection
oos.writeInt(FilePacket.FINISH); // write file size
oos.close();
os.close();
tcpSocket.close();
System.out.println("Transfered " + dataList.size() + " files");
if (sent > 1) System.out.println("Average delay: " + (delaySum / (sent - 1)));
// System.out.println("Waiting for results ...");
// Thread.sleep(waitToEnd);
} catch (Exception ex) {
ex.printStackTrace();
}
} | 9 |
@Override
public boolean keepCombating(Entity victim) {
boolean isRanging = PlayerCombat.isRanging(player) != 0;
if (!war.isCanCommence()) {
player.getPackets().sendGameMessage("The war hasn't started yet.",
true);
return false;
} else if (player.getCurrentFriendChat().getPlayers().contains(victim)) {
player.getPackets().sendGameMessage(
"You can't attack your own team members.", true);
return false;
} else if (player.getCombatDefinitions().getSpellId() > 0
&& war.isSet(Rule.NO_MAGIC)) {
player.getPackets().sendGameMessage(
"You can't use magic attacks during this war.", true);
return false;
} else if (isRanging && war.isSet(Rule.BAN_RANGE)) {
player.getPackets().sendGameMessage(
"You can't use range attacks during this war.", true);
return false;
} else if (!isRanging && war.isSet(Rule.BAN_MELEE)
&& player.getCombatDefinitions().getSpellId() <= 0) {
player.getPackets().sendGameMessage(
"You can't use melee attacks during this war.", true);
return false;
}
return true;
} | 9 |
public void computeDerivatives(double t, double[] y, double[] yDot) {
double p;
p = (y[0]*y[0]+y[1]*y[1]+y[2]*y[2]+y[3]*y[3]-1);
yDot[0] = -0.5*y[1]*y[4]-0.5*y[2]*y[5]-0.5*y[3]*y[6]+0.5*y[2]-0.5*y[0]*p;
yDot[1] = 0.5*y[0]*y[4]+0.5*y[2]*y[6]-0.5*y[3]*y[5]-0.5*y[3]-0.5*y[1]*p;
yDot[2] = 0.5*y[0]*y[5]+0.5*y[3]*y[4]-0.5*y[1]*y[6]-0.5*y[0]-0.5*y[2]*p;
yDot[3] = 0.5*y[0]*y[6]+0.5*y[1]*y[5]-0.5*y[2]*y[4]+0.5*y[1]-0.5*y[3]*p;
yDot[4] = (epsilon-delta)*(-y[5]*y[6]+3*(2*y[2]*y[3]+2*y[0]*y[1])*(y[0]*y[0]-y[1]*y[1]-y[2]*y[2]+y[3]*y[3]));
yDot[5] = (1-epsilon)/delta *(-y[6]*y[4]+3*(y[0]*y[0]-y[1]*y[1]-y[2]*y[2]+y[3]*y[3])*(2*y[1]*y[3]-2*y[0]*y[2]));
yDot[6] = (delta-1)/epsilon *(-y[4]*y[5]+3*(2*y[1]*y[3]-2*y[0]*y[2])*(2*y[2]*y[3]+2*y[0]*y[1]));
} | 0 |
@Override
public void calculateFractalOrbit() {
iterations = 0;
Complex[] complex = new Complex[1];
complex[0] = new Complex(pixel_orbit);//z
Complex temp = null;
Complex zold = new Complex();
if(parser.foundS()) {
parser.setSvalue(new Complex(complex[0]));
}
if(parser.foundP()) {
parser.setPvalue(new Complex());
}
for(; iterations < max_iterations; iterations++) {
zold.assign(complex[0]);
function(complex);
if(parser.foundP()) {
parser.setPvalue(new Complex(zold));
}
temp = rotation.getPixel(complex[0], true);
if(Double.isNaN(temp.getRe()) || Double.isNaN(temp.getIm()) || Double.isInfinite(temp.getRe()) || Double.isInfinite(temp.getIm())) {
break;
}
complex_orbit.add(temp);
}
} | 8 |
@Override
public Double getBalance(String id) {
if(id == null || "".equals(id.trim())) {
return -1.0;
}
for(Account a : accounts) {
if(id.equals(a.getId())) {
if(a.getBalance() < 0) {
return -1.0;
}
System.out.println("Geted balance is " + a.getBalance() + " RMB.");
return a.getBalance();
}
}
return -1.0;
} | 5 |
public JsonArray getArray(String key) {
Object value = get(key);
if (value instanceof JsonArray) {
return (JsonArray) value;
}
return new JsonArray();
} | 1 |
public void transformBlockInitializer(StructuredBlock block) {
StructuredBlock start = null;
StructuredBlock tail = null;
int lastField = -1;
while (block instanceof SequentialBlock) {
StructuredBlock ib = block.getSubBlocks()[0];
int field = transformOneField(lastField, ib);
if (field < 0)
clazzAnalyzer.addBlockInitializer(lastField + 1, ib);
else
lastField = field;
block = block.getSubBlocks()[1];
}
if (transformOneField(lastField, block) < 0)
clazzAnalyzer.addBlockInitializer(lastField + 1, block);
} | 3 |
public final String getAliasesAsString() {
String aliases = "";
for (String alias : this.aliases) {
if (!aliases.isEmpty()) aliases += ", ";
aliases += alias;
}
return aliases;
} | 2 |
@Override
public void process(Exchange e) throws Exception {
String body = e.getIn().getBody(String.class);
body = body.replaceAll("\\[", "");
body = body.replaceAll("\\]", "");
StringTokenizer tok = new StringTokenizer(body, ",");
Date date=null;
String account=null;
String money=null;
while (tok.hasMoreTokens()) {
String token = tok.nextToken();
token = token.trim();
if (token.contains("key:")) {
String sub =token.substring(token.indexOf(":")+1);
date = new Date(Long.parseLong(sub.trim()));
} else if (token.contains("value:")) {
account =token.substring(token.indexOf(":")+1);
} else if (token.contains("id:")) {
} else {
if (token.length()>0 ) {
try {
Double.parseDouble(token);
money = token;
} catch (NumberFormatException nfe) {
}
}
}
}
e.getIn().setHeader("Account", account);
if (date==null)return;
String dateString = dateFormatter.format(date);
String newline = dateString + "," + account + "," + money;
e.getIn().setBody(newline);
e.getIn().setHeader("Account", account);
} | 7 |
private void setupContents(int width, int height) {
//set up contents
contentsPanel.setBounds(0, 0, contentsWidth, height);
contentsPanel.setPreferredSize(new Dimension(contentsWidth, height));
contentsPanel.repaint();
contentsPanel.setVisible(false);
JButton mainMenuButton = contentsPanel.getMainMenuButton();
mainMenuButton.addMouseMotionListener(genericListener);
mainMenuButton.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
mainMenuShowing = true;
removeAllComponentsInContainer(slidePanel);
slidePanel.stopPlaying();
utilities.stopPlaying();
scaleFactorX = (double)(getSize().width-insets.left-insets.right)/(double)720;
scaleFactorY = (double)(getSize().height-insets.top-insets.bottom)/(double)540;
mainMenuPanel.setBounds(0, 0, getSize().width-insets.left-insets.right, getSize().height-insets.top-insets.bottom);
mainMenuPanel.resizeMainMenu(scaleFactorX, scaleFactorY);
layers.setVisible(false);
mainMenuPanel.setVisible(true);
}
});
final JList<String> contentsList = contentsPanel.getContentsList();
contentsPanel.getContentsList().addMouseMotionListener(genericListener);
contentsPanel.getContentsList().addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
frame.requestFocusInWindow();
if(contentsPanel.getPageListShowing()==true){
if(e.getClickCount() == 1) {
slidePanel.refreshSlide(slideList.getSlideList().get(contentsList.getSelectedIndex()));
contentsList.clearSelection();
}
}else{
slideList = collection.get(contentsList.getSelectedIndex());
slidePanel.loadPresentation(slideList);
slidePanel.refreshSlide(slideList.getSlideList().get(0));
}
}
});
JButton changeButton = contentsPanel.getChangeButton();
changeButton.addMouseMotionListener(genericListener);
changeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
frame.requestFocusInWindow();
contentsPanel.setScrollList(slideList);
}
});
} | 2 |
private void createTreeView(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 1;
gridLayout.marginHeight = gridLayout.marginWidth = 2;
gridLayout.horizontalSpacing = gridLayout.verticalSpacing = 0;
composite.setLayout(gridLayout);
treeScopeLabel = new Label(composite, SWT.BORDER);
treeScopeLabel.setText(FileViewer.getResourceString("details.AllFolders.text"));
treeScopeLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
tree = new Tree(composite, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.SINGLE);
tree.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL));
tree.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent event) {
final TreeItem[] selection = tree.getSelection();
if (selection != null && selection.length != 0) {
TreeItem item = selection[0];
File file = (File) item.getData(TREEITEMDATA_FILE);
notifySelectedDirectory(file);
}
}
public void widgetDefaultSelected(SelectionEvent event) {
final TreeItem[] selection = tree.getSelection();
if (selection != null && selection.length != 0) {
TreeItem item = selection[0];
item.setExpanded(true);
treeExpandItem(item);
}
}
});
tree.addTreeListener(new TreeAdapter() {
public void treeExpanded(TreeEvent event) {
final TreeItem item = (TreeItem) event.item;
final Image image = (Image) item.getData(TREEITEMDATA_IMAGEEXPANDED);
if (image != null) item.setImage(image);
treeExpandItem(item);
}
public void treeCollapsed(TreeEvent event) {
final TreeItem item = (TreeItem) event.item;
final Image image = (Image) item.getData(TREEITEMDATA_IMAGECOLLAPSED);
if (image != null) item.setImage(image);
}
});
createTreeDragSource(tree);
createTreeDropTarget(tree);
} | 6 |
@Override
public void run() {
List<Fetcher> fs = new ArrayList<Fetcher>();
// add shop fetcher
for (String url : this.getInitUrls()) {
Fetcher f = new TBShopFetcher(new RequestWrapper(url,
new TBShopCallback(), null, PriorityEnum.SHOP));
fs.add(f);
}
Map<String, Integer> offered = new HashMap<String, Integer>();
for (Object o : fs) {
Fetcher fetcher = (Fetcher) o;
String fetcherKey = fetcher.getClass().getName();
boolean offeredFlag = false;
do {
try {
offeredFlag = IautosResource.fetchQueue.offer(fetcher,
500, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
getLogger().debug(
"offer " + fetcher.getRequestWrapper().getUrl());
} while (!offeredFlag);
if (offered.containsKey(fetcherKey)) {
offered.put(fetcherKey, offered.get(fetcherKey) + 1);
} else {
offered.put(fetcherKey, 1);
}
}
for (Map.Entry<String, Integer> offer : offered.entrySet()) {
getLogger().info(
"add " + offer.getValue() + " fetcher task :"
+ offer.getKey());
}
} | 6 |
@Override
public void worldChangedAt(Position pos) {
// Immutable cities and units took away a lot of the elegance here...
CityFigure cf = cityFigures.get(pos);
City city = game.getCityAt(pos);
if (city != null){
if (cf != null) editor.drawing().remove(cf);
cf = new CityFigure(city,new Point(GfxConstants.getXFromColumn(pos.getColumn()), GfxConstants.getYFromRow(pos.getRow())));
editor.drawing().add(cf);
cityFigures.put(pos,cf);
}
UnitFigure uf = unitFigures.get(pos);
Unit unit = game.getUnitAt(pos);
if (unit == null && uf != null){
editor.drawing().remove(uf);
unitFigures.remove(pos);
} else if ( unit != null ){
if (uf != null) editor.drawing().remove(uf);
uf = new UnitFigure(unit,new Point(GfxConstants.getXFromColumn(pos.getColumn()), GfxConstants.getYFromRow(pos.getRow())));
editor.drawing().add(uf);
unitFigures.put(pos,uf);
}
} | 6 |
public Instruction getInstruction() {
return this.brain.getInstruction(this.state);
} | 0 |
public void renderCracks(int xPos, int yPos, int damage) {
xPos -= xOffset;
yPos -= yOffset;
int damageSprite = damage / 10;
if (damageSprite > 7) {
damageSprite = 7;
}
for (int y = 0; y < Sprite.CRACKS.SIZE; y++) {
int yp = yPos + y;
for (int x = 0; x < Sprite.CRACKS.SIZE; x++) {
int xp = xPos + x;
if (xp < 0 || xp >= width || yp < 0 || yp >= height) {
continue;
}
int col = Sprite.CRACKS.pixels[x + (y + damageSprite * Sprite.CRACKS.SIZE) * Sprite.CRACKS.SIZE];
if (col == 0xff000000) {
pixels[xp + yp * width] = col;
}
}
}
} | 8 |
@Override
public void run() {
try {
PUserDBAccess pdbAccess = new PUserDBAccess(dbAccess);
Statement stmt;
stmt = dbAccess.getConnection().createStatement();
PUser collaborativeProfile = pdbAccess.getUserProfile(user, null, clientName, true);
Map<String, Float> ftrFreqa = collaborativeProfile.getFtrReqs();
Map<String, Float> ftrVals = collaborativeProfile.getProfile();
HashMap<String, Float> ftrSum = new HashMap<String, Float>();
Map<Set<String>, Float> assocFreqa = collaborativeProfile.getFtrAssocs();
Map<Set<String>, Float> assocSum = new HashMap<Set<String>, Float>();
for (String ftr : ftrVals.keySet()) {
ftrSum.put(ftr, Float.valueOf(1));
}
for (Set<String> ftrSet : assocFreqa.keySet()) {
assocSum.put(ftrSet, Float.valueOf(1));
}
//System.out.println( assocFreqa.size() + " " + assocSum.size() );
String sql = "SELECT * FROM " + DBAccess.UASSOCIATIONS_TABLE + " WHERE " + DBAccess.FIELD_PSCLIENT + "='" + clientName + "' AND " + DBAccess.UASSOCIATIONS_TABLE_FIELD_SRC + "='" + user + "' AND " + DBAccess.UASSOCIATIONS_TABLE_FIELD_TYPE + "=" + DBAccess.RELATION_BINARY_SIMILARITY;
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String otherUser = rs.getString(DBAccess.UASSOCIATIONS_TABLE_FIELD_DST);
float dist = rs.getFloat(DBAccess.UASSOCIATIONS_TABLE_FIELD_WEIGHT);
PUser otherUserProfile = pdbAccess.getUserProfile(otherUser, null, clientName, true);
updateCollaborativeProfile(otherUserProfile, dist, assocFreqa, ftrFreqa, ftrVals, ftrSum, assocSum);
}
rs.close();
sql = "SELECT * FROM " + DBAccess.UASSOCIATIONS_TABLE + " WHERE " + DBAccess.FIELD_PSCLIENT + "='" + clientName + "' AND " + DBAccess.UASSOCIATIONS_TABLE_FIELD_DST + "='" + user + "' AND " + DBAccess.UASSOCIATIONS_TABLE_FIELD_TYPE + "=" + DBAccess.RELATION_BINARY_SIMILARITY;
rs = stmt.executeQuery(sql);
while (rs.next()) {
String otherUser = rs.getString(DBAccess.UASSOCIATIONS_TABLE_FIELD_SRC);
float dist = rs.getFloat(DBAccess.UASSOCIATIONS_TABLE_FIELD_WEIGHT);
PUser otherUserProfile = pdbAccess.getUserProfile(otherUser, null, clientName, true);
updateCollaborativeProfile(otherUserProfile, dist, assocFreqa, ftrFreqa, ftrVals, ftrSum, assocSum);
}
rs.close();
//if (ftrVals.size() != ftrFreqa.size()) {
// System.out.println(" sizes " + ftrVals.size() + " " + ftrFreqa.size());
// System.exit(- 1);
//}
sql = "INSERT DELAYED INTO " + DBAccess.CFPROFILE_TABLE + " VALUES (?,?,?,?,'" + clientName + "')";
PreparedStatement cfFtrStmt = dbAccess.getConnection().prepareStatement(sql);
cfFtrStmt.setString(1, this.user);
Set<Entry<String, Float>> entries = ftrVals.entrySet();
for (Iterator<Entry<String, Float>> it = entries.iterator(); it.hasNext();) {
Map.Entry<String, Float> entry = it.next();
String feature = entry.getKey();
float val = entry.getValue() / ftrSum.get(feature);
cfFtrStmt.setString(2, feature);
cfFtrStmt.setString(3, val + "");
cfFtrStmt.setFloat(4, val);
cfFtrStmt.addBatch();
//System.out.println( cfFtrStmt.toString() );
}
cfFtrStmt.executeBatch();
cfFtrStmt.close();
sql = "INSERT DELAYED INTO " + DBAccess.CFFEATURE_STATISTICS_TABLE + " VALUES (?,?," + DBAccess.STATISTICS_FREQUENCY + ",?,'" + clientName + "')";
PreparedStatement cfFtrfrStmt = dbAccess.getConnection().prepareStatement(sql);
cfFtrfrStmt.setString(1, this.user);
entries = ftrFreqa.entrySet();
for (Iterator<Entry<String, Float>> it = entries.iterator(); it.hasNext();) {
Map.Entry<String, Float> entry = it.next();
String feature = entry.getKey();
float val = entry.getValue() / ftrSum.get(feature);
cfFtrfrStmt.setString(2, feature);
cfFtrfrStmt.setFloat(3, val);
cfFtrfrStmt.addBatch();
}
cfFtrfrStmt.executeBatch();
cfFtrfrStmt.close();
sql = "INSERT DELAYED INTO " + DBAccess.CFFTRASSOCIATIONS_TABLE + " VALUES (?,?,?," + DBAccess.RELATION_SIMILARITY + ",?,'" + clientName + "')";
PreparedStatement cfAssocFtrStmt = dbAccess.getConnection().prepareStatement(sql);
cfAssocFtrStmt.setString(4, this.user);
Set<Entry<Set<String>, Float>> asentries = assocFreqa.entrySet();
//System.out.println( assocFreqa.size() + " " + assocSum.size() );
for (Iterator<Entry<Set<String>, Float>> it = asentries.iterator(); it.hasNext();) {
Map.Entry<Set<String>, Float> entry = it.next();
Set<String> features = entry.getKey();
float val = entry.getValue() / assocSum.get(features);
Iterator<String> ftrI = features.iterator();
cfAssocFtrStmt.setString(1, ftrI.next());
cfAssocFtrStmt.setString(2, ftrI.next());
cfAssocFtrStmt.setFloat(3, val);
cfAssocFtrStmt.addBatch();
}
cfAssocFtrStmt.executeBatch();
cfAssocFtrStmt.close();
stmt.close();
} catch (SQLException ex) {
WebServer.win.log.error(ex.toString());
System.exit(0);
}
WebServer.win.log.echo("Processing for " + user + " Collaborative profile completed");
} | 8 |
public int doEndTag() throws JspException {
DateTimeZone dateTimeZone = null;
if (value == null) {
dateTimeZone = DateTimeZone.UTC;
} else if (value instanceof String) {
try {
dateTimeZone = DateTimeZone.forID((String) value);
} catch (IllegalArgumentException iae) {
dateTimeZone = DateTimeZone.UTC;
}
} else {
dateTimeZone = (DateTimeZone) value;
}
if (var != null) {
pageContext.setAttribute(var, dateTimeZone, scope);
} else {
Config.set(pageContext, DateTimeZoneSupport.FMT_TIME_ZONE,
dateTimeZone, scope);
}
return EVAL_PAGE;
} | 4 |
public boolean containsObject() throws JSONException {
boolean result = false;
Iterator i = this.map.values().iterator();
while (!result && i.hasNext()) {
Object value = i.next();
result = value instanceof JSONObject
|| value instanceof JSONArray
&& ((JSONArray) value).length()>0
&& ((JSONArray) value).get(0) instanceof JSONObject;
}
return result;
} | 5 |
public Object nextValue() throws JSONException {
char c = this.nextClean();
String string;
switch (c) {
case '"':
case '\'':
return this.nextString(c);
case '{':
this.back();
return new JSONObject(this);
case '[':
this.back();
return new JSONArray(this);
}
/*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number. An implementation (such as this one)
* is allowed to also accept non-standard forms.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
StringBuffer sb = new StringBuffer();
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
sb.append(c);
c = this.next();
}
this.back();
string = sb.toString().trim();
if ("".equals(string)) {
throw this.syntaxError("Missing value");
}
return JSONObject.stringToValue(string);
} | 7 |
@Override
public boolean tick(Tickable ticking, int tickID)
{
if(!super.tick(ticking,tickID))
return false;
if(tickID==Tickable.TICKID_MOB)
{
if(fullRound)
{
final MOB mob=(MOB)affected;
if(!mob.isInCombat())
unInvoke();
if(mob.location()!=null)
{
if(mob.location().show(mob,null,this,CMMsg.MSG_OK_VISUAL,L("<S-YOUPOSS> successful defence <S-HAS-HAVE> allowed <S-HIM-HER> to disengage.")))
{
final MOB victim=mob.getVictim();
if((victim!=null)&&(victim.getVictim()==mob))
victim.makePeace(true);
mob.makePeace(true);
unInvoke();
}
}
}
fullRound=true;
}
return true;
} | 8 |
public static void main(String args[]) {
QuickSort quick = new QuickSort();
Scanner scan = new Scanner(System.in);
int N, i;
System.out.println("Enter value of N");
N = scan.nextInt();
int array[] = new int[N];
System.out.println("Enter " + N + " Elements");
for (i = 0; i < N; i++)
array[i] = scan.nextInt();
quick.sort(array);
System.out.println("Sorted Array: ");
for (i = 0; i < N; i++)
System.out.print(array[i] + " ");
} | 2 |
public static String getDefaultPasswordString() {
String random = RandomStringUtils.randomAlphanumeric(8);
return random;
} | 0 |
public long getLatency(int clientId) {
synchronized(CONNECTION_LOCK) {
ClientInfo client = clients.get(clientId);
if(client != null)
return client.getLatency();
return -1;
}
} | 1 |
private void generatePercentComparisonLines(
TreeMap<Float, Point2D.Float> marketToStockPairing) {
Point2D.Float dailyComparisonInitial = marketToStockPairing
.firstEntry().getValue();
boolean first = true;
for (Entry<Float, Point2D.Float> ent : marketToStockPairing.entrySet()) {
if (first) {
first = false;
continue;
}
Point2D.Float dailyComparisonFinal = ent.getValue();
int individualDelta = (int) (calculateDifferenceIndividual(
dailyComparisonInitial, dailyComparisonFinal) * 1000);
int marketDelta = (int) (calculateDifferenceMarket(
dailyComparisonInitial, dailyComparisonFinal) * 1000);
int individualToMarketDelta = (int) ((individualDelta - marketDelta));
// System.out.println(
// "percent change comparison: "+individualToMarketDelta);
Point2D.Float startPoint = timePathPoints.get(ent.getKey());
if(startPoint==null)
continue;
float scalingMultiple = 2.5f;
float individualX = startPoint.x;
float individualY = startPoint.y;
float changeX = individualX;
float changeY = individualY - marketDelta * scalingMultiple;
Line2D.Float comparisonLineMarket = new Line2D.Float(individualX,
individualY, changeX, changeY);
float changeYindividual = individualY - individualDelta
* scalingMultiple;
Line2D.Float comparisonLineIndividual = new Line2D.Float(
individualX, individualY, changeX, changeYindividual);
float changeYMarketToIndividual = individualY
- individualToMarketDelta * scalingMultiple;
Line2D.Float comparisonLineIndividualToMarket = new Line2D.Float(
individualX, individualY, changeX,
changeYMarketToIndividual);
// if (individualToMarketDelta >
// PERCENT_CHANGE_COMPARISON_RANGE_ABS)
// individualToMarketDelta = PERCENT_CHANGE_COMPARISON_RANGE_ABS;
// if (individualToMarketDelta <
// -PERCENT_CHANGE_COMPARISON_RANGE_ABS)
// individualToMarketDelta = -PERCENT_CHANGE_COMPARISON_RANGE_ABS;
// Color relativeColor = COLOR_MAP.get(individualToMarketDelta);
if (marketDelta < 0)
PERCENT_CHANGE_COMPARISON_LINES.put(comparisonLineMarket,
FAINT_RED_BLUE);
else
PERCENT_CHANGE_COMPARISON_LINES.put(comparisonLineMarket,
FAINT_GREEN_BLUE);
if (individualDelta < 0)
PERCENT_CHANGE_COMPARISON_LINES.put(comparisonLineIndividual,
FAINT_RED);
else
PERCENT_CHANGE_COMPARISON_LINES.put(comparisonLineIndividual,
FAINT_GREEN);
if (individualToMarketDelta > 0)
PERCENT_CHANGE_COMPARISON_LINES.put(
comparisonLineIndividualToMarket, Color.green);
else
PERCENT_CHANGE_COMPARISON_LINES.put(
comparisonLineIndividualToMarket, Color.red);
dailyComparisonInitial = dailyComparisonFinal;
}
} | 6 |
private LISP_object read_from(LinkedList<String> tokens)throws Exception{
if (tokens.size() == 0){
throw new Exception("unexpected EOF while reading");
}
String token = tokens.poll();
if (token.equals("")){
do{
token = tokens.poll();
}while (token.equals(""));
}
if ("(".equals(token)){
LISP_object L = new LISP_object();
L.list = new LinkedList();
while (!tokens.getFirst().equals(")")){
//System.out.println("lol " + tokens.getFirst());
if (tokens.getFirst().equals("\n"))
{
//System.out.println("lol");
tokens.poll();
}
LISP_object l = read_from(tokens);
L.list.add(l);
}
tokens.poll();
return L;
}
else
if (")".equals(token))
throw new Exception("unexpected EOF while reading");
else{
LISP_object l = new LISP_object();
l.var = atom(token);
return l;
}
} | 7 |
public static ArrayList<ArrayList<Field>> generateMap(int maxFields, int tileSize) {
ArrayList<ArrayList<Field>> map = new ArrayList<ArrayList<Field>>();
Random random = new Random();
double center = (double) maxFields/2;
for(int i = 0; i < maxFields; i++){
double probI = Math.abs(center-(i<center ? (i==center-0.5 ? i+0.5 : i+1) : i)); //position to be land/water (min = 0 | max = center-1)
ArrayList<Field> fieldList = new ArrayList<Field>();
for(int j = 0; j < maxFields; j++) {
double probJ = Math.abs(center-(j<center ? (j==center-0.5 ? j+0.5 : j+1) : j)); //position to be land/water (min = 0 | max = center-1)
double zeroToCenter = random.nextDouble()*(center-1);
double probability = (probI==probJ ? (probI+probJ)-0.75 : probI+probJ);
fieldList.add(zeroToCenter < probability ? new Ocean(tileSize) : new Land(tileSize));
}
map.add(fieldList);
}
return map;
} | 8 |
public Element drawShape(int x, int y, int w, int h,
Map<String, Object> style)
{
String fillColor = mxUtils
.getString(style, mxConstants.STYLE_FILLCOLOR);
String strokeColor = mxUtils.getString(style,
mxConstants.STYLE_STROKECOLOR);
float strokeWidth = (float) (mxUtils.getFloat(style,
mxConstants.STYLE_STROKEWIDTH, 1) * scale);
// Draws the shape
String shape = mxUtils.getString(style, mxConstants.STYLE_SHAPE);
Element elem = document.createElement("div");
if (shape.equals(mxConstants.SHAPE_LINE))
{
String direction = mxUtils.getString(style,
mxConstants.STYLE_DIRECTION, mxConstants.DIRECTION_EAST);
if (direction.equals(mxConstants.DIRECTION_EAST)
|| direction.equals(mxConstants.DIRECTION_WEST))
{
y = Math.round(y + h / 2);
h = 1;
}
else
{
x = Math.round(y + w / 2);
w = 1;
}
}
if (mxUtils.isTrue(style, mxConstants.STYLE_SHADOW, false)
&& fillColor != null)
{
Element shadow = (Element) elem.cloneNode(true);
String s = "overflow:hidden;position:absolute;" + "left:"
+ String.valueOf(x + mxConstants.SHADOW_OFFSETX) + "px;"
+ "top:" + String.valueOf(y + mxConstants.SHADOW_OFFSETY)
+ "px;" + "width:" + String.valueOf(w) + "px;" + "height:"
+ String.valueOf(h) + "px;background:"
+ mxConstants.W3C_SHADOWCOLOR
+ ";border-style:solid;border-color:"
+ mxConstants.W3C_SHADOWCOLOR + ";border-width:"
+ String.valueOf(Math.round(strokeWidth)) + ";";
shadow.setAttribute("style", s);
appendHtmlElement(shadow);
}
if (shape.equals(mxConstants.SHAPE_IMAGE))
{
String img = getImageForStyle(style);
if (img != null)
{
elem = document.createElement("img");
elem.setAttribute("border", "0");
elem.setAttribute("src", img);
}
}
// TODO: Draw other shapes. eg. SHAPE_LINE here
String s = "overflow:hidden;position:absolute;" + "left:"
+ String.valueOf(x) + "px;" + "top:" + String.valueOf(y)
+ "px;" + "width:" + String.valueOf(w) + "px;" + "height:"
+ String.valueOf(h) + "px;background:" + fillColor + ";"
+ ";border-style:solid;border-color:" + strokeColor
+ ";border-width:" + String.valueOf(Math.round(strokeWidth))
+ ";";
elem.setAttribute("style", s);
appendHtmlElement(elem);
return elem;
} | 7 |
public void initByArray(int... key) {
@SuppressWarnings("unused")
int lag = N32 >= 623 ? 11 : (N32 >= 68 ? 7 : (N32 >= 39 ? 5 : 3)) ;
int mid = (N32 - lag) / 2;
for (int i = sfmt.length - 1; i >= 0; i--)
sfmt[i] = 0x8b8b8b8b;
int count = key.length >= N32 ? key.length : N32 - 1, r = func1(0x8b8b8b8b);
sfmt[mid] += r;
r += key.length;
sfmt[mid + lag] += r;
sfmt[0] = r;
int i = 1, j = 0;
for (; j < count && j < key.length; j++) {
r = func1(sfmt[i] ^ sfmt[(i + mid) % N32]
^ sfmt[(i + N32 - 1) % N32]);
sfmt[(i + mid) % N32] += r;
r += key[j] + i;
sfmt[(i + mid + lag) % N32] += r;
sfmt[i] = r;
i = (i + 1) % N32;
}
for (; j < count; j++) {
r = func1(sfmt[i] ^ sfmt[(i + mid) % N32]
^ sfmt[(i + N32 - 1) % N32]);
sfmt[(i + mid) % N32] += r;
r += i;
sfmt[(i + mid + lag) % N32] += r;
sfmt[i] = r;
i = (i + 1) % N32;
}
for (j = 0; j < N32; j++) {
r = func2(sfmt[i] + sfmt[(i + mid) % N32]
+ sfmt[(i + N32 - 1) % N32]);
sfmt[(i + mid) % N32] ^= r;
r -= i;
sfmt[(i + mid + lag) % N32] ^= r;
sfmt[i] = r;
i = (i + 1) % N32;
}
periodCertification();
idx = N32;
} | 9 |
public JCheckBox getjCheckBoxPracticiens() {
return jCheckBoxPracticiens;
} | 0 |
public static int crypto_core(byte[] outv, byte[] inv, byte[] k, byte[] c)
{
int x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15;
int j0, j1, j2, j3, j4, j5, j6, j7, j8, j9, j10, j11, j12, j13, j14, j15;
int i;
j0 = x0 = load_littleendian(c, 0);
j1 = x1 = load_littleendian(k, 0);
j2 = x2 = load_littleendian(k, 4);
j3 = x3 = load_littleendian(k, 8);
j4 = x4 = load_littleendian(k, 12);
j5 = x5 = load_littleendian(c, 4);
j6 = x6 = load_littleendian(inv, 0);
j7 = x7 = load_littleendian(inv, 4);
j8 = x8 = load_littleendian(inv, 8);
j9 = x9 = load_littleendian(inv, 12);
j10 = x10 = load_littleendian(c, 8);
j11 = x11 = load_littleendian(k, 16);
j12 = x12 = load_littleendian(k, 20);
j13 = x13 = load_littleendian(k, 24);
j14 = x14 = load_littleendian(k, 28);
j15 = x15 = load_littleendian(c, 12);
for (i = ROUNDS; i > 0; i -= 2)
{
x4 ^= rotate(x0 + x12, 7);
x8 ^= rotate(x4 + x0, 9);
x12 ^= rotate(x8 + x4, 13);
x0 ^= rotate(x12 + x8, 18);
x9 ^= rotate(x5 + x1, 7);
x13 ^= rotate(x9 + x5, 9);
x1 ^= rotate(x13 + x9, 13);
x5 ^= rotate(x1 + x13, 18);
x14 ^= rotate(x10 + x6, 7);
x2 ^= rotate(x14 + x10, 9);
x6 ^= rotate(x2 + x14, 13);
x10 ^= rotate(x6 + x2, 18);
x3 ^= rotate(x15 + x11, 7);
x7 ^= rotate(x3 + x15, 9);
x11 ^= rotate(x7 + x3, 13);
x15 ^= rotate(x11 + x7, 18);
x1 ^= rotate(x0 + x3, 7);
x2 ^= rotate(x1 + x0, 9);
x3 ^= rotate(x2 + x1, 13);
x0 ^= rotate(x3 + x2, 18);
x6 ^= rotate(x5 + x4, 7);
x7 ^= rotate(x6 + x5, 9);
x4 ^= rotate(x7 + x6, 13);
x5 ^= rotate(x4 + x7, 18);
x11 ^= rotate(x10 + x9, 7);
x8 ^= rotate(x11 + x10, 9);
x9 ^= rotate(x8 + x11, 13);
x10 ^= rotate(x9 + x8, 18);
x12 ^= rotate(x15 + x14, 7);
x13 ^= rotate(x12 + x15, 9);
x14 ^= rotate(x13 + x12, 13);
x15 ^= rotate(x14 + x13, 18);
}
x0 += j0;
x1 += j1;
x2 += j2;
x3 += j3;
x4 += j4;
x5 += j5;
x6 += j6;
x7 += j7;
x8 += j8;
x9 += j9;
x10 += j10;
x11 += j11;
x12 += j12;
x13 += j13;
x14 += j14;
x15 += j15;
store_littleendian(outv, 0, x0);
store_littleendian(outv, 4, x1);
store_littleendian(outv, 8, x2);
store_littleendian(outv, 12, x3);
store_littleendian(outv, 16, x4);
store_littleendian(outv, 20, x5);
store_littleendian(outv, 24, x6);
store_littleendian(outv, 28, x7);
store_littleendian(outv, 32, x8);
store_littleendian(outv, 36, x9);
store_littleendian(outv, 40, x10);
store_littleendian(outv, 44, x11);
store_littleendian(outv, 48, x12);
store_littleendian(outv, 52, x13);
store_littleendian(outv, 56, x14);
store_littleendian(outv, 60, x15);
return 0;
} | 1 |
public void start() {
Random random = new Random();
Scanner scanner = new Scanner(System.in);
while ( true ) {
Long maxId = null;
float maxJC = Float.MIN_VALUE;
float jc;
System.out.print(">>> ");
String humanSay = scanner.nextLine();
//System.out.println("For line : " + humanSay);
//System.out.println("Set is : " + stringToSet(humanSay.toLowerCase()));
HashSet<String> humanSaySet = stringToSet(humanSay.toLowerCase());
HashSet<String> union = new HashSet<String>();
HashSet<String> intersection = new HashSet<String>();
for( Long id : conversationTweetIds ) {
union.clear();
intersection.clear();
union.addAll(humanSaySet);
intersection.addAll(humanSaySet);
HashSet<String> candidateSay = tweetIdVsSet.get(id);
union.addAll(candidateSay);
intersection.retainAll(candidateSay);
jc = ((float)candidateSay.size()) * ((float) intersection.size() / (float)union.size());
//System.out.println("JC = " + jc);
if( jc > maxJC ) {
maxJC = jc;
maxId = id;
//System.out.println("maxJC = " + maxJC + " and maxId = " + maxId);
//System.out.println("Inter : " + intersection + " and Union : " + union);
}
}
if( maxId == null ) {
System.out.println("Okay ... I c");
continue;
}
Long replyId = 0L;
LinkedHashSet<Long> possibleReplies = adjacencyList.get(maxId);
if( possibleReplies == null ) {
System.out.println("Okay ... I c");
}
else if(possibleReplies.size() > 0 ) {
Long[] arr = ((Long[]) possibleReplies.toArray());
int size = arr.length;
replyId = arr[((random.nextInt() % size) + (random.nextInt() % size)) % arr.length];
System.out.println(tweetIdVsTweetText.get(replyId));
}
else {
System.out.println(tweetIdVsTweetText.get(maxId));
}
}
} | 6 |
public static PreparedStatement createPreparedStatement(final Connection con, final String sql,
final boolean returnKeys, final Object... args) throws SQLException {
PreparedStatement ps;
if (returnKeys) {
ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
} else {
ps = con.prepareStatement(sql);
}
if (args != null) {
for (int i = 0; i < args.length; i++) {
Object arg = args[i];
setParameterValue(ps, i + 1, arg);
}
}
return ps;
} | 3 |
public static void setSpeedHost(String host) {
if (host.length() > 0 && !host.substring(host.length() - 1).equals("/")) {
host += "/";
}
getInstance().speedHost = host;
} | 2 |
private int readInt()
{
int ret = readByteAsInt();
int tmp;
if (ret < 128)
{
return ret;
}
else
{
ret = (ret & 0x7f) << 7;
tmp = readByteAsInt();
if (tmp < 128)
{
ret = ret | tmp;
}
else
{
ret = (ret | tmp & 0x7f) << 7;
tmp = readByteAsInt();
if (tmp < 128)
{
ret = ret | tmp;
}
else
{
ret = (ret | tmp & 0x7f) << 8;
tmp = readByteAsInt();
ret = ret | tmp;
}
}
}
// Sign extend
int mask = 1 << 28;
int r = -(ret & mask) | ret;
return r;
} | 3 |
@Test
public void testSendMessageToListWithQueue() {
LOGGER.log(Level.INFO, "----- STARTING TEST testSendMessageToListWithQueue -----");
String client_hash = "";
String client_hash2 = "";
String server_hash = "";
String server_hash2 = "";
try {
server1.setUseMessageQueues(true);
} catch (TimeoutException e) {
exception = true;
}
try {
server1.startThread();
} catch (IOException | ServerSocketCloseException | FeatureNotUsedException e) {
exception = true;
}
waitListenThreadStart(server1);
Assert.assertTrue(server1.getListenThread().getRun(), "ListenThread did not start in time");
try {
client_hash = server2.addSocket("127.0.0.1", port);
} catch (IOException | TimeoutException e) {
exception = true;
}
waitSocketThreadAddNotEmpty(server2);
waitSocketThreadAddNotEmpty(server1);
server_hash = getServerLastSocketHash(server1);
waitSocketThreadState(server1, server_hash, SocketThread.CONFIRMED);
waitMessageQueueAddNotEmpty(server1);
waitMessageQueueState(server1, server_hash, MessageQueue.RUNNING);
try {
client_hash2 = server2.addSocket("127.0.0.1", port);
} catch (IOException | TimeoutException e) {
exception = true;
}
waitSocketThreadState(server2, client_hash2, SocketThread.CONFIRMED);
boolean loop = true;
Timing new_timer = new Timing();
while (loop) {
if (server1.getSocketList().size() == 2) {
loop = false;
} else if (new_timer.getTime() > 5000) {
exception = true;
loop = false;
}
}
Assert.assertFalse(exception, "SocketThread was not added to server1");
for (SocketThread socket : server1.getSocketList().values()) {
if (socket.getHash().compareTo(server_hash) != 0) {
server_hash2 = socket.getHash();
}
}
waitSocketThreadState(server1, server_hash2, SocketThread.CONFIRMED);
waitMessageQueueState(server1, server_hash2, MessageQueue.RUNNING);
ArrayList<String> sockets = new ArrayList<String>();
sockets.add(server_hash);
sockets.add(server_hash2);
server1.sendMessage("TEST", sockets);
waitTime();
Assert.assertTrue(server1.containsHash(server_hash), "Socket1 on server1 has closed");
Assert.assertTrue(server1.containsHash(server_hash2), "Socket2 on server1 has closed");
Assert.assertTrue(server2.containsHash(client_hash), "Socket1 on server2 has closed");
Assert.assertTrue(server2.containsHash(client_hash2), "Socket2 on server2 has closed");
Assert.assertFalse(server1.getQueueList().get(server_hash).getMessages().contains("TEST"), "Message was not sent on socket1");
Assert.assertFalse(server1.getQueueList().get(server_hash2).getMessages().contains("TEST"), "Message was not sent on socket2");
Assert.assertFalse(exception, "Exception found");
LOGGER.log(Level.INFO, "----- TEST testSendMessageToListWithQueue COMPLETED -----");
} | 9 |
private void parseSchemaElement(String element) throws ParseException {
char elementId = element.charAt(0);
String elementTail = element.substring(1);
validateSchemaElementId(elementId);
if (isBooleanSchemaElement(elementTail))
parseBooleanSchemaElement(elementId);
else if (isStringSchemaElement(elementTail))
parseStringSchemaElement(elementId);
else if (isIntegerSchemaElement(elementTail)) {
parseIntegerSchemaElement(elementId);
} else {
throw new ParseException(
String.format("Argument: %c has invalid format: %s.",
elementId, elementTail), 0);
}
} | 3 |
private void paintMainMenu(Graphics2D g){
g.setFont(menuFont);
if (inHighScores){
drawHighScores(g);
}else if (inOptions){
drawOptions(g);
}else{
drawMenu(g);
}
} | 2 |
public static int showConfirmDialog(String msg, String title, int option, int type){
if (type < 0 || type > 2) type = 1;
return JOptionPane.showConfirmDialog(null, msg, (title == null ? "Confirm message" : title),
option, type);
} | 3 |
public void runGuesses(ArrayList<FaceData> data) {
for (FaceData fd : data) {
buildNetwork(fd);
boolean guess = true;
int[] acts = new int[4];
for (int i = 0; i < 4; i++) {
double act = calculateActivation(i + 1);
if (act == 1) {
acts[i]++;
guess = false;
}
}
if (isOnlyOneAct(acts)) {
for (int i = 0; i < acts.length; i++) {
if (acts[i] == 1) {
System.out.println(fd.getImageID() + " " + (i + 1));
}
}
} else if (!guess) {
Random r = new Random();
int g = r.nextInt(4);
while (acts[g] == 0) {
g = r.nextInt(4);
}
System.out.println(fd.getImageID() + " " + (g + 1));
} else {
Random r = new Random();
int g = r.nextInt(3) + 1;
System.out.println(fd.getImageID() + " " + g);
}
}
} | 8 |
private String compileCommand(Node command) throws CompilationErrorException {
StringBuilder builder = new StringBuilder();
switch (command.getNodeType()) {
case ASSIGNED:
builder.append(compileAssignValue(command));
break;
case RETURN:
builder.append(compileReturn(command));
break;
case PRINT:
builder.append(compilePrint(command));
break;
case DECLARE:
builder.append(compileVariableDeclaration(command));
break;
case METHOD_CALL:
builder.append(compileMethodCall((MethodCallNode) command));
break;
case CONDITIONAL_CONSTRUCTION:
builder.append(compileConditionalConstruction((ConditionalConstructionNode) command));
break;
case WHILE_BLOCK:
builder.append(compileWhileBlock((WhileBlockNode) command));
break;
default:
builder.append(CodeBuilder.CODE_INDENT)
.append("UNEXPECTED NODE\n");
break;
}
return builder.toString();
} | 7 |
public JButton getPrevButton(){
if(prevButton == null){
for(Component comp : getComponents()){
if(comp instanceof JButton){
if("Spinner.previousButton".equals(comp.getName())){
prevButton = (JButton) comp;
}
}
}
}
return prevButton;
} | 4 |
@Override
public boolean equals(Object o) {
if(!(o instanceof MapEntry)) {
return false;
}
MapEntry<?, ?> me = (MapEntry<?, ?>)o;
return (key == null ? me.getKey() == null : key.equals(me.getKey()))
&& (value == null ? me.getValue() == null : value.equals(me
.getValue()));
} | 8 |
public boolean isMoreOuterThan(ClassDeclarer declarer) {
ClassDeclarer ancestor = declarer;
while (ancestor != null) {
if (ancestor == this)
return true;
ancestor = ancestor.getParent();
}
return false;
} | 2 |
@EventHandler
public void WitchSlow(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.getWitchConfig().getDouble("Witch.Slow.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getWitchConfig().getBoolean("Witch.Slow.Enabled", true) && damager instanceof Witch && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, plugin.getWitchConfig().getInt("Witch.Slow.Time"), plugin.getWitchConfig().getInt("Witch.Slow.Power")));
}
} | 6 |
public Vector2f tileForce(Vector2f pos){
Vector2f temp = TileUtil.getCoordinate(pos);
Vector2f force = new Vector2f(0,0);
for(Tile tile : tileList ) {
if (TileUtil.getCoordinate(tile.getPosition()).equals(temp)){
force = tile.getForce();
}
}
return force;
} | 2 |
public PNGDecoder(InputStream input) throws IOException {
this.input = input;
this.crc = new CRC32();
this.buffer = new byte[4096];
readFully(buffer, 0, SIGNATURE.length);
if(!checkSignature(buffer)) {
throw new IOException("Not a valid PNG file");
}
openChunk(IHDR);
readIHDR();
closeChunk();
searchIDAT: for(;;) {
openChunk();
switch (chunkType) {
case IDAT:
break searchIDAT;
case PLTE:
readPLTE();
break;
case tRNS:
readtRNS();
break;
}
closeChunk();
}
if(colorType == COLOR_INDEXED && palette == null) {
throw new IOException("Missing PLTE chunk");
}
} | 7 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.