semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
private void saveVideo(URL url, DownloadTask task) {
        if (url == null) {
            return;
        }
        FileOutputStream out = null;
        InputStream stream = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File file = new File(task.source.getPreferredVideoLocation("mp4"));
        publish("Starting download to file:" + file.getAbsolutePath());
        try {
            out = new FileOutputStream(file);
            URLConnection uc = url.openConnection();
            String contentType = uc.getContentType();
            int length = uc.getContentLength();
            StatisticsStorage.numberofdownloadedbytes += length;
            publish("Content type: " + contentType + " with a length of " + length);
            stream = uc.getInputStream();
            bis = new BufferedInputStream(stream);
            bos = new BufferedOutputStream(out);
            byte[] bytes = new byte[1024];
            int i = 0;
            long time = System.currentTimeMillis();
            int nextbyte;
            while ((nextbyte = bis.read()) != -1) {
                bos.write(nextbyte);
                i++;
                if (System.currentTimeMillis() - time >= 1000) {
                    publish("downloaded " + (i++) + " bytes of " + length + " bytes.");
                    time = System.currentTimeMillis();
                    int progress = (i - 1) / length;
                    if (progress <= 100 && progress >= 0) setProgress(progress);
                }
            }
            bos.write(bytes);
        } catch (IOException e) {
            System.err.println(url);
            e.printStackTrace();
        } finally {
            try {
                if (out != null) out.close();
                if (stream != null) stream.close();
                if (bis != null) bis.close();
                if (bos != null) bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("done downloading video");
        task.source.setVideo(file.getAbsolutePath());
        if (task.source.hasLyrics()) {
            task.source.getLyrics().setTag("Video", file.getName());
        }
    }
private final void reOrderFriendsListByOnlineStatus() {
        boolean flag = true;
        while (flag) {
            flag = false;
            for (int i = 0; i < friendsCount - 1; i++) if (friendsListOnlineStatus[i] < friendsListOnlineStatus[i + 1]) {
                int j = friendsListOnlineStatus[i];
                friendsListOnlineStatus[i] = friendsListOnlineStatus[i + 1];
                friendsListOnlineStatus[i + 1] = j;
                long l = friendsListLongs[i];
                friendsListLongs[i] = friendsListLongs[i + 1];
                friendsListLongs[i + 1] = l;
                flag = true;
            }
        }
    }
public void zipDocsetFiles(SaxHandler theXmlHandler, int theEventId, Attributes theAtts) throws BpsProcessException {
        ZipOutputStream myZipOut = null;
        BufferedInputStream myDocumentInputStream = null;
        String myFinalFile = null;
        String myTargetPath = null;
        String myTargetFileName = null;
        String myInputFileName = null;
        byte[] myBytesBuffer = null;
        int myLength = 0;
        try {
            myZipOut = new ZipOutputStream(new FileOutputStream(myFinalFile));
            myZipOut.putNextEntry(new ZipEntry(myTargetPath + myTargetFileName));
            myDocumentInputStream = new BufferedInputStream(new FileInputStream(myInputFileName));
            while ((myLength = myDocumentInputStream.read(myBytesBuffer, 0, 4096)) != -1) myZipOut.write(myBytesBuffer, 0, myLength);
            myZipOut.closeEntry();
            myZipOut.close();
        } catch (FileNotFoundException e) {
            throw (new BpsProcessException(BpsProcessException.ERR_OPEN_FILE, "FileNotFoundException while building zip dest file"));
        } catch (IOException e) {
            throw (new BpsProcessException(BpsProcessException.ERR_OPEN_FILE, "IOException while building zip dest file"));
        }
    }
protected synchronized String encryptThis(String seed, String text) throws EncryptionException {
        String encryptedValue = null;
        String textToEncrypt = text;
        if (seed != null) {
            textToEncrypt = seed.toLowerCase() + text;
        }
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(textToEncrypt.getBytes("UTF-8"));
            encryptedValue = (new BASE64Encoder()).encode(md.digest());
        } catch (Exception e) {
            throw new EncryptionException(e);
        }
        return encryptedValue;
    }
private void init(URL url) {
            frame = new JInternalFrame(name);
            frame.addInternalFrameListener(this);
            listModel.add(listModel.size(), this);
            area = new JTextArea();
            area.setMargin(new Insets(5, 5, 5, 5));
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
                String in;
                while ((in = reader.readLine()) != null) {
                    area.append(in);
                    area.append("\n");
                }
                reader.close();
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
            th = area.getTransferHandler();
            area.setFont(new Font("monospaced", Font.PLAIN, 12));
            area.setCaretPosition(0);
            area.setDragEnabled(true);
            area.setDropMode(DropMode.INSERT);
            frame.getContentPane().add(new JScrollPane(area));
            dp.add(frame);
            frame.show();
            if (DEMO) {
                frame.setSize(300, 200);
            } else {
                frame.setSize(400, 300);
            }
            frame.setResizable(true);
            frame.setClosable(true);
            frame.setIconifiable(true);
            frame.setMaximizable(true);
            frame.setLocation(left, top);
            incr();
            SwingUtilities.invokeLater(new Runnable() {

                public void run() {
                    select();
                }
            });
            nullItem.addActionListener(this);
            setNullTH();
        }
public static ByteBuffer join(ByteBuffer buffer1, ByteBuffer buffer2) {
        if (buffer2 == null || buffer2.remaining() == 0) return NIOUtils.copy(buffer1);
        if (buffer1 == null || buffer1.remaining() == 0) return NIOUtils.copy(buffer2);
        ByteBuffer buffer = ByteBuffer.allocate(buffer1.remaining() + buffer2.remaining());
        buffer.put(buffer1);
        buffer.put(buffer2);
        buffer.flip();
        return buffer;
    }
@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getRequestURI().split("/")[3];
        if (log.isDebugEnabled()) log.debug("request: " + id + " from: " + request.getRemoteHost());
        Song song = manager.find(id);
        if (song != null) {
            File file = new File(song.getFile());
            if (file.exists()) {
                response.setStatus(HttpServletResponse.SC_OK);
                response.setContentType("audio/" + song.getType());
                response.setContentLength((int) file.length());
                FileInputStream stream = new FileInputStream(file);
                try {
                    IOUtils.copy(stream, response.getOutputStream());
                } finally {
                    IOUtils.closeQuietly(stream);
                }
            } else {
                log.warn("file not found: " + file);
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
        } else {
            log.info("song not found: " + id);
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }
public void myCheckCredHandler(View v) {
        Log.d("login_section", "entered handler");
        EditText Username = (EditText) findViewById(R.id.Username);
        EditText Password = (EditText) findViewById(R.id.user_pass);
        String username_S = Username.getText().toString();
        String pass_S = Password.getText().toString();
        TextView ltv = (TextView) findViewById(R.id.LoginPagetv);
        HttpClient httpclient = createHttpClient();
        HttpPost httppost = new HttpPost(authenticationURL);
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("login", username_S));
            nameValuePairs.add(new BasicNameValuePair("password", pass_S));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            int status = response.getStatusLine().getStatusCode();
            String responseBody = EntityUtils.toString(response.getEntity());
            Log.d("login_section", responseBody);
            JSONObject jsonObject = new JSONObject(responseBody);
            if (status == this.statusOK && jsonObject.getBoolean("logged_in")) {
                ltv.setText("You have been logged in. :D");
                etracks.setLogged(true);
                etracks.setUserToken(jsonObject.getString("user_token"));
                Intent it = new Intent(Intent.ACTION_VIEW);
                it.setClassName(this, etracks.class.getName());
                this.finish();
                startActivity(it);
            } else if (status == this.statusUnprocessable && !jsonObject.getBoolean("logged_in")) {
                if (!jsonObject.isNull("errors")) ltv.setText(jsonObject.getString("errors")); else ltv.setText("login unsuccessful");
            } else Log.d("login_section", "what just happened?");
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
public static void loadConfig(URL urlFile) throws CacheException {
        Document document;
        try {
            document = Utilities.getDocument(urlFile.openStream());
        } catch (IOException e) {
            throw new CacheException("Could not open '" + urlFile.getFile() + "'", e);
        } catch (JAnalyticsException e) {
            throw new CacheException("Could not open '" + urlFile.getFile() + "'", e);
        }
        Element element = (Element) document.getElementsByTagName(DOCUMENT_CACHE_ELEMENT_NAME).item(0);
        if (element != null) {
            String className = element.getAttribute(CLASSNAME_ATTRIBUTE_NAME);
            if (className != null) {
                Properties config = new Properties();
                NodeList nodes = element.getElementsByTagName(PARAM_ELEMENT_NAME);
                if (nodes != null) {
                    for (int i = 0, count = nodes.getLength(); i < count; i++) {
                        Node node = nodes.item(i);
                        if (node instanceof Element) {
                            Element n = (Element) node;
                            String name = n.getAttribute(NAME_ATTRIBUTE_NAME);
                            String value = n.getAttribute(VALUE_ATTRIBUTE_NAME);
                            config.put(name, value);
                        }
                    }
                }
                loadConfig(className, config);
            }
        }
    }
private void openGSM() {
        try {
            GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation();
            int cid = gcl.getCid();
            int lac = gcl.getLac();
            int mcc = Integer.valueOf(tm.getNetworkOperator().substring(0, 3));
            int mnc = Integer.valueOf(tm.getNetworkOperator().substring(3, 5));
            JSONObject holder = new JSONObject();
            holder.put("version", "1.1.0");
            holder.put("host", "maps.google.com");
            holder.put("request_address", true);
            JSONArray array = new JSONArray();
            JSONObject data = new JSONObject();
            data.put("cell_id", cid);
            data.put("location_area_code", lac);
            data.put("mobile_country_code", mcc);
            data.put("mobile_network_code", mnc);
            array.put(data);
            holder.put("cell_towers", array);
            DefaultHttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost("http://www.google.com/loc/json");
            StringEntity se = new StringEntity(holder.toString());
            post.setEntity(se);
            HttpResponse resp = client.execute(post);
            HttpEntity entity = resp.getEntity();
            BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
            StringBuffer sb = new StringBuffer();
            String result = br.readLine();
            while (result != null) {
                sb.append(result);
                result = br.readLine();
            }
            mLat = Double.parseDouble(sb.toString().split(":")[2].split(",")[0]);
            mLon = Double.parseDouble(sb.toString().split(":")[3].split(",")[0]);
        } catch (Exception e) {
        }
        returnGeoLatLon();
    }
public void connect() throws IOException {
        if (log.isDebugEnabled()) log.debug("Connecting to: " + HOST);
        ftpClient.connect(HOST);
        if (log.isDebugEnabled()) log.debug("\tReply: " + ftpClient.getReplyString());
        if (log.isDebugEnabled()) log.debug("Login as anonymous");
        ftpClient.login("anonymous", "");
        if (log.isDebugEnabled()) log.debug("\tReply: " + ftpClient.getReplyString());
        folder = INTACT_FOLDER;
    }
public APIResponse delete(String id) throws Exception {
        APIResponse response = new APIResponse();
        connection = (HttpURLConnection) new URL(url + "/api/record/delete/" + id).openConnection();
        connection.setRequestMethod("DELETE");
        connection.setConnectTimeout(TIMEOUT);
        connection.connect();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            response.setDone(true);
            response.setMessage("Record Deleted!");
        } else {
            response.setDone(false);
            response.setMessage("Delete Record Error Code: Http (" + connection.getResponseCode() + ")");
        }
        connection.disconnect();
        return response;
    }
public static String getDeclaredXMLEncoding(URL url) throws IOException {
        InputStream stream = url.openStream();
        BufferedReader buffReader = new BufferedReader(new InputStreamReader(stream));
        String firstLine = buffReader.readLine();
        if (firstLine == null) {
            return SYSTEM_ENCODING;
        }
        int piStart = firstLine.indexOf("<?xml version=\"1.0\"");
        if (piStart != -1) {
            int attributeStart = firstLine.indexOf("encoding=\"");
            if (attributeStart >= 0) {
                int nextQuote = firstLine.indexOf('"', attributeStart + 10);
                if (nextQuote >= 0) {
                    String encoding = firstLine.substring(attributeStart + 10, nextQuote);
                    return encoding.trim();
                }
            }
        }
        stream.close();
        return SYSTEM_ENCODING;
    }
public void testGetContentInputStream() {
        URL url;
        try {
            url = new URL("http://www.wurzer.org/" + "Homepage/Publikationen/Eintrage/2009/10/7_Wissen_dynamisch_organisieren_files/" + "KnowTech%202009%20-%20Wissen%20dynamisch%20organisieren.pdf");
            InputStream in = url.openStream();
            Content c = provider.getContent(in);
            assertNotNull(c);
            assertTrue(!c.getFulltext().isEmpty());
            assertTrue(c.getModificationDate() < System.currentTimeMillis());
            assertTrue(c.getAttributes().size() > 0);
            assertEquals("KnowTech 2009 - Wissen dynamisch organisieren", c.getAttributeByName("Title").getValue());
            assertEquals("Joerg Wurzer", c.getAttributeByName("Author").getValue());
            assertEquals("Pages", c.getAttributeByName("Creator").getValue());
            assertNull(c.getAttributeByName("Keywords"));
            assertTrue(c.getFulltext().startsWith("Wissen dynamisch organisieren"));
            assertTrue(c.getAttributeByName("Author").isKey());
            assertTrue(!c.getAttributeByName("Producer").isKey());
        } catch (MalformedURLException e) {
            fail("Malformed url - " + e.getMessage());
        } catch (IOException e) {
            fail("Couldn't read file - " + e.getMessage());
        }
    }
private String sendMessage(HttpURLConnection connection, String reqMessage) throws IOException {
        if (msgLog.isTraceEnabled()) msgLog.trace("Outgoing SOAPMessage\n" + reqMessage);
        BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());
        out.write(reqMessage.getBytes("UTF-8"));
        out.close();
        InputStream inputStream = null;
        if (connection.getResponseCode() < 400) inputStream = connection.getInputStream(); else inputStream = connection.getErrorStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        IOUtils.copyStream(baos, inputStream);
        inputStream.close();
        String response = new String(baos.toByteArray(), "UTF-8");
        if (msgLog.isTraceEnabled()) msgLog.trace("Incoming Response SOAPMessage\n" + response);
        return response;
    }
