method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
33c56b7e-86f8-43f0-86e4-c91bf0ab0d2f | 3 | private boolean htaccessGranted( URI requestURI,
HTTPHeaders headers,
HypertextAccessFile htaccess,
File directory,
Map<String,BasicType> additionalSettings,
Map<String,BasicType> optionalReturnSettings,
Environment<String,BasicType> session )
throws IOException,
AuthorizationException,
ConfigurationException {
// Does the .htaccess have an AuthType directive at all?
// (there are also .htaccess file for basic configuration purposes)
if( htaccess.getAuthType() == null )
return true;
BasicType authMethod = additionalSettings.get( Constants.KEY_AUTHORIZATION_METHOD );
if( authMethod == null ) { // || authUser == null || authPass == null )
return false; // No authorization credentials passed (at least one missing)
}
try {
return this.hypertextAccessHandler.accessGranted( requestURI,
headers,
htaccess,
authMethod.getString(), // Wrapper cannot be null here
additionalSettings,
optionalReturnSettings
);
} catch( MissingParamException e ) {
// The client did not send all essential credentials.
throw new AuthorizationException( AuthorizationException.MISSING_PARAM, e.getMessage() );
}
} |
fd26604a-ad42-446e-8ca0-6d09e03a78a5 | 4 | public boolean mouseIn(int mx, int my)
{
if (xpos <= mx && mx <= xpos + width && ypos <= my
&& my <= ypos + height)
return true;
return false;
} |
ed6399ba-52ad-4cd2-b869-711ab8210238 | 9 | private int HuffmanValue(int table[],int temp[], int index[], InputStream in) throws IOException{
int code, input ,mask=0xFFFF;
if(index[0]<8){
temp[0] <<= 8;
input = get8(in);
if(input==0xFF){
marker=get8(in);
if(marker!=0) marker_index=9;
}
temp[0] |= input;
} else index[0] -= 8;
code=table[temp[0] >> index[0]];
if((code&MSB)!=0){
if(marker_index!=0){ marker_index=0; return 0xFF00|marker;}
temp[0] &= (mask >> (16-index[0]));
temp[0] <<= 8;
input = get8(in);
if(input==0xFF){
marker=get8(in);
if(marker!=0) marker_index=9;
}
temp[0] |= input;
code=table[(code&0xFF)*256 + (temp[0] >> index[0])];
index[0]+=8;
}
index[0] += 8 - (code>>8);
if(index[0]<0) error("index="+index[0]+" temp="+temp[0]+" code="+code+" in HuffmanValue()");
if(index[0] < marker_index){ marker_index=0; return 0xFF00|marker;}
temp[0] &= ( mask >> (16-index[0]) );
return code&0xFF;
} |
e2f27ab0-170c-4663-b825-98d1b51a3d0f | 9 | public String searchANDdescribe() {
StringBuilder result = new StringBuilder();
for(K k : this) {
if(k.getClass().equals(PapaBuilding.class)){
result.append(((PapaBuilding) k).getAttributes());
}else if(k.getClass().equals(PapaBicho.class)){
result.append(((PapaBicho) k).getAttributes());
}else if(k.getClass().equals(Monk.class)){
result.append(((PapaBicho) k).getAttributes());
}else if(k.getClass().equals(Harvester.class)){
result.append(((PapaBicho) k).getAttributes());
}else if (k.getClass().equals(Healer.class)){
result.append(((PapaBicho) k).getAttributes());
}else if(k.getClass().equals(Kamikaze.class)){
result.append(((PapaBicho) k).getAttributes());
}else if(k.getClass().equals(Base.class)){
result.append(((PapaBuilding) k).getAttributes());
}else if (k.getClass().equals(House.class)){
result.append(((PapaBuilding) k).getAttributes());
}
}
return result.toString();
} |
2acc69b2-99a6-4394-b334-c8e1979a8f30 | 7 | private void toggleRemoveSelection(TreePath path) {
Stack stack = new Stack();
TreePath parent = path.getParentPath();
while (parent != null && !isPathSelected(parent)) {
stack.push(parent);
parent = parent.getParentPath();
}
if (parent != null) {
stack.push(parent);
} else {
super.removeSelectionPaths(new TreePath[] { path });
return;
}
while (!stack.isEmpty()) {
TreePath temp = (TreePath) stack.pop();
TreePath peekPath = stack.isEmpty() ? path : (TreePath) stack
.peek();
Object node = temp.getLastPathComponent();
Object peekNode = peekPath.getLastPathComponent();
int childCount = model.getChildCount(node);
for (int i = 0; i < childCount; i++) {
Object childNode = model.getChild(node, i);
if (childNode != peekNode) {
super.addSelectionPaths(new TreePath[] { temp
.pathByAddingChild(childNode) });
}
}
}
super.removeSelectionPaths(new TreePath[] { parent });
} |
db9cdb67-7e5a-40d4-af15-589aad30b5e2 | 5 | @Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Municipality)) {
return false;
}
Municipality other = (Municipality) object;
if ((this.municipalityID == null && other.municipalityID != null) || (this.municipalityID != null && !this.municipalityID.equals(other.municipalityID))) {
return false;
}
return true;
} |
767b4ede-af34-48cd-bebf-3168aa9d9f1d | 0 | public void setFirstName(String firstName) {
this.firstName = firstName;
} |
a217fd21-4e90-468c-ab0c-36d26b18283f | 2 | private void promote(Position pos) {
if (board.getFieldAt(pos) == Board.BLACK_REGULAR_PIECE) {
board.changeFieldAt(pos, Board.BLACK_KING);
} else if (board.getFieldAt(pos) == Board.WHITE_REGULAR_PIECE) {
board.changeFieldAt(pos, Board.WHITE_KING);
}
} |
c9cd299c-3bc6-4e75-b31f-056a60af6bf7 | 6 | public void checkPairs( Hand hand, Hand handP, String name ) {
ArrayList<Card> alC = hand.getCards();
for (int i = 0; i < alC.size(); i++) {
Card checker = alC.get(i);
for (int n = 0; n < alC.size(); n++ ) {
if ( n != i && checker.equals( alC.get(n)) ) {
Card type = alC.get( n );
System.out.println( name + " has a pair of " + type.getFace() + "s" );
if ( n > i ) {
handP.add( hand.draw( n ) );
handP.add( hand.draw( i ) );
}
else {
handP.add( hand.draw( i ) );
handP.add( hand.draw( n ) );
}
if (name.equals("Player")) {
reportHand();
}
}
}
}
} |
c4429e7d-7d21-45f1-9192-b083612304ff | 7 | public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == 127) {
sim.doDelete();
return;
}
if (e.getKeyChar() > ' ' && e.getKeyChar() < 127) {
Class c = sim.shortcuts[e.getKeyChar()];
if (c == null) {
return;
}
CircuitElm elm = null;
elm = sim.constructElement(c, 0, 0);
if (elm == null) {
return;
}
sim.setMouseMode(MODE_ADD_ELM);
sim.mouseModeStr = c.getName();
sim.addingClass = c;
}
if (e.getKeyChar() == ' ' || e.getKeyChar() == KeyEvent.VK_ESCAPE) {
sim.setMouseMode(MODE_SELECT);
sim.mouseModeStr = "Select";
}
sim.tempMouseMode = sim.mouseMode;
} |
6e9e73e7-996f-4827-aa77-b5dfa5587168 | 9 | public Paint getGradientePaint(){
int x1=0, x2=getWidth(), y1=0, y2=getHeight();
switch (gradiente){
case HORIZONTAL:
x1=getWidth()/2;
y1=0;
x2=getWidth()/2;
y2=getHeight();
return new GradientPaint(x1,y1,colorPrimario, x2, y2,colorSecundario);
case VERTICAL:
x1=0;
y1=getHeight()/2;
x2=getWidth();
y2=getHeight()/2;
return new GradientPaint(x1,y1,colorPrimario, x2, y2,colorSecundario);
case ESQUINA_1:
x1=0;
y1=0;
return new RadialGradientPaint(x1, y1,
getWidth(),
new float[]{0f, 1f},
new Color[]{colorPrimario, colorSecundario});
case ESQUINA_2:
x1=getWidth();
y1=0;
return new RadialGradientPaint(x1, y1,
getWidth(),
new float[]{0f, 1f},
new Color[]{colorPrimario, colorSecundario});
case ESQUINA_3:
x1=getWidth();
y1=getHeight();
return new RadialGradientPaint(x1, y1,
getWidth(),
new float[]{0f, 1f},
new Color[]{colorPrimario, colorSecundario});
case ESQUINA_4:
x1=0;
y1=getHeight();
return new RadialGradientPaint(x1, y1,
getWidth(),
new float[]{0f, 1f},
new Color[]{colorPrimario, colorSecundario});
case CIRCULAR:
x1=getWidth()/2;
y1=getHeight()/2;
return new RadialGradientPaint(x1, y1,
getWidth(),
new float[]{0f, 0.5f},
new Color[]{colorPrimario, colorSecundario});
case CENTRAL:
x1=getWidth()/2;
y1=0;
x2=getWidth()/2;
y2=getHeight();
return new LinearGradientPaint(x1, y1, x2, y2, new float[]{0f, 0.5f, 1f},
new Color[]{colorPrimario, colorSecundario, colorPrimario});
case AQUA:
return new LinearGradientPaint(0, 0, 0, getHeight(),
new float[]{0f, 0.3f, 0.5f, 1f},
new Color[]{colorPrimario.brighter().brighter(),
colorPrimario.brighter(),
colorSecundario.darker().darker(),
colorSecundario.darker()});
default:
return new GradientPaint(0,0,colorPrimario, x2, y2,colorSecundario);
}
} |
816a20f2-6ec2-41b6-91bf-dea28c382ad6 | 4 | private void rotate()
{
//orient++;
if (orient%4==0)
{
litPositions=new int[][]
{{0,1,0},
{0,1,0},
{0,1,1}};
}
if (orient%4==1)
{
litPositions=new int[][]
{{0,0,0},
{1,1,1},
{1,0,0}};
}
if (orient%4==2)
{
litPositions=new int[][]
{{1,1,0},
{0,1,0},
{0,1,0}};
}
if (orient%4==3)
{
litPositions=new int[][]
{{0,0,1},
{1,1,1},
{0,0,0}};
}
} |
ade94b79-4d34-4f5e-bdfb-a65cf3638463 | 0 | NonTerminal(HashSet<Token.Kind> tokenSet)
{
firstSet.addAll(tokenSet);
} |
30eb9175-b770-43f2-8520-ba529ece5f86 | 4 | public List<Message> getMessageList( long cvs_id, int person, int page_size, int offset ){
List<Message> list = new ArrayList<Message>();
PersonInfoHandler handler = null;
try{
ResultSet result = dao_list.getMessageList(cvs_id, person, page_size, offset);
handler = new PersonInfoHandler();
if( !handler.initialize() )
return null;
while( result.next() ){
Message msg = new Message();
msg.id = result.getLong( "message_id" );
msg.type = result.getInt( "type" );
msg.sender = handler.getNameById( result.getInt( "sender" ) );
msg.sender_id = result.getInt( "sender" );
msg.dst = result.getInt( "destination" );
msg.title = result.getString( "title" );
msg.time = df.format( result.getTimestamp( "time" ) );
list.add(msg);
}
handler.close();
return list;
} catch ( SQLException e ){
System.out.println( "MessageHandler : failed to get message list" );
if( handler != null )
handler.close();
return null;
}
} |
f1141946-301c-4e86-af34-1593ac57eb55 | 6 | @Override
public boolean execute(RuleExecutorParam param) {
Rule rule = param.getRule();
List<String> values = Util.getValue(param, rule);
if (values == null || values.isEmpty()) {
return false;
}
boolean retValue = true;
for (String value : values) {
String compareValue = rule.getValue();
if (rule.isIgnoreCase()) {
value = value.toUpperCase();
}
Pattern pattern = Pattern.compile(compareValue);
Matcher matcher = pattern.matcher(value);
boolean intRetValue = matcher.matches();
if (Operators.NotMatches.getValue().equals(rule.getOper())) {
intRetValue = !intRetValue;
}
retValue = retValue && intRetValue;
}
return retValue;
} |
9564ea57-ce8b-4ffd-8b84-e859eddf9815 | 2 | private void nextNonce() {
for(int i = 0; i < NONCE_SIZE; i++) {
byte b = nonce[i];
if(b == Byte.MAX_VALUE) {
nonce[i] = Byte.MIN_VALUE;
} else {
nonce[i] = ++b;
return;
}
}
} |
ca0d7bc6-27b3-4b76-878c-a751d076e9e8 | 0 | public State hasChosenItemsState() {
return hasChosenItemsState;
} |
4547711d-fdb4-4673-b149-563c3f18aa71 | 4 | public int DisplayWinners() {
int TotalWinners = winners.size();
do {
if (TotalWinners == 1) {
System.out.println("Player " + winners.get(0).getPlayerid()
+ " has won the game!");
TotalWinners--;
} else if (TotalWinners == 2) {
System.out.println("Player " + winners.get(0).getPlayerid()
+ " and Player " + winners.get(1).getPlayerid()
+ " have won the game!");
TotalWinners -= 2;
} else {
for (int player = 0; player < winners.size() - 2; player++) {
System.out.print("Player "
+ winners.get(player).getPlayerid() + ", ");
winners.remove(player);
TotalWinners--;
}
}
} while (TotalWinners > 0);
return TotalWinners;
} |
f8390a8c-f9e8-4f28-a3cb-0be2b408c278 | 7 | public void testCode() {
int count = 0;
boolean success;
do {
count++;
success = TaskManager.DoTask(new SimpleAbstractTask("MESSAGE TASK") {
/**
*
*/
private static final long serialVersionUID = -354957472036892394L;
@Override
public synchronized void executeTask() {
for (int i = 0; i < 1; i++) {
try {
// Thread.sleep(5000);
System.out.println("BEGIN EXECUTION");
String mMessage = "";
mMessage = SynchedInOut.getInstance().postMessageForUserInput("Message " + i + ": ");
Socket sock = new Socket(InetAddress.getLocalHost().getHostName(), 1337);
System.out.println("NEXT STEP");
System.out.println("Message " + i + ": ");
Client client = new Client();
client.setCurrentIP(sock.getInetAddress().getHostAddress());
client.setPort(sock.getLocalPort());
client.addStringMessage(mMessage);
PrintWriter out = new PrintWriter(sock
.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
out.println(mMessage + " : " + i);
String fromServer = "null";
while ((fromServer = in.readLine()) != null) {
switch (Integer.valueOf(fromServer)) {
case 200: {
System.out.println("I registered!");
break;
}
case 401: {
System.out
.println("Authentication exception");
break;
}
default: {
System.out.println("Unknown Exception");
break;
}
}
}
out.flush();
in.close();
out.close();
sock.close();
// Thread.sleep(3000);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void onProgressUpdate() {
// TODO Auto-generated method stub
}
@Override
public void onFinished() {
// TODO Auto-generated method stub
System.out.println(this.getClass().getSimpleName() + " finished");
}
@Override
public byte[] toBytes() {
// TODO Auto-generated method stub
return null;
}
@Override
public Task fromBytes(byte[] byteArray) {
// TODO Auto-generated method stub
return null;
}
});
} while (count < 1);
} |
bf8f2293-9db1-41a2-857f-77ad277bc3bd | 1 | private String[] toPathArray(String path) {
if (path.charAt(0) == '/') path = path.substring(1);
return path.split("/");
} |
7fe11270-6c7c-49b8-b374-9ba5b38731d3 | 3 | protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String form = "";
HttpSession sesion = request.getSession();
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
try (PrintWriter out = response.getWriter()) {
/*Formulario solicitado*/
String formulario = request.getParameter("formulario");
if (formulario.equals("movimientoEquipo")) {
form = obtenFormulario(formulario);
form = form.replace("<input type=\"text\" id=\"nombre\" name=\"nombre\">", "<input type=\"text\" id=\"nombre\" "
+ "name=\"nombre\" value=\""
+ bd.regresaNombre((String) sesion.getAttribute("login")) + "\" disabled>");
out.print(form);
} else {
if (formulario.equals("usuarioBaja")) {
form = obtenFormulario(formulario);
form = form.replace("<aqui va la tabla>", obten_tabla_usuarios((String) sesion.getAttribute("login")));
out.print(form);
} else {
if (formulario.equals("catalogoAltaRegistro")) {
form = obtenFormulario(formulario);
form = form.replace("<aqui va el catalogo>", obten_select_catalogo("catalogo_tipo_equipo"));
out.print(form);
} else {
out.print(obtenFormulario(formulario));
}
}
}
}
} |
1872f103-d854-46b6-8ff3-3e5b5b1ed2de | 9 | public FloatElement[] getSortedSimilarWordsByDelta(String word) throws Exception{
int index = model1.index(word);
FloatElement[] similarWords = new FloatElement[model1.sizeOfVocabulary];
//float invalid = -10;
for (int i=0; i<model1.sizeOfVocabulary; i++){
float pmi1 = 0;
float pmi2 = 0;
float similarity = Float.NEGATIVE_INFINITY;
try {
pmi2 = model2.getPMI(index, i);
//if (pmi2 < BASE_PMI) pmi2 = BASE_PMI;
} catch (Exception e) {
// if not exist in the smaller window
try {
pmi1 = model1.getPMI(index, i);
if (REMOVE_NON_FREQUENT_WORDS && model1.getFrequency(i) < model1.totalWords / model1.FrequencyLimit)
similarity = 0; // exclude rarely appearing words
else{
similarity = deltaPMI(pmi1, BASE_PMI);
/*
if (model1.getCoOccurrence(index, i) > 10)
similarity = combinedPMI(pmi1, BASE_PMI);
else
similarity = pmi1; // + CORPUS_PMI_DELTA;
*/
}
} catch (Exception e2) {
// TODO Auto-generated catch block
similarity = 0;
}
}
if (similarity == Float.NEGATIVE_INFINITY){
try {
pmi1 = model1.getPMI(index, i);
/*
if ((double) model1.getCoOccurrence(index, i) / model1.getFrequency(index) < model1.CONDITIONAL_THRESHOLD)
similarity = invalid;
else
*/
if (REMOVE_NON_FREQUENT_WORDS && model1.getFrequency(i) < model1.totalWords / model1.FrequencyLimit)
similarity = 0; // exclude rarely appearing words
else
similarity = deltaPMI(pmi1, pmi2);
} catch (Exception e) {
// TODO Auto-generated catch block
//throw new Exception("Error in program! The two words " + word + " " + model1.vocabulary[i] + " do not co-occur in the bigger window but co-occur in the smaller window");
similarity = 0;
}
}
FloatElement element = new FloatElement(model1.vocabulary[i], similarity);
similarWords[i] = element;
}
Arrays.sort(similarWords);
return similarWords;
} |
75c0a62b-0e81-41a2-b806-25123ae71cf2 | 2 | public void testPropertyCompareToDayOfMonth() {
MonthDay test1 = new MonthDay(TEST_TIME1);
MonthDay test2 = new MonthDay(TEST_TIME2);
assertEquals(true, test1.dayOfMonth().compareTo(test2) < 0);
assertEquals(true, test2.dayOfMonth().compareTo(test1) > 0);
assertEquals(true, test1.dayOfMonth().compareTo(test1) == 0);
try {
test1.dayOfMonth().compareTo((ReadablePartial) null);
fail();
} catch (IllegalArgumentException ex) {}
DateTime dt1 = new DateTime(TEST_TIME1);
DateTime dt2 = new DateTime(TEST_TIME2);
assertEquals(true, test1.dayOfMonth().compareTo(dt2) < 0);
assertEquals(true, test2.dayOfMonth().compareTo(dt1) > 0);
assertEquals(true, test1.dayOfMonth().compareTo(dt1) == 0);
try {
test1.dayOfMonth().compareTo((ReadableInstant) null);
fail();
} catch (IllegalArgumentException ex) {}
} |
400d95d9-0566-4b8e-a4ec-dc2ccfee71e2 | 7 | public void chat() {
// Get username
System.out.println("Enter a username:");
System.out.print(">");
// Get chat message
try(BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))){
String fromUser = stdIn.readLine();
bow.setUserName(fromUser);
System.out.println("You may now enter messages to send.");
System.out.print(">");
//Loops continuously for proper chat interaction.
while((fromUser = stdIn.readLine()) != null){
if(fromUser.equals("elderberries"))
{
if(bow.getSocket() != null || !bow.getSocket().isClosed())
bow.getSocket().close();
break;
}
//In case a bad hostname is entered, we can just try to get another hostname.
//This gives the user a new chance as opposed to just exiting.
while(bow.getChatState() == ChatState.NOT_CONNECTED){
System.out.println("Please enter a host name to connect to.");
System.out.print(">");
//If we connect properly, this should no longer loop.
connect(stdIn.readLine());
}
//We are going to block until the exchange is done.
//We'll let Concorde handle exchanging keys for consistency.
while(bow.getChatState() == ChatState.EXCHANGING);
//Finally, we send out message and loop back around.
bow.shootArrow(fromUser);
System.out.print(">");
}
}catch(IOException ex){
System.out.println("Error reading input.");
concorde.stopReceivingArrows();
System.exit(1);
}
} |
78ff0f39-e592-4252-ba0e-2f9e3df90538 | 0 | @Test
public void resolve() {
String [] numbers={
"37107287533902102798797998220837590246510135740250",
"46376937677490009712648124896970078050417018260538",
"74324986199524741059474233309513058123726617309629",
"91942213363574161572522430563301811072406154908250",
"23067588207539346171171980310421047513778063246676",
"89261670696623633820136378418383684178734361726757",
"28112879812849979408065481931592621691275889832738",
"44274228917432520321923589422876796487670272189318",
"47451445736001306439091167216856844588711603153276",
"70386486105843025439939619828917593665686757934951",
"62176457141856560629502157223196586755079324193331",
"64906352462741904929101432445813822663347944758178",
"92575867718337217661963751590579239728245598838407",
"58203565325359399008402633568948830189458628227828",
"80181199384826282014278194139940567587151170094390",
"35398664372827112653829987240784473053190104293586",
"86515506006295864861532075273371959191420517255829",
"71693888707715466499115593487603532921714970056938",
"54370070576826684624621495650076471787294438377604",
"53282654108756828443191190634694037855217779295145",
"36123272525000296071075082563815656710885258350721",
"45876576172410976447339110607218265236877223636045",
"17423706905851860660448207621209813287860733969412",
"81142660418086830619328460811191061556940512689692",
"51934325451728388641918047049293215058642563049483",
"62467221648435076201727918039944693004732956340691",
"15732444386908125794514089057706229429197107928209",
"55037687525678773091862540744969844508330393682126",
"18336384825330154686196124348767681297534375946515",
"80386287592878490201521685554828717201219257766954",
"78182833757993103614740356856449095527097864797581",
"16726320100436897842553539920931837441497806860984",
"48403098129077791799088218795327364475675590848030",
"87086987551392711854517078544161852424320693150332",
"59959406895756536782107074926966537676326235447210",
"69793950679652694742597709739166693763042633987085",
"41052684708299085211399427365734116182760315001271",
"65378607361501080857009149939512557028198746004375",
"35829035317434717326932123578154982629742552737307",
"94953759765105305946966067683156574377167401875275",
"88902802571733229619176668713819931811048770190271",
"25267680276078003013678680992525463401061632866526",
"36270218540497705585629946580636237993140746255962",
"24074486908231174977792365466257246923322810917141",
"91430288197103288597806669760892938638285025333403",
"34413065578016127815921815005561868836468420090470",
"23053081172816430487623791969842487255036638784583",
"11487696932154902810424020138335124462181441773470",
"63783299490636259666498587618221225225512486764533",
"67720186971698544312419572409913959008952310058822",
"95548255300263520781532296796249481641953868218774",
"76085327132285723110424803456124867697064507995236",
"37774242535411291684276865538926205024910326572967",
"23701913275725675285653248258265463092207058596522",
"29798860272258331913126375147341994889534765745501",
"18495701454879288984856827726077713721403798879715",
"38298203783031473527721580348144513491373226651381",
"34829543829199918180278916522431027392251122869539",
"40957953066405232632538044100059654939159879593635",
"29746152185502371307642255121183693803580388584903",
"41698116222072977186158236678424689157993532961922",
"62467957194401269043877107275048102390895523597457",
"23189706772547915061505504953922979530901129967519",
"86188088225875314529584099251203829009407770775672",
"11306739708304724483816533873502340845647058077308",
"82959174767140363198008187129011875491310547126581",
"97623331044818386269515456334926366572897563400500",
"42846280183517070527831839425882145521227251250327",
"55121603546981200581762165212827652751691296897789",
"32238195734329339946437501907836945765883352399886",
"75506164965184775180738168837861091527357929701337",
"62177842752192623401942399639168044983993173312731",
"32924185707147349566916674687634660915035914677504",
"99518671430235219628894890102423325116913619626622",
"73267460800591547471830798392868535206946944540724",
"76841822524674417161514036427982273348055556214818",
"97142617910342598647204516893989422179826088076852",
"87783646182799346313767754307809363333018982642090",
"10848802521674670883215120185883543223812876952786",
"71329612474782464538636993009049310363619763878039",
"62184073572399794223406235393808339651327408011116",
"66627891981488087797941876876144230030984490851411",
"60661826293682836764744779239180335110989069790714",
"85786944089552990653640447425576083659976645795096",
"66024396409905389607120198219976047599490197230297",
"64913982680032973156037120041377903785566085089252",
"16730939319872750275468906903707539413042652315011",
"94809377245048795150954100921645863754710598436791",
"78639167021187492431995700641917969777599028300699",
"15368713711936614952811305876380278410754449733078",
"40789923115535562561142322423255033685442488917353",
"44889911501440648020369068063960672322193204149535",
"41503128880339536053299340368006977710650566631954",
"81234880673210146739058568557934581403627822703280",
"82616570773948327592232845941706525094512325230608",
"22918802058777319719839450180888072429661980811197",
"77158542502016545090413245809786882778948721859617",
"72107838435069186155435662884062257473692284509516",
"20849603980134001723930671666823555245252804609722",
"53503534226472524250874054075591789781264330331690"};
long result=calc(numbers);
print((""+result).substring(0, 10));
} |
7884804c-32cd-4686-a951-0c15d8e5621f | 5 | @Override
protected void setCompletion(final HTTPCompletion completion) {
super.setCompletion(new HTTPCompletion() {
@Override
public void failure(URLRequest request, Throwable t) {
if (completion != null) {
completion.failure(request, t);
}
}
@Override
public void success(URLRequest request, Object responseData) {
if (completion != null) {
String xmlContent = new String((byte[])responseData);
Document document = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(new InputSource(new StringReader(xmlContent)));
document.getDocumentElement().normalize();
if (completion != null) {
completion.success(request, document);
}
} catch (Exception e) {
if (completion != null) {
completion.failure(request, e);
}
}
}
}
});
} |
733669c2-5db9-40ce-8627-ef209b9b24fe | 1 | public void initAscii()
{
for(char i=0 ; i<256 ; i++)
tableAscii.add(i);
} |
f077f857-e8b4-489c-b833-7e50e11b132c | 8 | @Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Tree)) {
return false;
}
final Tree<?> other = (Tree<?>) obj;
if (rootNode == null) {
if (other.rootNode != null) {
return false;
}
} else if (!rootNode.equals(other.rootNode)) {
return false;
}
return true;
} |
896501e5-f88f-4351-9fda-59398407ef37 | 4 | @Override
public void componentResized(ComponentEvent e)
{
if(e.getComponent() == null || e.getComponent() instanceof JFrame == false)
return;
JFrame frame = (JFrame)e.getComponent();
Container contentPane = frame.getContentPane();
int newWidth = contentPane.getWidth();
int newHeight = contentPane.getHeight();
FontMetrics fontMetrics = frame.getGraphics().getFontMetrics(appearance.getNormalTextFont());
int consoleWidth = newWidth / fontMetrics.charWidth(' ');
int consoleHeight = newHeight / fontMetrics.getHeight();
if(consoleWidth == lastWidth && consoleHeight == lastHeight)
return;
lastWidth = consoleWidth;
lastHeight = consoleHeight;
resize(consoleWidth, consoleHeight);
} |
54241df2-0578-42c9-af9c-9bab87c75370 | 1 | private void init() {
statsFile = new File("stats.txt");
date = new Date();
jLabel1 = new JLabel();
this.setBackground(Color.black);
initLeaderBoards();
setBackLabel();
resetLayout();
//saveStats();
try {
loadStats();
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "Error when reading the statsFile!", "Error", JOptionPane.ERROR_MESSAGE);
}
} |
f604ee55-a688-4e60-a5c2-cab7982ef79d | 9 | static Playlist playlistFromElement(DomElement e) {
if (e == null)
return null;
Playlist p = new Playlist();
if (e.hasChild("id"))
p.id = Integer.parseInt(e.getChildText("id"));
p.title = e.getChildText("title");
if (e.hasChild("size"))
p.size = Integer.parseInt(e.getChildText("size"));
p.creator = e.getChildText("creator");
p.annotation = e.getChildText("annotation");
DomElement tl = e.getChild("trackList");
if (tl != null) {
for (DomElement te : tl.getChildren("track")) {
Track t = new Track(te.getChildText("title"), te.getChildText("identifier"),
te.getChildText("creator"));
t.album = te.getChildText("album");
t.duration = Integer.parseInt(te.getChildText("duration")) / 1000;
t.imageUrls.put(ImageSize.LARGE, te.getChildText("image"));
t.imageUrls.put(ImageSize.ORIGINAL, te.getChildText("image"));
t.location = te.getChildText("location");
for (DomElement ext : te.getChildren("extension")) {
if ("http://www.last.fm".equals(ext.getAttribute("application"))) {
for (DomElement child : ext.getChildren()) {
t.lastFmExtensionInfos.put(child.getTagName(), child.getText());
}
}
}
p.tracks.add(t);
}
if (p.size == 0)
p.size = p.tracks.size();
}
return p;
} |
35ae9a51-36e4-4c3f-b022-ff7d5b2ac03b | 8 | void updateVelocity(double t)
{
double dx, dy;
if (Math.abs(getVelocity()[0] + (force.getX()/getMass())*t) < .6) //Breaks physics by limiting velocity. Might not actually do anything...
dx = getVelocity()[0] + (force.getX()/getMass())*t;
else
dx = getVelocity()[0];
if (Math.abs(getVelocity()[1] + (force.getY()/getMass())*t) < .6)
dy = getVelocity()[1] + (force.getY()/getMass())*t;
else
dy = getVelocity()[1];
heading = Math.abs(Math.atan(dy/dx));
if (dx < 0 && dy > 0)
heading += 90;
else if (dx < 0 && dy < 0)
heading += 180;
else if (dx > 0 && dy < 0)
heading += 270;
setVelocity(dx, dy);
} |
d20713d1-976d-4d31-9180-38619e906ede | 4 | public void dragCard(String ID, int newx, int newy) {
for (Object e : table.getComponents()) {
if ((e.getClass().equals(TCard.class)
|| e.getClass().equals(Token.class))
&&((TCard) e).getID().equals(ID)) {
((TCard) e).setCardPosition(newx, newy);
break;
}
}
} |
c541e1c2-1e0d-4a50-bb7b-c99d28d97887 | 6 | public void update(float delta) {
if (startTime < 0) {
startTime = System.currentTimeMillis();
} else if (time + delta < length / 1000) {
time += delta;
}
if (endTime < 0 && System.currentTimeMillis() - startTime > length) {
endTime = System.currentTimeMillis();
}
if (System.currentTimeMillis() - endTime > 500 && endTime > 0) {
nextState = new LevelState(screen);
}
} |
3bbfd025-626d-4e02-9e37-906b719ce299 | 7 | private void initNameTileFontMenu(Color bg) {
this.nametextTilePanel = new JPanel();
this.nametextTilePanel.setBackground(bg);
this.nametextTilePanel.setLayout(new VerticalLayout(5, VerticalLayout.LEFT));
String initFontTmp = this.skin.getNametextZoomedFont();
int initFontSizeTmp = this.skin.getNametextZoomedFontsize();
Color initFontColorTmp = new Color(this.skin.getNametextZoomedFontcolor()[1], this.skin.getNametextZoomedFontcolor()[2],
this.skin.getNametextZoomedFontcolor()[3]);
boolean boldTmp = this.skin.getNametextZoomedFonttype() == Fonttype.BOLD;
boolean underlineTmp = (this.skin.getNametextZoomedFontstyle() == Fontstyle.UNDERLINE)
|| (this.skin.getNametextZoomedFontstyle() == Fontstyle.SHADOWUNDERLINE);
boolean shadowTmp = (this.skin.getNametextZoomedFontstyle() == Fontstyle.SHADOW)
|| (this.skin.getNametextZoomedFontstyle() == Fontstyle.SHADOWUNDERLINE);
this.nametextZoomedFontfield = new FontField(bg, strFontFieldTitle, initFontTmp, initFontSizeTmp, initFontColorTmp, boldTmp,
underlineTmp, shadowTmp) {
private final long serialVersionUID = 1L;
@Override
public void fontChosen(String input) {
if (!input.equals("")) {
FontChangesMenu.this.skin.setNametextZoomedFont(input);
updateFont(FontChangesMenu.this.skin.getNametextZoomedFont());
} else {
FontChangesMenu.this.skin.setNametextZoomedFont(null);
}
}
@Override
public void sizeTyped(String input) {
if (input != null) {
FontChangesMenu.this.skin.setNametextZoomedFontsize(parseInt(input));
updateSize(FontChangesMenu.this.skin.getNametextZoomedFontsize());
} else {
FontChangesMenu.this.skin.setNametextZoomedFontsize(-1);
}
}
@Override
public void colorBtnPressed(int[] argb) {
FontChangesMenu.this.skin.setNametextZoomedFontcolor(argb);
updateColor(new Color(FontChangesMenu.this.skin.getNametextZoomedFontcolor()[1],
FontChangesMenu.this.skin.getNametextZoomedFontcolor()[2],
FontChangesMenu.this.skin.getNametextZoomedFontcolor()[3]));
}
@Override
public void boldPressed(boolean selected) {
FontChangesMenu.this.skin.setNametextZoomedFonttype(selected ? Fonttype.BOLD : Fonttype.NORMAL);
updateBold(FontChangesMenu.this.skin.getNametextZoomedFonttype() == Fonttype.BOLD);
}
@Override
public void underlinePressed(boolean selected) {
FontChangesMenu.this.skin.setNametextZoomedFontstyle(getUnderlineFontstyle(selected,
FontChangesMenu.this.skin.getNametextZoomedFontstyle()));
updateUnderline((FontChangesMenu.this.skin.getNametextZoomedFontstyle() == Fontstyle.UNDERLINE)
|| (FontChangesMenu.this.skin.getNametextZoomedFontstyle() == Fontstyle.SHADOWUNDERLINE));
}
@Override
public void shadowPressed(boolean selected) {
FontChangesMenu.this.skin.setNametextZoomedFontstyle(getShadowFontstyle(selected,
FontChangesMenu.this.skin.getNametextZoomedFontstyle()));
updateShadow((FontChangesMenu.this.skin.getNametextZoomedFontstyle() == Fontstyle.SHADOW)
|| (FontChangesMenu.this.skin.getNametextZoomedFontstyle() == Fontstyle.SHADOWUNDERLINE));
}
};
this.nametextTilePanel.add(this.nametextZoomedFontfield);
} |
f098cd7f-23d0-41ce-b579-006818d11555 | 1 | public boolean decryptSerializedTable(){
String smartcard="verysecurepassword";
try {
File f = new File(TABLE_FILE);
File fe = new File(ENCRYPTED_TABLE_FILE);
f.createNewFile();
fe.createNewFile();
FileInputStream fis = new FileInputStream(ENCRYPTED_TABLE_FILE);
FileOutputStream fos = new FileOutputStream(TABLE_FILE);
decrypt(smartcard, fis, fos);
} catch (Throwable e) {
e.printStackTrace();
}
return true;
} |
d427275b-d02f-49ae-99f0-b7ddbfdc50d0 | 3 | public void mouseClick(MouseEvent e){
if(e.getButton() == MouseEvent.BUTTON1){
if(data.orientation == 0){
menu.show(this, 0, TabButton.BUTTON_ACTIVE_HEIGHT);
}
else if(data.orientation == 1){
menu.show(this, 0, -menu.getHeight());
}
}
} |
fd7be1a7-698c-4181-8f1d-d1c16703d2c0 | 6 | protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) {
while (in.remaining() > 0) {
if (out.remaining() < 1) {
return CoderResult.OVERFLOW;
}
final char c = in.get();
if (c >= 0 && c < 256 && IDENT_PDF_DOC_ENCODING_MAP[c]) {
out.put((byte) c);
} else {
final Byte mapped = EXTENDED_TO_PDF_DOC_ENCODING_MAP.get(c);
if (mapped != null) {
out.put(mapped);
} else {
return CoderResult.unmappableForLength(1);
}
}
}
return CoderResult.UNDERFLOW;
} |
8fff9502-fd82-49bd-a422-26b4ecec94fc | 6 | private static void assertNum(int totalCounts,
List<List<Double>> dataPointsUnnormalized) throws Exception
{
int sum = 0;
for (int x = 0; x < dataPointsUnnormalized.size(); x++)
for (int y = 0; y < dataPointsUnnormalized.get(x).size(); y++)
sum += dataPointsUnnormalized.get(x).get(y);
if (totalCounts != sum)
throw new Exception("Logic error " + totalCounts + " " + sum);
if (dataPointsUnnormalized.size() > 0)
{
int length = dataPointsUnnormalized.get(0).size();
for (int x = 0; x < dataPointsUnnormalized.size(); x++)
if (length != dataPointsUnnormalized.get(x).size())
throw new Exception("Jagged array");
}
} |
dfaf676d-19a0-457f-a465-510c9f7fcbfe | 3 | public File getFile(String lfn, int resID)
{
if (lfn == null || resID == -1) {
return null;
}
// sends a request to the RC
int eventTag = DataGridTags.FILE_REQUEST;
sendEvent(eventTag, lfn, resID);
// waiting for a response from the resource
Sim_type_p tag = new Sim_type_p(DataGridTags.FILE_DELIVERY);
Sim_event ev = new Sim_event();
super.sim_get_next(tag, ev); // only look for this type of ack
File file = null;
try {
file = (File) ev.get_data();
}
catch (Exception e) {
file = null;
System.out.println(super.get_name() + ".getFile(): Exception");
}
return file;
} |
d2490b09-670a-4bd4-a5f0-5e9a0d015ac8 | 2 | private void serverNameTMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_serverNameTMouseReleased
int index = serverNameT.getSelectedRow();
if(index>=0){
String server = (String)serverNameT.getModel().getValueAt(index, 0);
serverConfigTF.setText(server);
Configuracion c = configuraciones.buscar(server);
if(c!=null){
serverStrategiesTF.setText(c.getStrategiesDir());
serverRMANLogTF.setText(c.getRMANLogDir());
serverRMANScriptTF.setText(c.getRMANScriptDir());
serverBackupTF.setText(c.getBackupDir());
}
else{
serverStrategiesTF.setText("");
serverRMANLogTF.setText("");
serverRMANScriptTF.setText("");
serverBackupTF.setText("");
}
}
}//GEN-LAST:event_serverNameTMouseReleased |
66d7eb24-42a3-4a7b-a1bf-710a49b3c103 | 2 | public void createDestinationDirectories() {
File projectObfuscatedDir = new File(destinationDir);
projectObfuscatedDir.mkdir();
for (File directory : projectFiles) {
if (directory.isDirectory()) {
String n = destinationDir + "/" + directory.getAbsolutePath().substring(sourceDir.length());
File newDirectory = new File(n);
newDirectory.mkdir();
}
}
} |
29dfaa0e-bc06-479d-aeaa-411e83aaa63c | 5 | public void onDisconnect() {
GUIMain.add_line(DarkIRC.AppLang.getString("quit_msg"));
while (!isConnected()) {
try {
reconnect();
Thread.sleep(3000L);
for (int i = 0; i < DarkIRC.channelsList.size(); i++) {
if (DarkIRC.channelsList.get(i).name.startsWith("#")) {
this.joinChannel(DarkIRC.channelsList.get(i).name);
}
}
} catch (Exception e) {
try {
Thread.sleep(10000);
} catch (Exception e1) {
}
}
}
} |
8da240bb-2182-4496-9e91-dfda6e0bc974 | 3 | *@param nivel
**/
public void showMeMoney(beansMiembro miembro, int nivel){
String tab = appMiembro.getLines(nivel);
System.out.println(tab+"----------------------------------");
System.out.println(tab+"| "+miembro.getNick()+" Tus datos monetarios son:");
System.out.println(tab+"----------------------------------");
System.out.println(tab+"| Entradas --> "+miembro.getIngresos());
System.out.println(tab+"| Salidas --> "+miembro.getEgresos());
System.out.println(tab+"----------------------------------");
if(miembro.getIngresos() < miembro.getEgresos()){
System.out.println(tab+"| Su deficit es de : "+(miembro.getIngresos() - miembro.getEgresos()));
}else if(miembro.getEgresos() == 0){
System.out.println(tab+"| Compra algo para estar activo.");
}else if(miembro.getEgresos() < miembro.getIngresos()){
System.out.println(tab+"| Su superavit es de : "+(miembro.getIngresos() - miembro.getEgresos()));
}
System.out.println(tab+"----------------------------------");
} |
1ecc942d-c1ba-4263-bf8f-b934bfdb9db9 | 3 | @Override
public ArrayList<String> getEffectSprites(){
ArrayList<String> result = new ArrayList<String>();
if(stype!=null) result.add(stype);
if(stypeCount!=null) result.add(stypeCount);
if(estype!=null) result.add(estype);
return result;
} |
ab6f9d2a-d696-467d-8a1e-04a8a0122733 | 3 | public SimulationResultsHolder runSimulation() {
resultsHolder = new SimulationResultsHolder();
resultsHolder.addFlyReleaseInfo(fr.toString());
for (int i = 1; i<=numberOfDays; i++) {
System.err.println("Running simulation for day " + i + "...");
double totalProbForDay = 0;
int numberOfFlies = 0;
Iterator<OutbreakLocation> releasePointItr = fr.allOutbreakLocations.iterator();
while (releasePointItr.hasNext()) {
OutbreakLocation currentReleasePoint = releasePointItr.next();
ArrayList<Point2D.Double> flyLocations = currentReleasePoint.locateFlies(i);
Iterator<Point2D.Double> flyLocationItr = flyLocations.iterator();
while (flyLocationItr.hasNext()) {
Point2D.Double currentLocation = flyLocationItr.next();
Double currentEscapeProb = tg.getTotalEscapeProbability(currentLocation);
String[] results = {Integer.toString(i), currentReleasePoint.shortString(),
locationToString(currentLocation), Double.toString(currentEscapeProb)};
resultsHolder.addRawData(results);
totalProbForDay += currentEscapeProb;
numberOfFlies += 1;
}
}
double avgForDay = totalProbForDay / numberOfFlies;
cumulativeProb *= avgForDay;
resultsHolder.addAvgEscapeProbability(i, avgForDay);
}
System.err.println("Simulation complete!");
return resultsHolder;
} |
bbc54900-3497-4fb1-9af9-0cc8cb01ff62 | 8 | private String makeCode(){
String c=((ComboText)command.getSelectedItem()).getValue();
if(c.equals("MAKE")){
return logoObj.getText()+"=addons.logo("+makeW.getValue()+","+makeH.getValue()+"); "
+ logoObj.getText()+".setClosedCanvas("+closedCanvas.isSelected()+");";
}
else if(c.equals("forward") || c.equals("backward")
|| c.equals("turnRight") || c.equals("turnLeft")
|| c.equals("distance")){
return logoObj.getText()+"."+c+"("+value.getText()+")";
}
else if(c.equals("setColor")){
return logoObj.getText()+"."+c+"(\""+colorHEX.getText()+"\")";
}
else if(c.equals("distance")){
return variable.getText()+"="+logoObj.getText()+"."+c+"(("+value.getText()+"))";
}
else
return logoObj.getText()+"."+c+"()";
} |
977b1047-6d69-4877-8e71-12ca25cd4cd9 | 6 | @Override
public void update( float delta )
{
SphereCollider spheres[] = new SphereCollider[6];
spheres[0] = new SphereCollider( player.getTransform().getPos(), 150 );
spheres[1] = new SphereCollider( player.getTransform().getPos(), 100 );
spheres[2] = new SphereCollider( player.getTransform().getPos(), 75 );
spheres[3] = new SphereCollider( player.getTransform().getPos(), 50 );
spheres[4] = new SphereCollider( player.getTransform().getPos(), 20 );
spheres[5] = new SphereCollider( player.getTransform().getPos(), 10 );
List<QuadTree> toDivide = new ArrayList<QuadTree>();
// List<QuadTree> toRemove = new ArrayList<QuadTree>();
int limit = 0;
for ( QuadTree quadTree : quadTrees )
{
List<QuadTree> renderedNode = quadTree.getLeaves();
for ( QuadTree node : renderedNode )
{
for ( int i = 0; i < spheres.length; i++ )
{
if ( isInSphere( i + 1, spheres[i], node ) )
{
toDivide.add( node );
limit++;
break;
}
// else if ( node.parent != null )
// {
// Collections.addAll( toRemove, node.parent );
// }
}
if ( limit == 5 )
break;
}
}
for ( QuadTree node : toDivide )
{
subDivideChunk( (Chunk) node.object, node );
}
// for ( QuadTree node : toRemove )
// {
// List<QuadTree> list = Arrays.asList( node.children );
// for ( QuadTree q : list )
// {
// try
// {
// mesh.delTriangles( ((Chunk)q.object).getTriangles() );
// }
// catch ( Exception e )
// {
// e.printStackTrace();
// }
// }
// mesh.addTriangles( ( (Chunk) node.object ).getTriangles() );
// }
} |
adc3a758-0d8c-40c7-9764-54d9ac358c61 | 2 | public Repl(Class<? extends Visitor<S, T>> vClass) {
this.interp = null;
evalClass = vClass;
try {
interp = evalClass.newInstance();
} catch (InstantiationException | IllegalAccessException ie) {
System.err.println(ie.getMessage());
System.err.println("Fatal error: Failed to instantiate "
+ "interpreter! Terminating...");
System.exit(1);
}
} |
cf51ffe3-e370-408a-bef3-047678aa319e | 3 | public List getAll() throws SQLException {
Session session = null;
List list = new ArrayList();
try {
session = HibernateUtil.getInstance().openSession();
list = session.createCriteria(EmployeeModel.class).list();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
return list;
} |
2a547033-01ea-4211-8348-a55936b246cc | 5 | public String toString () {
if (size == 0) return "{}";
StringBuilder buffer = new StringBuilder(32);
buffer.append('{');
K[] keyTable = this.keyTable;
int[] valueTable = this.valueTable;
int i = keyTable.length;
while (i-- > 0) {
K key = keyTable[i];
if (key == null) continue;
buffer.append(key);
buffer.append('=');
buffer.append(valueTable[i]);
break;
}
while (i-- > 0) {
K key = keyTable[i];
if (key == null) continue;
buffer.append(", ");
buffer.append(key);
buffer.append('=');
buffer.append(valueTable[i]);
}
buffer.append('}');
return buffer.toString();
} |
6b9a5975-4a3f-425d-86f9-85eed83f6777 | 8 | private void calcDeriv(){
if(this.numerDiffFlag){
// Numerical differentiation using delta and interpolation
this.cs = new CubicSpline(this.x, this.y);
double[] xjp1 = new double[this.nPoints];
double[] xjm1 = new double[this.nPoints];
for(int i=0; i<this.nPoints; i++){
xjp1[i] = this.x[i] + this.incrX;
if(xjp1[i]>this.x[this.nPoints-1])xjp1[i] = this.x[this.nPoints-1];
xjm1[i] = this.x[i] - this.incrX;
if(xjm1[i]<this.x[0])xjm1[i] = this.x[0];
}
for(int i=0; i<this.nPoints; i++){
this.dydx[i] = (cs.interpolate(xjp1[i]) - cs.interpolate(xjm1[i]))/(xjp1[i] - xjm1[i]);
}
}
else{
// Numerical differentiation using provided data points
int iip =0;
int iim =0;
for(int i=0; i<this.nPoints; i++){
iip = i+1;
if(iip>=this.nPoints)iip = this.nPoints-1;
iim = i-1;
if(iim<0)iim = 0;
this.dydx[i] = (this.y[iip] - this.y[iim])/(this.x[iip] - this.x[iim]);
}
}
this.derivCalculated = true;
} |
d774ea63-b18d-4890-bdb5-3ed866be4b79 | 4 | public Candlestick constroiCandleParaData(Calendar data,
List<Negocio> negocios) {
if(negocios.isEmpty())
return new Candlestick(0,0,0,0,0,data);
double maximo = negocios.get(0).getPreco();
double minimo = negocios.get(0).getPreco();
double volume = 0;
for (Negocio negocio : negocios) {
volume += negocio.getVolume();
if (negocio.getPreco() > maximo) {
maximo = negocio.getPreco();
} else if (negocio.getPreco() < minimo) {
minimo = negocio.getPreco();
}
}
double abertura = negocios.get(0).getPreco();
double fechamento = negocios.get(negocios.size()-1).getPreco();
return new Candlestick(abertura, fechamento, minimo, maximo,
volume, data);
} |
72f69d18-188e-4cd4-8d4c-bdef58713fcb | 7 | @Override
public void appliquerReglesLocalesDeValidation(String[] categoriesReconnues) {
//Validation de la date pour cycle. La date est valide entre 1er
//avril 2012 et 1er avril 2014. Le reste n'est pas valide.
Date dateMinConv = new Date();
Date dateMaxConv = new Date();
try {
dateMinConv = sdf.parse(DATE_MIN_CYCLE);
dateMaxConv = sdf.parse(DATE_MAX_CYCLE);
} catch (ParseException ex) {
}
if (date.compareTo(dateMinConv)>=0 && date.compareTo(dateMaxConv)<=0) {
} else {
activiteValide = false;
String errDate = "La date de l'activité " + description +
" n'est pas reconnue. Elle sera ignorée.";
ajouterMessageErreur(errDate);
}
//Le prochain segment vérifie si la catégorie est reconnue ou non.
boolean categorieOk = false;
for (int i = 0; i < categoriesReconnues.length; i++) {
if (categorie.equals(categoriesReconnues[i])) {
categorieOk = true;
}
}
if (!categorieOk) {
activiteValide = false;
String errCat = "L'activité " + description + " est dans une catégorie non reconnue. Elle sera ignorée.";
ajouterMessageErreur(errCat);
}
//Vérifie que les heures d'une activité sont bien supérieures ou égales à 1.
if (heures < 1) {
activiteValide = false;
String errHeure = "L'activité " + description + " a un nombre d'heure inférieur à 1. Elle sera donc ignorée.";
ajouterMessageErreur(errHeure);
}
} |
11063363-93f1-426e-a3ef-9b338593068e | 1 | @Override
public void setState(Map<String, Object> state) {
this.state = state;
this.showInfoArea(state);
this.showHistoryArea(state);
this.showFeedbackArea(state);
this.updateMessageArea("");
this.input = "";
this.inputInfoArea.clear();
this.enableClicks = false;
currentState = (String)state.get(this.CURRENTMOVE) == null?
"" : (String)state.get(this.CURRENTMOVE);
} |
33cd7c5b-f87f-47a9-8131-5f0221290134 | 1 | @Override
public void update() {
for(Particle p:particles){
p.update();
}
} |
72f560ae-501a-4b25-801c-bfafa3239379 | 4 | public static void sobreescribirFichero(Map<String,Cliente> array){
try{
FileWriter fichero=new FileWriter("src/Ficheros/Clientes.txt");
PrintWriter pw=new PrintWriter(fichero);
float aux_cuenta_corriente=0, aux_cuenta_ahorro=0, aux_penalizacion=0;
Iterator it=array.entrySet().iterator();
while(it.hasNext()){
Map.Entry a=(Map.Entry)it.next();
if(((Cliente)(a.getValue())).getCunetacorriente()==null){
aux_cuenta_corriente=-1;
}else{
aux_cuenta_corriente=((Cliente)(a.getValue())).getCunetacorriente().consultarSaldo();
}
if(((Cliente)(a.getValue())).getCunetaahorro()==null){
aux_cuenta_ahorro=-1;
aux_penalizacion=-1;
}else{
aux_cuenta_ahorro=((Cliente)(a.getValue())).getCunetaahorro().consultarSaldo();
aux_penalizacion=((Cliente)(a.getValue())).getCunetaahorro().get_penalizacion();
}
pw.println(((Cliente)(a.getValue())).getDni()+";"+aux_cuenta_corriente+";"+aux_cuenta_ahorro+";"+aux_penalizacion+";");
}
pw.close();
fichero.close();
}catch(Exception e){
System.out.println("Error al sobreescribir en la BBDD de los clientes");
}
} |
001916e4-f4ff-4d13-a8fa-4975de6153dc | 6 | static final ItemDefinition itemDefinitionForID(int i) {
ItemDefinition itemDefinition = (ItemDefinition) Class13.itemDefinitionNodes.getObjectForID(i);
if (itemDefinition != null) {
return itemDefinition;
}
byte abyte0[] = Class142_Sub10.aClass73_3362.method774(Class77.method833((byte) 96, i), Class142_Sub13.method1514(127, i));
itemDefinition = new ItemDefinition();
itemDefinition.id = i;
if (abyte0 != null) {
itemDefinition.readValues(new Stream(abyte0));
}
itemDefinition.method1175((byte) 43);
if (itemDefinition.certTemplateID != -1) {
itemDefinition.toNote(itemDefinitionForID(itemDefinition.certID), itemDefinitionForID(itemDefinition.certTemplateID));
}
if (itemDefinition.anInt2175 != -1) {
itemDefinition.method1176(itemDefinitionForID(itemDefinition.anInt2142), itemDefinitionForID(itemDefinition.anInt2175), -17529);
}
if (!Class57.onMembersServer && itemDefinition.membersItem) {
itemDefinition.actions = NPCComposite.aStringArray2072;
itemDefinition.groundActions = Class36.aStringArray652;
itemDefinition.name = Cache.membersObject;
itemDefinition.aBoolean2159 = false;
itemDefinition.team = 0;
}
Class13.itemDefinitionNodes.addObject(i, itemDefinition);
return itemDefinition;
} |
581ad9ad-a797-4ad8-8f35-e0d7dce1d34c | 5 | private void cleanup() {
try
{
if (this.inputListener.isAlive())
{
this.inputListener.interrupt();
}
if (!this.socket.isInputShutdown())
{
this.socket.getInputStream().close();
}
if (!this.socket.isOutputShutdown())
{
this.socket.getOutputStream().close();
}
if (!this.socket.isClosed())
{
this.socket.close();
}
}
catch (Exception e)
{
}
finally
{
this.notifyClientDisconnected();
}
} |
01f3ae3e-62b3-45a0-b4f2-c3bc0381cdfe | 0 | public void addNodeAfter(int item)
{
link = new IntNode(item, link);
} |
2f46d397-f04c-4d20-8210-5ca386cb4ed2 | 9 | private static Moves performCleanupStep2(BotState state, Moves movesSoFar) {
Moves out = new Moves();
boolean meaningfulMovePresent = false;
for (AttackTransferMove attackTransferMove : movesSoFar.attackTransferMoves) {
if (!attackTransferMove.getToRegion().getPlayerName().equals(state.getMyPlayerName())) {
meaningfulMovePresent = true;
}
}
System.err.println("meaningfulMovePresent: " + meaningfulMovePresent);
String gameState = GameStateCalculator.calculateGameState(state);
if (!meaningfulMovePresent && gameState.equals("won")) {
Region biggestArmiesRegion = null;
int mostArmies = 0;
for (Region region : state.getVisibleMap().getOpponentBorderingRegions(state)) {
if (region.getIdleArmies() > mostArmies) {
mostArmies = region.getIdleArmies();
biggestArmiesRegion = region;
}
}
if (biggestArmiesRegion != null && biggestArmiesRegion.getIdleArmies() >= 100) {
System.err.println("biggestArmiesRegion != null && biggestArmiesRegion.getIdleArmies() >= 100");
Region opponentNeighborRegion = biggestArmiesRegion.getEnemyNeighbors(state).get(0);
int mostOpponentArmies = opponentNeighborRegion.getArmies()
+ OpponentDeploymentGuesser.getGuessedOpponentDeployment(state, opponentNeighborRegion);
double currentFraction = mostArmies / mostOpponentArmies;
double ownKills = mostArmies * 0.6;
double opponentKills = mostOpponentArmies * 0.7;
double newFraction = (mostArmies - opponentKills) / (mostOpponentArmies - ownKills);
System.err.println("currentFraction: " + currentFraction);
System.err.println("newFraction: " + newFraction);
if (newFraction > currentFraction) {
AttackTransferMove attackTransferMove = new AttackTransferMove(state.getMyPlayerName(),
biggestArmiesRegion, opponentNeighborRegion, biggestArmiesRegion.getIdleArmies());
out.attackTransferMoves.add(attackTransferMove);
}
}
}
MovesPerformer.performMoves(state, out);
return out;
} |
8422dcba-9fb1-46b3-9aac-3112dbbe3968 | 7 | static private final boolean cvc(int i)
{ if (i < 2 || !cons(i) || cons(i-1) || !cons(i-2)) return false;
{ int ch = b[i];
if (ch == 'w' || ch == 'x' || ch == 'y') return false;
}
return true;
} |
8f598617-339d-4540-ac5b-cb1178a0374e | 7 | public Shell open(Display display) {
// Load the images
Class<HoverHelp> 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;
} |
9e053ae1-b4c3-4186-a20f-1492b19f924c | 5 | public void addPlugin(JPanel panel, PluginArea placement){
if(panel != null){
panel.setBackground(Constants.GUI_BACKGROUND);
if(placement == PluginArea.SEARCH){
this.topPanel.add(panel, BorderLayout.EAST);
} else {
if(placement == PluginArea.LEFT_TOP){
this.layers[0].stopAndRemove();
this.leftPanelView.remove(0);
this.leftPanelView.add(panel, 0);
}
if(placement == PluginArea.LEFT_MIDDLE){
this.layers[1].stopAndRemove();
this.leftPanelView.remove(1);
this.leftPanelView.add(panel, 1);
}
if(placement == PluginArea.LEFT_BOTTOM){
this.layers[2].stopAndRemove();
this.leftPanelView.remove(2);
this.leftPanelView.add(panel, 2);
}
}
/*Revalidate so we instantly refresh the view*/
this.leftPanelView.revalidate();
} else {
Log.getLogger().log(Level.SEVERE, "Could not add plugin panel to the view, panel is null");
}
} |
9a4ccd1c-95bf-4da4-80ea-38e889a72063 | 8 | public static void main(String[] args) throws Throwable{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Comparator<int[]> comp = new Comparator<int[]>() {
public int compare(int[] o1, int[] o2) {
if(o1[0]<o2[0])return -1;
if(o1[0]>o2[0])return 1;
return -1;
}
};
StringBuffer sb = new StringBuffer();
for (int i = 0, C = parseInt(in.readLine().trim()); i < C; i++) {
int N = parseInt(in.readLine().trim());
arr = new int[N][];
int []sol = new int[N];
for (int j = 0; j < N; j++) {
StringTokenizer st = new StringTokenizer(in.readLine().trim());
arr[j] = new int[]{parseInt(st.nextToken()), parseInt(st.nextToken()), j};
}
mem = new Point[N][6][6];
Arrays.sort(arr, comp);
sb.append(function(0,10,10) + "\n");
int valIzq = 10, valDer = 10;
for (int j = 0; j < sol.length; j++) {
sol[arr[j][2]] = mem[j][valIzq/10][valDer/10].y;
if(mem[j][valIzq/10][valDer/10].y == 1)valIzq = arr[j][1];
else if(mem[j][valIzq/10][valDer/10].y == 2)valDer = arr[j][1];
}
for (int j = 0; j < sol.length; j++)
sb.append(sol[j] + "\n");
}
System.out.print(new String(sb));
} |
5be4907c-6afc-463b-bd4b-b49c310a9f24 | 7 | public static Stella_Object accessMarkerTableSlotValue(MarkerTable self, Symbol slotname, Stella_Object value, boolean setvalueP) {
if (slotname == Logic.SYM_LOGIC_TEST_TABLE) {
if (setvalueP) {
self.testTable = ((HashTable)(value));
}
else {
value = self.testTable;
}
}
else if (slotname == Logic.SYM_LOGIC_RECALL_TABLE) {
if (setvalueP) {
self.recallTable = ((List)(value));
}
else {
value = self.recallTable;
}
}
else if (slotname == Logic.SYM_LOGIC_SUPPORTS_RECALLp) {
if (setvalueP) {
self.supportsRecallP = BooleanWrapper.coerceWrappedBooleanToBoolean(((BooleanWrapper)(value)));
}
else {
value = (self.supportsRecallP ? Stella.TRUE_WRAPPER : Stella.FALSE_WRAPPER);
}
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + slotname + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
return (value);
} |
60aa0d5b-6dc8-41a4-93a7-06fd613f89f6 | 5 | public Object match(final String path) {
if (rules.containsKey(path)) {
return rules.get(path);
}
int n = path.lastIndexOf('/');
for (Iterator it = lpatterns.iterator(); it.hasNext();) {
String pattern = (String) it.next();
if (path.substring(n).endsWith(pattern)) {
return rules.get(pattern);
}
}
for (Iterator it = rpatterns.iterator(); it.hasNext();) {
String pattern = (String) it.next();
if (path.startsWith(pattern)) {
return rules.get(pattern);
}
}
return null;
} |
e3466c72-8e26-4189-9387-2e514cc9b899 | 5 | @Override
public long[] run(String query) {
FUNCTION_NAME = "PRM";
query = query.toUpperCase();
boolean state = true;
SQLParser parser = new SQLParser();
state &= parser.parse(query + ".txt"); // file name
wrieteGlobalInfoToHDFS(parser);
long[] time = new long[4];
long startTime = new Date().getTime();
if (state) {
if (state) { // init conf
Configuration conf = new Configuration();
state &= doFirstPhase(query, conf, PATH_OUTPUT_FIRST, parser.getDimensionTables());
time[0] = new Date().getTime() - startTime;
startTime = new Date().getTime();
}
if (state) { // init conf
Configuration conf = new Configuration();
state &= doSecondPhase(query, conf, PATH_OUTPUT_SECOND, parser.getDimensionTables(), parser.getFilterTables(),
(parser.getTables().length - 1)*reduceScale);
time[1] = new Date().getTime() - startTime;
startTime = new Date().getTime();
}
if (state) {
Configuration conf = new Configuration();
state &= doThirdPhase(query.toUpperCase(), conf, PATH_OUTPUT_THIRD);
time[2] = new Date().getTime() - startTime;
startTime = new Date().getTime();
}
if (state) {
Configuration conf = new Configuration();
state &= doForthPhase(query.toUpperCase(), conf, PATH_OUTPUT_FINAL);
time[3] = new Date().getTime() - startTime;
}
}
return time;
} |
df030563-114e-463b-b7f5-8f539370f3c3 | 6 | @Override
public void getInput() {
int selection = -1;
boolean isValid = false;
do {
this.displayMenu();
Scanner input = SnakeWithPartner.getInFile();
do {
try {
selection = input.nextInt();
isValid = true;
} catch (NumberFormatException numx) {
System.out.println("Invalid Input. Please input a valid number.");
isValid = false;
}
} while (!isValid);
switch (selection) {
case 1:
this.helpMenuControl.displayRules();
break;
case 2:
this.helpMenuControl.displayControls();
break;
case 0:
break;
default:
System.out.println("Please enter a valid menu item:");
continue;
}
} while (selection != 0);
} |
e87260fd-01e9-4a9a-88e1-48ea8e09846e | 3 | @Action(name = "hcomponent.handler.onkeydown.invoke", args = { "undefined" })
public void onKeyDownInvoke(Updates updates, String[] args, String param) {
HComponent<?> html = (HComponent<?>) Session.getCurrent().get(
"_hcomponent.object." + param);
if (html.getOnKeyDownListener() != null)
Session.getCurrent().gethActionManager().invokeHAction(html.getOnKeyDownListener(), updates, args, param);
} |
639db4ca-8973-4adb-991a-4ed7d1cd22dd | 1 | private boolean jj_3R_87() {
if (jj_scan_token(INTEGER_LITERAL)) return true;
return false;
} |
7d051f62-8b95-400e-a6de-eed0528dbe75 | 5 | public static String getTruncatedPathName(String pathNameString, String truncationString) {
// we keep info thru the first directory
// then separator..separator
// then filename
// if just two separators in pathname, we do nothing
// c:\foo.txt
// one separator, do nothing
// c:\moo\foo.txt
// two separators, do nothing
// c:\moo\boo\foo.txt
// three separators
// replace info tween separators 2 and 3 with ..
// c:\moo\..\foo.txt
// c:\moo\boo\goo\foo.txt
// four separators
// replace
// so: our scheme:
// scan for separators, from left
// note positions of 2nd and, if more than 2, last
// then: build a string out of substring thru 2nd sep
// plus our trunc string
// plus substring from last sep thru til end
// local vars
int secondSeparator = -1 ;
int lastSeparator = -1 ;
int length = pathNameString.length() ;
// we're scanning the full string
for (int scanner = 0, separatorCount = 0; scanner < length; scanner ++) {
// if we find a separator char ...
if (pathNameString.charAt(scanner) == File.separatorChar) {
// note the find
separatorCount ++ ;
// if this is the second separator ..
if (separatorCount == 2) {
secondSeparator = scanner ;
// else it's provisionally the last separator
} else {
lastSeparator = scanner ;
} // end if-else
} // end if
} // end for
// if we have 2 or fewer separators, just return the pathname
if ( (secondSeparator == -1) || (lastSeparator < secondSeparator) ) {
return pathNameString ;
} // end if
// okay, we have more than 2 separators
// [srk] var here just temp for testing ... return directly once cooked
String resultString = (pathNameString.substring(0, secondSeparator + 1)
+ truncationString
+ pathNameString.substring(lastSeparator, length)) ;
return resultString ;
} // end method getTruncatedPathName |
84d387a4-6359-4d3e-a133-f02d46ee0843 | 1 | @Test
public void executeScenario() throws UnknownHostException {
logger_.info("[Repair Scenario 4 Start] Peer on \"1\" repairs subtree on \"0\"");
Injector injector = ScenarioSharedState.getInjector();
localPeerContextInit(injector);
LocalPeerContext context = injector.getInstance(LocalPeerContext.class);
Host[] zeroLevel = context.getLocalRT().getLevelArray(0);
Host[] firstLevel = context.getLocalRT().getLevelArray(1);
Assert.assertTrue("Something went wrong during test initialization. " +
"Conjugate subtree is overpopulated.",
(zeroLevel.length == 2) && (firstLevel.length == 1));
logger_.info("=====================================================================================");
logger_.info("Repairing host {}:{} [path: {}]",
new Object[]{
zeroLevel[1].getAddress(),
zeroLevel[1].getPort(),
zeroLevel[1].getHostPath()});
RepairService repairService = injector.getInstance(RepairService.class);
repairService.fixNode(zeroLevel[1]);
logger_.info("Localhost instance: {}:{} [path: {}]",
new Object[]{
context.getLocalRT().getLocalhost().getAddress(),
context.getLocalRT().getLocalhost().getPort(),
context.getLocalRT().getLocalhost().getHostPath()});
logger_.info("[Repair Scenario 4 End]");
Assert.assertTrue(context.getLocalRT().getLocalhost().getAddress().getHostAddress().compareTo(localIP_) == 0);
Assert.assertTrue(context.getLocalRT().getLocalhost().getPort() == localPort_);
Assert.assertTrue(context.getLocalRT().getLocalhost().getHostPath().toString().compareTo(expectedFinalPath_) == 0);
Assert.assertTrue(context.getLocalRT().levelNumber() == expectedLevelNumber_);
} |
14e68607-57c9-4bec-b37e-e5cd2a1055c6 | 2 | @Override
public GetGameModelResponse getGameModel(int version, String cookie) {
ArrayList<Pair<String,String>> requestHeaders = new ArrayList<Pair<String,String>>();
requestHeaders.add(new Pair<String,String>(COOKIE_STR, cookie));
ICommandResponse response = this.clientCommunicator.executeCommand(RequestType.GET, requestHeaders, "game/model?version=" + Integer.toString(version), null, ServerModel.class);
//ICommandResponse response = this.clientCommunicator.executeCommand(RequestType.GET, requestHeaders, "game/model", null, ServerModel.class);
boolean needToUpdate = true;
if(response.getResponseObject() == null) {
needToUpdate = false;
}
boolean successful = response.getResponseCode() == 200;
return new GetGameModelResponse(successful, successful ? (ServerModel)response.getResponseObject() : null, needToUpdate);
} |
1521a2c2-108c-4722-8d75-2224f2a766ac | 6 | @Override
public void perform(CommandSender sender, String[] args) {
if (args.length < 3)
{
inform(sender, "Usage: /give <player> <badge>");
}
Player player = Bukkit.getPlayerExact(args[1]);
try
{
badge = Badge.fromInt(Integer.parseInt(args[2]));
}
catch (NumberFormatException e)
{
badge = Badge.fromString(args[2].toLowerCase());
}
if (badge == null)
{
badge = Badge.fromString(args[2]);
if (badge == null)
{
inform(sender, "Please enter a valid badge id");
return;
}
}
if (player != null)
{
Material material = Material.matchMaterial(badge.getID().toString());
if (material != null)
{
int amount = 1;
short data = 0;
player.getInventory().addItem(new ItemStack[] { new ItemStack(material, amount, data) });
broadcast(sender, player.getDisplayName() + ChatColor.WHITE + " Has just received the " + ChatColor.GOLD + badge.getFormalName() + ChatColor.WHITE + " badge!");
}
else
{
inform(sender, "Invalid badge ID: " + args[2]);
}
}
else
{
inform(sender, "Can't find the player named: " + args[1]);
}
} |
1225be2b-2b3d-42de-9327-d0f4c0682f8d | 2 | private void validateVertex(int v) {
if (v < 0 || v >= V)
throw new IndexOutOfBoundsException("vertex " + v + " is not between 0 and " + (V-1));
} |
92304d07-869d-4f9d-94b3-c5558ff57b7d | 3 | void begin() {
while(true){
if(toDo.isEmpty() == true){
toDo.addAll(done);
toDo.add(new DefaultState(as));
done.clear();
}
if(toDo.peek() == null){
toDo.remove();
}
else{
toDo.peek().show();
done.add(toDo.poll().next());
}
}
} |
ec85de06-e480-4bcf-8922-cd164e342f5b | 5 | public void filter(byte[] samples, int offset, int length) {
if (source == null || listener == null) {
// nothing to filter - return
return;
}
// calculate the listener's distance from the sound source
float dx = (source.getX() - listener.getX());
float dy = (source.getY() - listener.getY());
float distance = (float)Math.sqrt(dx * dx + dy * dy);
// set volume from 0 (no sound) to 1
float newVolume = (maxDistance - distance) / maxDistance;
if (newVolume <= 0) {
newVolume = 0;
}
// set the volume of the sample
int shift = 0;
for (int i=offset; i<offset+length; i+=2) {
float volume = newVolume;
// shift from the last volume to the new volume
if (shift < NUM_SHIFTING_SAMPLES) {
volume = lastVolume + (newVolume - lastVolume) *
shift / NUM_SHIFTING_SAMPLES;
shift++;
}
// change the volume of the sample
short oldSample = getSample(samples, i);
short newSample = (short)(oldSample * volume);
setSample(samples, i, newSample);
}
lastVolume = newVolume;
} |
91c898a0-3f0e-41b3-986a-2eebfd30eaae | 0 | public static void main(String[] args) {
new _6_Initialization();
} |
1f5ef34f-c35a-4662-bce5-c14557526784 | 2 | public final void startup(CmdLine cmdLine) {
if (mHasStarted) {
System.err.println(getClass().getSimpleName() + ".startup(...) may only be called once."); //$NON-NLS-1$
} else {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this);
configureApplication(cmdLine);
LaunchProxy.getInstance().setReady(true);
for (File file : cmdLine.getArgumentsAsFiles()) {
OpenDataFileCommand.open(file);
}
EventQueue.invokeLater(this);
}
} |
72a44337-ffe3-425e-97af-fddf67830f1f | 7 | @Override
public String process(HttpServletRequest request)
throws MissingRequiredParameter {
String password = request.getParameter("password");
String name = request.getParameter("name");
String surname = request.getParameter("surname");
String email = request.getParameter("email");
int idtipo = 3;
String direccion = request.getParameter("direccion");
String ciudad = request.getParameter("ciudad");
String telefono = request.getParameter("telefono");
if (password == null || email == null) {
throw new MissingRequiredParameter();
}
CheckUserHandler checkUserHandler = new CheckUserHandler();
String jsonResult = checkUserHandler.process(request);
JSONParser parser = new JSONParser();
KeyFinder finder = new KeyFinder();
finder.setMatchKey("result");
boolean alreadyExists = true;
try {
while (!finder.isEnd()) {
parser.parse(jsonResult, finder, true);
if (finder.isFound()) {
finder.setFound(false);
alreadyExists = Boolean.parseBoolean(finder.getValue()
.toString());
}
}
} catch (ParseException pe) {
pe.printStackTrace();
}
if (alreadyExists)
return "{\"status\":\"KO\", \"result\": \"El usuario ya existe.\"}";
User user = new User();
try {
connection = dataSource.getConnection();
statement = connection.createStatement();
/*StringBuffer update = new StringBuffer(
"INSERT INTO usuarios (email, password, nombre, apellidos,direccion,ciudad,telefono,id_tipo) VALUES (");
update.append("'" + email + "', ");
update.append("'" + password + "', ");
update.append("'" + name + "', ");
update.append("'" + surname + "', ");
update.append("'" + direccion + "', ");
update.append("'" + ciudad + "', ");
update.append("'" + telefono + "', ");
update.append("'" + idtipo + "', ");
update.append(")");
System.out.println(update);
statement.executeUpdate(update.toString());*/
statement.execute("insert into usuarios (email, password, nombre, apellidos,direccion,ciudad,telefono,id_tipo) values ('"+email+"', '"+password+"','"+name+"','"+surname+"','"+direccion+"','"+ciudad+"','"+telefono+"','"+idtipo+"');");
//ResultSet rs = statement.getGeneratedKeys();
//if (rs.next())
//user.setId(rs.getInt(1));
} catch (SQLException e) {
// e.printStackTrace();
return "{\"status\":\"KO\", \"result\": \"Error en el acceso a la base de datos.\"}";
}
user.setIdtipo(idtipo);
user.setName(name);
user.setSurname(surname);
user.setEmail(email);
HttpSession session = request.getSession();
session.setAttribute("user", user);
String result = "{\"status\":\"OK\", \"result\":" + user.toJSONString()
+ "}";
return result;
} |
ee2cbca1-1299-46d8-846f-66ca5e5e1f45 | 0 | public static void main(String[] args) {
DotThis dt = new DotThis();
Inner dti = dt.inner();
dti.outer().f();
} |
7792dbbe-50f9-459c-8ac2-c068f1ea61a1 | 1 | public static boolean isValidName(String name) {
if (name == null) {
return false;
}
return name.length() > 3;
} |
c2cfd361-a67d-4a67-9248-fea91893844f | 8 | public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Starting Threads");
System.out.println("*******************************************");
Thread.yield();
final ArrayList<Integer> _al;
ArrayList<Integer> _bl = new ArrayList<Integer>();
for(int index = 0; index<10;index++){
_bl.add(index, (Integer)index);
}
_al = _bl;
if(_al.size()>0){
System.out.println("I am in ");
new Thread(){
public void run(){
for(int i=0;i<10;i++){
System.out.println("a -"+_al.get(i));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Thread interruped on "+i+"iteration of a");
e.printStackTrace();
}
}
}
}.start();
new Thread(){
public void run(){
for(int i=0;i<10;i++){
System.out.println("b -"+_al.get(i));
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("Thread interruped on "+i+"iteration of b");
e.printStackTrace();
}
}
}
}.start();
new Thread(){
public void run(){
for(int i=0;i<10;i++){
System.out.println("c -"+_al.get(i));
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("Thread interruped on "+i+"iteration of c");
e.printStackTrace();
}
}
}
}.start();
}
System.out.println("*******************************************");
System.out.println("Threads Completed");
} |
0868f59d-9d7e-4aec-b7aa-226b2568ac0b | 2 | public boolean filter(List<String> allowedFrameElements){
boolean result = false;
Iterator<String> iter = frameElements.keySet().iterator();
while (iter.hasNext()) {
if(allowedFrameElements.contains(iter.next())){
result = true;
}else{
iter.remove();
}
}
return result;
} |
f3c7a0b5-d723-491d-b891-60a3c3101b8a | 2 | @Test
public void testCustomUserAgentParsing() {
// Test limited to the big browser families. As Camino can not be detected any longer, the second best match is Firefox3 (a child of Firefox).
for (String agentString : camino2) {
assertEquals(Browser.FIREFOX3, Browser.parseUserAgentString(agentString,Arrays.asList(Browser.IE,Browser.CHROME, Browser.APPLE_WEB_KIT, Browser.FIREFOX)));
}
// When there is no match in the given set, return UNKNOWN
for (String agentString : opera9) {
assertEquals(Browser.UNKNOWN, Browser.parseUserAgentString(agentString,Arrays.asList(Browser.IE,Browser.CHROME, Browser.APPLE_WEB_KIT, Browser.FIREFOX)));
}
} |
3421d2c7-3292-48fa-9d49-59817ca207c9 | 4 | public void addStudent(Student student) throws IllegalArgumentException {
// Student names must be unique. This is because of a bug in JComboBox where
// getSelectedIndex() returns the first index that contains the name of
// the selected item: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4133743
// I don't agree with this, because it forces all items in JComboBox to
// be unique, but c'est la vie.
//for ( Student s : this.students )
for ( int i = 0; i < this.numStudents; i++ ) {
Student s = this.students[i];
if ( s.getName().equals( student.getName() ) )
throw new IllegalArgumentException("There is already a student with this name in the system.");
}
//this.students.add(student);
if ( this.numStudents < this.students.length ) {
this.students[numStudents++] = student;
} else {
throw new IllegalArgumentException("There are only 100 students allowed");
}
for (ChangeListener l : this.listeners) {
l.stateChanged(new ChangeEvent(this));
}
} |
49678b26-10c5-4308-bce1-08f22eae27ec | 9 | public static String getPrimitiveName(char c) {
switch (c) {
case 'B':
return "byte";
case 'C':
return "char";
case 'D':
return "double";
case 'F':
return "float";
case 'I':
return "int";
case 'J':
return "long";
case 'S':
return "short";
case 'Z':
return "boolean";
case 'V':
return "void";
}
return null;
} |
cfc2bb6b-7c9a-4727-a66e-56f5894f2943 | 3 | @SuppressWarnings("unchecked")
@Override
public double getScore(Object userAnswer) {
if (userAnswer == null)
return 0;
String ans = (String) userAnswer;
ArrayList<String> trueAns = (ArrayList<String>) answer;
for (int i = 0; i < trueAns.size(); i++) {
if (trueAns.get(i).equals(ans))
return score;
}
return 0;
} |
c2d883f6-24fc-4067-a99f-122d0d6aeb1d | 4 | protected void handleObject(Object obj) {
if (obj == null)
return;
if (associatedMethods.get(obj.getClass()) == null)
return;
try {
associatedMethods.get(obj.getClass()).invoke(this, obj);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} |
5e0941f9-e8a2-4327-942a-8b9edd0c3ec5 | 6 | public void updateMailToAndCc(String to, String cc) {
Address[] receiverAddress = createAddressFromStandardString(to);
if (receiverAddress == null) {
//如果没有设置收件人,则直接发送给发件人
try {
receiverAddress = mMailMessage.getFrom();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (receiverAddress != null) {
try {
mMailMessage.setRecipients(Message.RecipientType.TO, receiverAddress);
} catch (Exception e) {
e.printStackTrace();
}
}
Address[] ccReceiverAddress = createAddressFromStandardString(cc);
if (ccReceiverAddress != null) {
try {
mMailMessage.setRecipients(Message.RecipientType.CC, ccReceiverAddress);
} catch (Exception e) {
e.printStackTrace();
}
};
} |
f7509117-a0ca-4ac5-a273-9b40fbba2216 | 7 | @SuppressWarnings("rawtypes")
public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
Player player = (Player) sender;
ChatColor blue = ChatColor.AQUA;
ChatColor gold = ChatColor.GOLD;
if (player.hasPermission("skeptermod.usecommand.smclear")
|| (player.isOp())); {
if (command.getName().equalsIgnoreCase("smclear")); {
if (args.length == 0) {
int i = 0;
for (Iterator iterator1 = Bukkit.getServer().getWorlds()
.iterator(); iterator1.hasNext();) {
World world = (World) iterator1.next();
for (Iterator iterator2 = world.getEntities()
.iterator(); iterator2.hasNext();) {
Entity e = (Entity) iterator2.next();
if (e instanceof Item) {
i++;
e.remove();
}
}
}
player.sendMessage(gold + "[Skeptermod] " + blue
+ "Removed " + i + " dropped items");
}
}
}
return true;
} |
26258c51-51be-4a83-af1c-cb26699588c1 | 5 | public void checkNext() {
if (this.proceedToNext()) {
this.cardBot.sendMessage("##cah", Colors.BOLD + "All players have submitted their cards." + Colors.NORMAL + " Time for " + this.czar.getName() + " to pick the winning card.");
this.cardBot.sendMessage("##cah", this.blackCard.getColored());
this.cardBot.sendNotice(this.czar.getName(), "Say the number of the card you wish to win.");
Collections.shuffle(this.players);
this.playerIter = new ArrayList<Player>(this.players);
this.playerIter.remove(this.czar);
for (int i = 0; i < this.playerIter.size(); i++) {
final Player player = this.playerIter.get(i);
if (player.isWaiting()) {
this.playerIter.remove(player);
}
}
for (int i = 0; i < this.playerIter.size(); i++) {
final Player player = this.playerIter.get(i);
if (this.blackCard.getAnswers() == 1) {
this.cardBot.sendMessage("##cah", i + 1 + ": " + player.getPlayedCards()[0].getColored());
} else {
this.cardBot.sendMessage("##cah", i + 1 + ": " + player.getPlayedCards()[0].getColored() + " | " + player.getPlayedCards()[1].getColored());
}
}
this.gameStatus = GameStatus.CZAR_TURN;
}
} |
d9222829-bf1f-4f1e-87c1-e62e19bf60dc | 4 | public void draw(Graphics g)
{
printLEDNumbers();
if (isAlive && !isPaused)
{
advance();
}
else if (isAlive && isPaused)
{
g.setColor(Color.red);
g.drawString("PAUSED", 200, 40);
}
else
{
g.setColor(Color.red);
g.drawString("GAME OVER (press 'N' for new game)", 200, 40);
}
//board.draw(g);
//drawCurrentPiece(g);
g.setColor(Color.red);
g.drawString("Score: "+Integer.toString(board.getScore()), 200, 475);
} |
f5c80bbb-0c72-49e0-8dee-cdcfd395efca | 3 | public void removeSetting(String key) {
if (getValue(key).equals("null"))
return;
synchronized(settings) {
for (int i = 0; i < settings.size(); i++) {
if (settings.get(i).split("=")[0].trim().equalsIgnoreCase(key)) {
settings.remove(i);
break;
}
}
}
} |
82a7d155-91cb-40ee-9cd6-c5e07cb4e9fa | 3 | @SuppressWarnings("resource")
@Override
public JsonObject getData() {
JsonObject json = new JsonObject();
checkFile(config.getPath());
File file = new File(this.config.getPath());
try {
if(file.isFile()){
json = read(file);
}else{
json = readFiles();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
} |
30e69993-b037-4d71-a059-5c9d17ac9dc5 | 9 | @Deprecated
public static String eventuallyRemoveStartingAndEndingDoubleQuote(String s) {
if (s.length() > 1 && isDoubleQuote(s.charAt(0)) && isDoubleQuote(s.charAt(s.length() - 1))) {
return s.substring(1, s.length() - 1);
}
if (s.startsWith("(") && s.endsWith(")")) {
return s.substring(1, s.length() - 1);
}
if (s.startsWith("[") && s.endsWith("]")) {
return s.substring(1, s.length() - 1);
}
if (s.startsWith(":") && s.endsWith(":")) {
return s.substring(1, s.length() - 1);
}
return s;
} |
333950aa-0f10-4596-bbfc-a35e529b06d7 | 9 | List<Equipo> getEquipos(String categoriaId, String deporteId) {
List<Equipo> listaEquipos=null;
String tituloDeporte="deporteId";
Map<String, Equipo> mapaEquipos = new HashMap();
Categoria categoria = torneos.getCategoria(categoriaId);
String tituloCategoria = categoria.getTitulo();
// Buscamos la información del deporte (¡mejorar!):
List<Deporte> listaDeportes = categoria.getListaDeportes();
Deporte deporte=null;
for(int i=0;deporte==null&&i<listaDeportes.size();i++){
Deporte deporte_=listaDeportes.get(i);
if(deporte_.getId().compareTo(deporteId)==0){
deporte=deporte_;
}
}
if(deporte!=null){
tituloDeporte=deporte.getTitulo();
}
// Se busca, para cada partido del deporte y torneo indicado, en cada fase, los equipos existentes:
List<Fase> listaclasificaciones = categoria.getFases(deporteId);
for (Fase fase : listaclasificaciones) {
List<Ronda> listaRondas = fase.getRondas();
for (Ronda ronda : listaRondas) {
List<Partido> listaPartidos = ronda.getPartidos();
for (Partido partido : listaPartidos) {
Equipo equipo1 = partido.getEquipo1();
Equipo equipo2 = partido.getEquipo2();
DatosEquipo datosEquipo = new DatosEquipo(equipo1, tituloCategoria, tituloDeporte);
mapaEquipos.put(datosEquipo.getTituloCategoria() + ">" + datosEquipo.getTituloDeporte() + ">" + equipo1.getNombre(), equipo1);
datosEquipo = new DatosEquipo(equipo2, tituloCategoria, tituloDeporte);
mapaEquipos.put(datosEquipo.getTituloCategoria() + ">" + datosEquipo.getTituloDeporte() + ">" + equipo2.getNombre(), equipo2);
}
}
}
if (!mapaEquipos.isEmpty()) {
listaEquipos = new ArrayList<Equipo>();
for (Equipo datosEquipo : mapaEquipos.values()) {
listaEquipos.add(datosEquipo);
}
// Ordenamos la lista de equipos...
Collections.sort(listaEquipos, new Comparator<Equipo>() {
@Override
public int compare(Equipo t, Equipo t1) {
String s = t.getNombre();
String s1 =t1.getNombre();
return s1.compareTo(s);
}
});
}
return listaEquipos;
} |
a1c39487-3206-4b79-b306-813b6c168c76 | 7 | public void doSave() {
UserBean userBean = (UserBean) BeanHelper.getBean("userBean");
//load unitate into hashmap
List<Unitate> unitateList = userBean.getUser().getSirues().getUnitateList();
HashMap<String, Long> siruesMap = new HashMap<>();
HashMap<Long, Integer> countMap = new HashMap<>();
for (int i = 0; i < unitateList.size(); i++) {
siruesMap.put(unitateList.get(i).getNumeRo(), unitateList.get(i).getSirues());
countMap.put(unitateList.get(i).getSirues(), 0);
}
//loop over imageList
for (int i = 0; i < imageList.size(); i++) {
SchoolImage schoolImage = imageList.get(i);
if (!schoolImage.getDestination().equals(SchoolImage.DESTINATION_UNUSED)) {
//if used whe check usage
File oldName = new File(FILE_PREFIX + "/" + schoolImage.getFileName());
File newName;
Long sirues = siruesMap.get(schoolImage.getUnitatea());
if (schoolImage.getDestination().equals(SchoolImage.DESTINATION_FACADE)) {
//facade, only 1 image
newName = new File(FILE_PREFIX + "/" + sirues + "_fata.jpeg");
} else {
//class, we keep count
newName = new File(FILE_PREFIX + "/" + sirues + "_" + countMap.get(sirues) + ".jpeg");
countMap.put(sirues, countMap.get(sirues) + 1);
}
try {
if (newName.exists()) {
newName.delete();
}
if (oldName.renameTo(newName)) {
System.out.println("Saved as: " + newName.getAbsolutePath());
} else {
//Rename failed, making copy
//copy file with Java 7 API
Path oldPath = Paths.get(oldName.getAbsolutePath());
Path newPath = Paths.get(newName.getAbsolutePath());
Files.copy(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING);
//copy file
/*FileOutputStream fileOutputStream = new FileOutputStream(newName);
byte[] buffer = new byte[BUFFER_SIZE];
int bulk;
InputStream inputStream = new FileInputStream(oldName);
while (true) {
bulk = inputStream.read(buffer);
if (bulk < 0) {
break;
}
fileOutputStream.write(buffer, 0, bulk);
fileOutputStream.flush();
}
fileOutputStream.close();
inputStream.close();*/
System.out.println("Copy to: " + newName.getAbsolutePath() + " scuccess!");
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
imageList.clear();
} |
e6d7ccdd-18c7-41bb-a950-144091278868 | 5 | @Override
protected Void doInBackground() {
final int BUFFER_SIZE = 2048;
BufferedInputStream bis = null;
ByteArrayOutputStream baos;
String prefix = ConfigManager.getInstance().getClientPrefix();
String addr = ConfigManager.getInstance().getProperties().getProperty("updateurl");
addr = addr.replace("%PREFIX%", prefix);
addr = addr.replace("%FILE%", this.path);
try {
URL url = new URL(addr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "User-Agent: Kubach v" + Constants.VERSION);
this.totalProgressValue = connection.getContentLength();
int totalDataRead = 0;
bis = new BufferedInputStream(connection.getInputStream());
baos = new ByteArrayOutputStream();
try (BufferedOutputStream bos = new BufferedOutputStream(baos, BUFFER_SIZE)) {
byte[] data = new byte[BUFFER_SIZE];
int i = 0;
while ((i = bis.read(data)) != -1) {
totalDataRead = totalDataRead + i;
baos.write(data, 0, i);
publish(new SyncTaskState(addr, "Downloading (" + String.format("%.2f", totalDataRead / (float) this.totalProgressValue * 100) + "%)", totalDataRead));
}
// Write file to disk
File f = new File(this.pathToFile);
writeBytesToFile(f, baos.toByteArray());
publish(new SyncTaskState(addr, "Finished", this.totalProgressValue, f));
}
} catch (IOException ex) {
ex.printStackTrace();
if (--numTries > 0) {
publish(new SyncTaskState(addr, "Retrying...", 0));
this.doInBackground();
} else {
publish(new SyncTaskState(addr, "FAILED", 0));
}
} finally {
try {
bis.close();
} catch (IOException ex) {
ex.printStackTrace();
if (--numTries > 0) {
publish(new SyncTaskState(addr, "Retrying...", 0));
this.doInBackground();
} else {
publish(new SyncTaskState(addr, "FAILED", 0));
}
}
}
return null;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.