public static synchronized String getSequenceNumber(String SequenceName) {
        String result = "0";
        Connection conn = null;
        Statement ps = null;
        ResultSet rs = null;
        try {
            conn = TPCW_Database.getConnection();
            conn.setAutoCommit(false);
            String sql = "select num from sequence where name='" + SequenceName + "'";
            ps = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
            rs = ps.executeQuery(sql);
            long num = 0;
            while (rs.next()) {
                num = rs.getLong(1);
                result = new Long(num).toString();
            }
            num++;
            sql = "update sequence set num=" + num + " where name='" + SequenceName + "'";
            int res = ps.executeUpdate(sql);
            if (res == 1) {
                conn.commit();
            } else conn.rollback();
        } catch (Exception e) {
            System.out.println("Error Happens when trying to obtain the senquence number");
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) conn.close();
                if (rs != null) rs.close();
                if (ps != null) ps.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        return result;
    }
public static void main(String[] args) {
        StringBuffer htmlPage;
        htmlPage = new StringBuffer();
        double min = 99999.99;
        double max = 0;
        double value = 0;
        try {
            URL url = new URL("http://search.ebay.com/" + args[0]);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;
            while ((line = in.readLine()) != null) {
                htmlPage.append(line);
                htmlPage.append("\n");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        Pattern p = Pattern.compile("\\$([\\d\\.]+)", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(htmlPage);
        while (m.find()) {
            if (m.start(0) < m.end(0)) {
                value = Double.parseDouble(m.group(1));
                if (value < min) {
                    min = value;
                }
                if (value > max) {
                    max = value;
                }
            }
        }
        if (min == 99999.99) {
            min = 0;
        }
        System.out.println(args[0] + "," + min + "," + max);
        System.exit(0);
    }
public static String MD5(String source) {
        logger.info(source);
        String result = null;
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(source.getBytes());
            byte[] bytes = digest.digest();
            result = EncodeUtils.hexEncode(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        logger.info(result);
        return result;
    }
public static String SHA256(String source) {
        logger.info(source);
        String result = null;
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            digest.update(source.getBytes());
            byte[] bytes = digest.digest();
            result = EncodeUtils.hexEncode(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        logger.info(result);
        return result;
    }
public static String SHA(String source) {
        logger.info(source);
        String result = null;
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA");
            digest.update(source.getBytes());
            byte[] bytes = digest.digest();
            result = EncodeUtils.hexEncode(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        logger.info(result);
        return result;
    }
public static void readProperties() throws IOException {
        URL url1 = cl.getResource("conf/soapuddi.config");
        Properties props = new Properties();
        if (url1 == null) throw new IOException("soapuddi.config not found");
        props.load(url1.openStream());
        className = props.getProperty("Class");
        url = props.getProperty("URL");
        user = props.getProperty("user");
        password = props.getProperty("passwd");
        operatorName = props.getProperty("operator");
        authorisedName = props.getProperty("authorisedName");
        isUpdated = true;
    }
private void download(String groupId, String artifactId, String version, String type) throws ClientProtocolException, IOException {
        String finalName = artifactId + "-" + version;
        File file = new File(deployables, groupId + "/" + artifactId + "/" + version + "/" + finalName + "." + type);
        if (file.exists()) {
            log.warn("Won't download {} found at {}", finalName, file.getAbsolutePath());
            return;
        }
        String url = repository + groupId + "/" + artifactId + "/" + version + "/" + finalName + "." + type;
        HttpGet get = new HttpGet(url);
        HttpResponse response = httpclient.execute(get);
        if (response.getStatusLine().getStatusCode() == 200) writeContent(get, response.getEntity(), file); else throw new RuntimeException("Failed to download " + url + " due to error " + response.getStatusLine());
    }
private void initFtp() throws IOException {
        ftpClient.setConnectTimeout(5000);
        ftpClient.connect(ftpHost);
        ftpClient.login(userName, password);
        if (workingDir != null) {
            ftpClient.changeWorkingDirectory(workingDir);
        }
        logger.info("Connection established.");
    }
public List<String[]> getCSV(String name) {
        return new ResourceLoader<List<String[]>>(name) {

            @Override
            protected List<String[]> get(URL url) throws Exception {
                CSVReader reader = null;
                try {
                    reader = new CSVReader(new InputStreamReader(url.openStream()));
                    return reader.readAll();
                } finally {
                    IOUtils.closeQuietly(reader);
                }
            }
        }.get();
    }
@Override
            protected List<String[]> get(URL url) throws Exception {
                CSVReader reader = null;
                try {
                    reader = new CSVReader(new InputStreamReader(url.openStream()));
                    return reader.readAll();
                } finally {
                    IOUtils.closeQuietly(reader);
                }
            }