diff --git "a/datasets/latency.jsonl" "b/datasets/latency.jsonl" new file mode 100644--- /dev/null +++ "b/datasets/latency.jsonl" @@ -0,0 +1,47 @@ +{"non_functional_requirement":"framerate","commit":"https:\/\/github.com\/onyxbits\/listmyaps\/commit\/5065990868de934c2c9aa5dfce01b69b362eb94e","commit_message":"'\\\\\"BUGFIX: Recycle views to scroll faster\\\\n\\\\\"'","source_code":"package de.onyxbits.listmyapps;\n\nimport java.util.List;\n\nimport android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ArrayAdapter;\nimport android.widget.CheckBox;\nimport android.widget.TextView;\n\npublic class AppAdapter extends ArrayAdapter {\n\n\tpublic AppAdapter(Context context, int textViewResourceId,\n\t\t\tList spi) {\n\t\tsuper(context, textViewResourceId, spi);\n\t}\n\t\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n View ret;\n SortablePackageInfo spi = getItem(position);\n \n LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n ret = inflater.inflate(R.layout.app_item,null);\n ((TextView)ret.findViewById(R.id.appname)).setText(spi.displayName);\n ((TextView)ret.findViewById(R.id.apppackage)).setText(spi.packageName);\n CheckBox sel = ((CheckBox)ret.findViewById(R.id.selected));\n sel.setOnClickListener(spi);\n sel.setChecked(spi.selected);\n return ret;\n\n }\n\n}\n","target_code":"package de.onyxbits.listmyapps;\n\nimport java.util.List;\n\nimport android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ArrayAdapter;\nimport android.widget.CheckBox;\nimport android.widget.TextView;\n\npublic class AppAdapter extends ArrayAdapter {\n\n\tpublic AppAdapter(Context context, int textViewResourceId,\n\t\t\tList spi) {\n\t\tsuper(context, textViewResourceId, spi);\n\t}\n\t\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n View ret=convertView;\n if (ret==null) {\n \tLayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n \tret = inflater.inflate(R.layout.app_item,null);\n }\n SortablePackageInfo spi = getItem(position);\n \n ((TextView)ret.findViewById(R.id.appname)).setText(spi.displayName);\n ((TextView)ret.findViewById(R.id.apppackage)).setText(spi.packageName);\n CheckBox sel = ((CheckBox)ret.findViewById(R.id.selected));\n sel.setChecked(spi.selected);\n sel.setOnClickListener(spi);\n \n return ret;\n\n }\n\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the frame rate. Write the entire code and no other text.\n```java\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n SearchEngineManager.getInstance().init(this);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n```\n\n### Thought:\nThe onCreate() function performs necessary initializations such as loading certain preferences, and sets up SearchEngineManager instance. However, loading preferences depends on the Search Engine manager, because the default search engine preference uses the search engine manager; we therefore need to ensure that preferences aren't loaded until search engines are loaded, to avoid potential hangup of the application for a fresh install. The following optimized code first initializes the search engine manager and then loads preferences.\n\n### Response:\n ```java\n \/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n SearchEngineManager.getInstance().init(this);\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the frame rate. Write the entire code and no other text:\npackage de.onyxbits.listmyapps;\n\nimport java.util.List;\n\nimport android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ArrayAdapter;\nimport android.widget.CheckBox;\nimport android.widget.TextView;\n\npublic class AppAdapter extends ArrayAdapter {\n\n\tpublic AppAdapter(Context context, int textViewResourceId,\n\t\t\tList spi) {\n\t\tsuper(context, textViewResourceId, spi);\n\t}\n\t\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n View ret;\n SortablePackageInfo spi = getItem(position);\n \n LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n ret = inflater.inflate(R.layout.app_item,null);\n ((TextView)ret.findViewById(R.id.appname)).setText(spi.displayName);\n ((TextView)ret.findViewById(R.id.apppackage)).setText(spi.packageName);\n CheckBox sel = ((CheckBox)ret.findViewById(R.id.selected));\n sel.setOnClickListener(spi);\n sel.setChecked(spi.selected);\n return ret;\n\n }\n\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the frame rate. Write the entire code and no other text.\n```java\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n SearchEngineManager.getInstance().init(this);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n```\n### Response:\n ```java\n \/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n SearchEngineManager.getInstance().init(this);\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the frame rate. Write the entire code and no other text:\npackage de.onyxbits.listmyapps;\n\nimport java.util.List;\n\nimport android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ArrayAdapter;\nimport android.widget.CheckBox;\nimport android.widget.TextView;\n\npublic class AppAdapter extends ArrayAdapter {\n\n\tpublic AppAdapter(Context context, int textViewResourceId,\n\t\t\tList spi) {\n\t\tsuper(context, textViewResourceId, spi);\n\t}\n\t\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n View ret;\n SortablePackageInfo spi = getItem(position);\n \n LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n ret = inflater.inflate(R.layout.app_item,null);\n ((TextView)ret.findViewById(R.id.appname)).setText(spi.displayName);\n ((TextView)ret.findViewById(R.id.apppackage)).setText(spi.packageName);\n CheckBox sel = ((CheckBox)ret.findViewById(R.id.selected));\n sel.setOnClickListener(spi);\n sel.setChecked(spi.selected);\n return ret;\n\n }\n\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the frame rate. Write the entire code and no other text:\npackage de.onyxbits.listmyapps;\n\nimport java.util.List;\n\nimport android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ArrayAdapter;\nimport android.widget.CheckBox;\nimport android.widget.TextView;\n\npublic class AppAdapter extends ArrayAdapter {\n\n\tpublic AppAdapter(Context context, int textViewResourceId,\n\t\t\tList spi) {\n\t\tsuper(context, textViewResourceId, spi);\n\t}\n\t\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n View ret;\n SortablePackageInfo spi = getItem(position);\n \n LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n ret = inflater.inflate(R.layout.app_item,null);\n ((TextView)ret.findViewById(R.id.appname)).setText(spi.displayName);\n ((TextView)ret.findViewById(R.id.apppackage)).setText(spi.packageName);\n CheckBox sel = ((CheckBox)ret.findViewById(R.id.selected));\n sel.setOnClickListener(spi);\n sel.setChecked(spi.selected);\n return ret;\n\n }\n\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the code to make scrolling faster and improve user experience of the android application. Write the entire code and no other text in the response.\n\n### Concepts:\n[+] recycle convertView object\n\n### Given program:\n```java\npackage de.onyxbits.listmyapps;\n\nimport java.util.List;\n\nimport android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ArrayAdapter;\nimport android.widget.CheckBox;\nimport android.widget.TextView;\n\npublic class AppAdapter extends ArrayAdapter {\n\n\tpublic AppAdapter(Context context, int textViewResourceId,\n\t\t\tList spi) {\n\t\tsuper(context, textViewResourceId, spi);\n\t}\n\t\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n View ret;\n SortablePackageInfo spi = getItem(position);\n \n LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n ret = inflater.inflate(R.layout.app_item,null);\n ((TextView)ret.findViewById(R.id.appname)).setText(spi.displayName);\n ((TextView)ret.findViewById(R.id.apppackage)).setText(spi.packageName);\n CheckBox sel = ((CheckBox)ret.findViewById(R.id.selected));\n sel.setOnClickListener(spi);\n sel.setChecked(spi.selected);\n return ret;\n\n }\n\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower frame rate.\n\nCode-A:\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n \/\/ Loading preferences depends on the Search Engine manager, because the default search\n \/\/ engine pref uses the search engine manager - we therefore need to ensure\n \/\/ that prefs aren't loaded until search engines are loaded.\n SearchEngineManager.getInstance().init(this);\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n\n\nCode-B:\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n SearchEngineManager.getInstance().init(this);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower frame rate utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower frame rate.\n\nCode-A:\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n SearchEngineManager.getInstance().init(this);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n\n\nCode-B:\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n \/\/ Loading preferences depends on the Search Engine manager, because the default search\n \/\/ engine pref uses the search engine manager - we therefore need to ensure\n \/\/ that prefs aren't loaded until search engines are loaded.\n SearchEngineManager.getInstance().init(this);\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower frame rate utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/aaronjwood\/PortAuthority\/commit\/251e9ea3d07dfe09c911041ee841d78acbfa5eba","commit_message":"'\\\\\"Use a socket connection when scanning for hosts instead of isReachable. Set performance options to prefer fast connection. Enable TCP_NODELAY\\\\n\\\\\"'","source_code":"package com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetAddress;\n\npublic class ScanHostsRunnable implements Runnable {\n\n private static final String TAG = \"ScanHostsRunnable\";\n\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for(int i = this.start; i <= this.stop; i++) {\n String newIp = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n try {\n InetAddress address = InetAddress.getByName(newIp);\n address.isReachable(100);\n }\n catch(IOException ignored) {\n }\n finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}","target_code":"package com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\n\npublic class ScanHostsRunnable implements Runnable {\n\n private static final String TAG = \"ScanHostsRunnable\";\n\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for(int i = this.start; i <= this.stop; i++) {\n String newIp = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n try {\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(newIp, 7), 100);\n }\n catch(IOException ignored) {\n }\n finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetAddress;\n\npublic class ScanHostsRunnable implements Runnable {\n\n private static final String TAG = \"ScanHostsRunnable\";\n\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for(int i = this.start; i <= this.stop; i++) {\n String newIp = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n try {\n InetAddress address = InetAddress.getByName(newIp);\n address.isReachable(100);\n }\n catch(IOException ignored) {\n }\n finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetAddress;\n\npublic class ScanHostsRunnable implements Runnable {\n\n private static final String TAG = \"ScanHostsRunnable\";\n\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for(int i = this.start; i <= this.stop; i++) {\n String newIp = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n try {\n InetAddress address = InetAddress.getByName(newIp);\n address.isReachable(100);\n }\n catch(IOException ignored) {\n }\n finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetAddress;\n\npublic class ScanHostsRunnable implements Runnable {\n\n private static final String TAG = \"ScanHostsRunnable\";\n\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for(int i = this.start; i <= this.stop; i++) {\n String newIp = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n try {\n InetAddress address = InetAddress.getByName(newIp);\n address.isReachable(100);\n }\n catch(IOException ignored) {\n }\n finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the code using a socket connection when scanning for hosts to improve execution time. Write the entire code and no other text in the response.\n\n### Concepts:\n[-] isReachable\n[-] java.net.InetAddress\n[+] java.net.InetSocketAddress\n[+] java.net.Socket\n[+] setPerformancePreferences\n[+] TCP_NODELAY\n\n### Given program:\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetAddress;\n\npublic class ScanHostsRunnable implements Runnable {\n\n private static final String TAG = \"ScanHostsRunnable\";\n\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for(int i = this.start; i <= this.stop; i++) {\n String newIp = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n try {\n InetAddress address = InetAddress.getByName(newIp);\n address.isReachable(100);\n }\n catch(IOException ignored) {\n }\n finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower frame rate.\n\nCode-A:\npackage de.onyxbits.listmyapps;\n\nimport java.util.List;\n\nimport android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ArrayAdapter;\nimport android.widget.CheckBox;\nimport android.widget.TextView;\n\npublic class AppAdapter extends ArrayAdapter {\n\n\tpublic AppAdapter(Context context, int textViewResourceId,\n\t\t\tList spi) {\n\t\tsuper(context, textViewResourceId, spi);\n\t}\n\t\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n View ret=convertView;\n if (ret==null) {\n \tLayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n \tret = inflater.inflate(R.layout.app_item,null);\n }\n SortablePackageInfo spi = getItem(position);\n \n ((TextView)ret.findViewById(R.id.appname)).setText(spi.displayName);\n ((TextView)ret.findViewById(R.id.apppackage)).setText(spi.packageName);\n CheckBox sel = ((CheckBox)ret.findViewById(R.id.selected));\n sel.setChecked(spi.selected);\n sel.setOnClickListener(spi);\n \n return ret;\n\n }\n\n}\n\n\nCode-B:\npackage de.onyxbits.listmyapps;\n\nimport java.util.List;\n\nimport android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ArrayAdapter;\nimport android.widget.CheckBox;\nimport android.widget.TextView;\n\npublic class AppAdapter extends ArrayAdapter {\n\n\tpublic AppAdapter(Context context, int textViewResourceId,\n\t\t\tList spi) {\n\t\tsuper(context, textViewResourceId, spi);\n\t}\n\t\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n View ret;\n SortablePackageInfo spi = getItem(position);\n \n LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n ret = inflater.inflate(R.layout.app_item,null);\n ((TextView)ret.findViewById(R.id.appname)).setText(spi.displayName);\n ((TextView)ret.findViewById(R.id.apppackage)).setText(spi.packageName);\n CheckBox sel = ((CheckBox)ret.findViewById(R.id.selected));\n sel.setOnClickListener(spi);\n sel.setChecked(spi.selected);\n return ret;\n\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower frame rate utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower frame rate.\n\nCode-A:\npackage de.onyxbits.listmyapps;\n\nimport java.util.List;\n\nimport android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ArrayAdapter;\nimport android.widget.CheckBox;\nimport android.widget.TextView;\n\npublic class AppAdapter extends ArrayAdapter {\n\n\tpublic AppAdapter(Context context, int textViewResourceId,\n\t\t\tList spi) {\n\t\tsuper(context, textViewResourceId, spi);\n\t}\n\t\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n View ret;\n SortablePackageInfo spi = getItem(position);\n \n LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n ret = inflater.inflate(R.layout.app_item,null);\n ((TextView)ret.findViewById(R.id.appname)).setText(spi.displayName);\n ((TextView)ret.findViewById(R.id.apppackage)).setText(spi.packageName);\n CheckBox sel = ((CheckBox)ret.findViewById(R.id.selected));\n sel.setOnClickListener(spi);\n sel.setChecked(spi.selected);\n return ret;\n\n }\n\n}\n\n\nCode-B:\npackage de.onyxbits.listmyapps;\n\nimport java.util.List;\n\nimport android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ArrayAdapter;\nimport android.widget.CheckBox;\nimport android.widget.TextView;\n\npublic class AppAdapter extends ArrayAdapter {\n\n\tpublic AppAdapter(Context context, int textViewResourceId,\n\t\t\tList spi) {\n\t\tsuper(context, textViewResourceId, spi);\n\t}\n\t\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n View ret=convertView;\n if (ret==null) {\n \tLayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n \tret = inflater.inflate(R.layout.app_item,null);\n }\n SortablePackageInfo spi = getItem(position);\n \n ((TextView)ret.findViewById(R.id.appname)).setText(spi.displayName);\n ((TextView)ret.findViewById(R.id.apppackage)).setText(spi.packageName);\n CheckBox sel = ((CheckBox)ret.findViewById(R.id.selected));\n sel.setChecked(spi.selected);\n sel.setOnClickListener(spi);\n \n return ret;\n\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower frame rate utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/aaronjwood\/PortAuthority\/commit\/e37a1a522a15773710f051d9fff5c0ce68ade5cb","commit_message":"'\\\\\"Java can often do more optimizations to things outside of try blocks. Take more advantage of the JIT\\\\n\\\\\"'","source_code":"package com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\n\npublic class ScanHostsRunnable implements Runnable {\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for (int i = this.start; i <= this.stop; i++) {\n String ip = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n try {\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(ip, 7), 250);\n socket.close();\n } catch (IOException ignored) {\n } finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}","target_code":"package com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\n\npublic class ScanHostsRunnable implements Runnable {\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for (int i = this.start; i <= this.stop; i++) {\n String ip = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n\n try {\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(ip, 7), 250);\n socket.close();\n } catch (IOException ignored) {\n } finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\n\npublic class ScanHostsRunnable implements Runnable {\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for (int i = this.start; i <= this.stop; i++) {\n String ip = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n try {\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(ip, 7), 250);\n socket.close();\n } catch (IOException ignored) {\n } finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\n\npublic class ScanHostsRunnable implements Runnable {\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for (int i = this.start; i <= this.stop; i++) {\n String ip = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n try {\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(ip, 7), 250);\n socket.close();\n } catch (IOException ignored) {\n } finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\n\npublic class ScanHostsRunnable implements Runnable {\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for (int i = this.start; i <= this.stop; i++) {\n String ip = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n try {\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(ip, 7), 250);\n socket.close();\n } catch (IOException ignored) {\n } finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the run function to improve execution time. Write the entire code and no other text in the response.\n\n### Concepts:\n [+] statements inside vs outside try...finally block\n[hint] moving statements outside try...finally blocks enables optimizations\n\n### Given program:\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\n\npublic class ScanHostsRunnable implements Runnable {\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for (int i = this.start; i <= this.stop; i++) {\n String ip = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n try {\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(ip, 7), 250);\n socket.close();\n } catch (IOException ignored) {\n } finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/vaginessa\/TestBrowser-Lightning\/commit\/d68ab94bbb4ac5a4ccdca5771b5c12603773b125","commit_message":"'\\\\\"Optimize LicenseActivity\\\\n\\\\\"'","source_code":"\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.LinearLayout;\n\n\/*\n *NOTE: This activity must not be removed in order to comply with the Mozilla Public License v. 2.0 \n *under which this code is licensed. Unless you plan on providing other attribution in the app to \n *the original source in another visible way, it is advised against the removal of this Activity.\n *\/\npublic class LicenseActivity extends Activity {\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\tsetContentView(R.layout.license_activity);\n\t\tgetActionBar().setHomeButtonEnabled(true);\n\t\tgetActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tLinearLayout thunder = (LinearLayout) findViewById(R.id.browserLicense);\n\t\tLinearLayout aosp = (LinearLayout) findViewById(R.id.licenseAOSP);\n\t\tLinearLayout hosts = (LinearLayout) findViewById(R.id.licenseHosts);\n\t\tthunder.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/www.mozilla.org\/MPL\/2.0\/\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\t\taosp.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/www.apache.org\/licenses\/LICENSE-2.0\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\t\t\n\t\thosts.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/hosts-file.net\/\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tfinish();\n\t\treturn super.onOptionsItemSelected(item);\n\t}\n\n}\n","target_code":"\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.view.MenuItem;\nimport android.view.View;\n\n\/*\n *NOTE: This activity must not be removed in order to comply with the Mozilla Public License v. 2.0 \n *under which this code is licensed. Unless you plan on providing other attribution in the app to \n *the original source in another visible way, it is advised against the removal of this Activity.\n *\/\npublic class LicenseActivity extends Activity implements View.OnClickListener {\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\tsetContentView(R.layout.license_activity);\n\t\tgetActionBar().setHomeButtonEnabled(true);\n\t\tgetActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tfindViewById(R.id.browserLicense).setOnClickListener(this);\n\t\tfindViewById(R.id.licenseAOSP).setOnClickListener(this);\n\t\tfindViewById(R.id.licenseHosts).setOnClickListener(this);\n\t}\n\t\n\t@Override\n public void onClick(View v) {\n\t switch (v.getId()) {\n\t case R.id.browserLicense:\n actionView(\"http:\/\/www.mozilla.org\/MPL\/2.0\/\");\n break;\n\t case R.id.licenseAOSP:\n\t actionView(\"http:\/\/www.apache.org\/licenses\/LICENSE-2.0\");\n break;\n\t case R.id.licenseHosts:\n\t actionView(\"http:\/\/hosts-file.net\/\");\n break;\n }\n }\n\t\n\tprivate void actionView(String url) {\n\t startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));\n finish();\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tfinish();\n\t\treturn super.onOptionsItemSelected(item);\n\t}\n\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.LinearLayout;\n\n\/*\n *NOTE: This activity must not be removed in order to comply with the Mozilla Public License v. 2.0 \n *under which this code is licensed. Unless you plan on providing other attribution in the app to \n *the original source in another visible way, it is advised against the removal of this Activity.\n *\/\npublic class LicenseActivity extends Activity {\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\tsetContentView(R.layout.license_activity);\n\t\tgetActionBar().setHomeButtonEnabled(true);\n\t\tgetActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tLinearLayout thunder = (LinearLayout) findViewById(R.id.browserLicense);\n\t\tLinearLayout aosp = (LinearLayout) findViewById(R.id.licenseAOSP);\n\t\tLinearLayout hosts = (LinearLayout) findViewById(R.id.licenseHosts);\n\t\tthunder.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/www.mozilla.org\/MPL\/2.0\/\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\t\taosp.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/www.apache.org\/licenses\/LICENSE-2.0\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\t\t\n\t\thosts.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/hosts-file.net\/\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tfinish();\n\t\treturn super.onOptionsItemSelected(item);\n\t}\n\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.LinearLayout;\n\n\/*\n *NOTE: This activity must not be removed in order to comply with the Mozilla Public License v. 2.0 \n *under which this code is licensed. Unless you plan on providing other attribution in the app to \n *the original source in another visible way, it is advised against the removal of this Activity.\n *\/\npublic class LicenseActivity extends Activity {\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\tsetContentView(R.layout.license_activity);\n\t\tgetActionBar().setHomeButtonEnabled(true);\n\t\tgetActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tLinearLayout thunder = (LinearLayout) findViewById(R.id.browserLicense);\n\t\tLinearLayout aosp = (LinearLayout) findViewById(R.id.licenseAOSP);\n\t\tLinearLayout hosts = (LinearLayout) findViewById(R.id.licenseHosts);\n\t\tthunder.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/www.mozilla.org\/MPL\/2.0\/\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\t\taosp.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/www.apache.org\/licenses\/LICENSE-2.0\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\t\t\n\t\thosts.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/hosts-file.net\/\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tfinish();\n\t\treturn super.onOptionsItemSelected(item);\n\t}\n\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.LinearLayout;\n\n\/*\n *NOTE: This activity must not be removed in order to comply with the Mozilla Public License v. 2.0 \n *under which this code is licensed. Unless you plan on providing other attribution in the app to \n *the original source in another visible way, it is advised against the removal of this Activity.\n *\/\npublic class LicenseActivity extends Activity {\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\tsetContentView(R.layout.license_activity);\n\t\tgetActionBar().setHomeButtonEnabled(true);\n\t\tgetActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tLinearLayout thunder = (LinearLayout) findViewById(R.id.browserLicense);\n\t\tLinearLayout aosp = (LinearLayout) findViewById(R.id.licenseAOSP);\n\t\tLinearLayout hosts = (LinearLayout) findViewById(R.id.licenseHosts);\n\t\tthunder.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/www.mozilla.org\/MPL\/2.0\/\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\t\taosp.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/www.apache.org\/licenses\/LICENSE-2.0\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\t\t\n\t\thosts.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/hosts-file.net\/\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tfinish();\n\t\treturn super.onOptionsItemSelected(item);\n\t}\n\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite LicenseActivity class to improve execution time. Write the entire code and no other text in the response.\n\n### Concepts:\n[implement] View.OnClickListener\n[override] onClick and actionView functions\n[-] android.view.View.OnClickListener\n[-] android.widget.LinearLayout\n\n### Given program:\n```java\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.LinearLayout;\n\n\/*\n *NOTE: This activity must not be removed in order to comply with the Mozilla Public License v. 2.0 \n *under which this code is licensed. Unless you plan on providing other attribution in the app to \n *the original source in another visible way, it is advised against the removal of this Activity.\n *\/\npublic class LicenseActivity extends Activity {\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\tsetContentView(R.layout.license_activity);\n\t\tgetActionBar().setHomeButtonEnabled(true);\n\t\tgetActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tLinearLayout thunder = (LinearLayout) findViewById(R.id.browserLicense);\n\t\tLinearLayout aosp = (LinearLayout) findViewById(R.id.licenseAOSP);\n\t\tLinearLayout hosts = (LinearLayout) findViewById(R.id.licenseHosts);\n\t\tthunder.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/www.mozilla.org\/MPL\/2.0\/\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\t\taosp.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/www.apache.org\/licenses\/LICENSE-2.0\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\t\t\n\t\thosts.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/hosts-file.net\/\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tfinish();\n\t\treturn super.onOptionsItemSelected(item);\n\t}\n\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\n\npublic class ScanHostsRunnable implements Runnable {\n\n private static final String TAG = \"ScanHostsRunnable\";\n\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for(int i = this.start; i <= this.stop; i++) {\n String newIp = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n try {\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(newIp, 7), 100);\n }\n catch(IOException ignored) {\n }\n finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}\n\nCode-B:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetAddress;\n\npublic class ScanHostsRunnable implements Runnable {\n\n private static final String TAG = \"ScanHostsRunnable\";\n\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for(int i = this.start; i <= this.stop; i++) {\n String newIp = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n try {\n InetAddress address = InetAddress.getByName(newIp);\n address.isReachable(100);\n }\n catch(IOException ignored) {\n }\n finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetAddress;\n\npublic class ScanHostsRunnable implements Runnable {\n\n private static final String TAG = \"ScanHostsRunnable\";\n\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for(int i = this.start; i <= this.stop; i++) {\n String newIp = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n try {\n InetAddress address = InetAddress.getByName(newIp);\n address.isReachable(100);\n }\n catch(IOException ignored) {\n }\n finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}\n\nCode-B:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\n\npublic class ScanHostsRunnable implements Runnable {\n\n private static final String TAG = \"ScanHostsRunnable\";\n\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for(int i = this.start; i <= this.stop; i++) {\n String newIp = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n try {\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(newIp, 7), 100);\n }\n catch(IOException ignored) {\n }\n finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/aaronjwood\/PortAuthority\/commit\/0eb3cc570e3898cf681d12cf399ab040aea16e8f","commit_message":"'\\\\\"For larger scans a fixed thread pool provides better performance\\\\n\\\\\"'","source_code":"package com.aaronjwood.portauthority.async;\n\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n\n private static final String TAG = \"ScanPortsAsyncTask\";\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = delegate;\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n * @return\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n final int NUM_THREADS = 500;\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n ExecutorService executor = Executors.newCachedThreadPool();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for(int i = 0; i < NUM_THREADS; i++) {\n if(previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(10, TimeUnit.MINUTES);\n }\n catch(InterruptedException ignored) {\n }\n\n this.delegate.processFinish(true);\n\n return null;\n }\n}\n","target_code":"package com.aaronjwood.portauthority.async;\n\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n\n private static final String TAG = \"ScanPortsAsyncTask\";\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = delegate;\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n * @return\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n final int NUM_THREADS = 500;\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for(int i = 0; i < NUM_THREADS; i++) {\n if(previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(10, TimeUnit.MINUTES);\n }\n catch(InterruptedException ignored) {\n }\n\n this.delegate.processFinish(true);\n\n return null;\n }\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.async;\n\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n\n private static final String TAG = \"ScanPortsAsyncTask\";\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = delegate;\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n * @return\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n final int NUM_THREADS = 500;\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n ExecutorService executor = Executors.newCachedThreadPool();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for(int i = 0; i < NUM_THREADS; i++) {\n if(previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(10, TimeUnit.MINUTES);\n }\n catch(InterruptedException ignored) {\n }\n\n this.delegate.processFinish(true);\n\n return null;\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.async;\n\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n\n private static final String TAG = \"ScanPortsAsyncTask\";\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = delegate;\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n * @return\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n final int NUM_THREADS = 500;\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n ExecutorService executor = Executors.newCachedThreadPool();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for(int i = 0; i < NUM_THREADS; i++) {\n if(previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(10, TimeUnit.MINUTES);\n }\n catch(InterruptedException ignored) {\n }\n\n this.delegate.processFinish(true);\n\n return null;\n }\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.async;\n\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n\n private static final String TAG = \"ScanPortsAsyncTask\";\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = delegate;\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n * @return\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n final int NUM_THREADS = 500;\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n ExecutorService executor = Executors.newCachedThreadPool();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for(int i = 0; i < NUM_THREADS; i++) {\n if(previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(10, TimeUnit.MINUTES);\n }\n catch(InterruptedException ignored) {\n }\n\n this.delegate.processFinish(true);\n\n return null;\n }\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the code to improve execution time for larger scans. Write the entire code and no other text in the response.\n\n### Concepts:\n[+] Fixed size thread pool\n[in] doInBackground function\n\n### Given program:\n```java\npackage com.aaronjwood.portauthority.async;\n\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n\n private static final String TAG = \"ScanPortsAsyncTask\";\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = delegate;\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n * @return\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n final int NUM_THREADS = 500;\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n ExecutorService executor = Executors.newCachedThreadPool();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for(int i = 0; i < NUM_THREADS; i++) {\n if(previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(10, TimeUnit.MINUTES);\n }\n catch(InterruptedException ignored) {\n }\n\n this.delegate.processFinish(true);\n\n return null;\n }\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\n\npublic class ScanHostsRunnable implements Runnable {\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for (int i = this.start; i <= this.stop; i++) {\n String ip = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n\n try {\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(ip, 7), 250);\n socket.close();\n } catch (IOException ignored) {\n } finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}\n\nCode-B:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\n\npublic class ScanHostsRunnable implements Runnable {\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for (int i = this.start; i <= this.stop; i++) {\n String ip = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n try {\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(ip, 7), 250);\n socket.close();\n } catch (IOException ignored) {\n } finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\n\npublic class ScanHostsRunnable implements Runnable {\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for (int i = this.start; i <= this.stop; i++) {\n String ip = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n try {\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(ip, 7), 250);\n socket.close();\n } catch (IOException ignored) {\n } finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}\n\nCode-B:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\n\npublic class ScanHostsRunnable implements Runnable {\n private String[] ipParts;\n private int start;\n private int stop;\n private MainAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to scan for hosts\n *\n * @param ipParts IP address split up by the segments\n * @param start Host to start scanning at\n * @param stop Host to stop scanning at\n * @param delegate Called when host discovery has finished\n *\/\n public ScanHostsRunnable(String[] ipParts, int start, int stop, MainAsyncResponse delegate) {\n this.ipParts = ipParts;\n this.start = start;\n this.stop = stop;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the host discovery\n *\/\n @Override\n public void run() {\n for (int i = this.start; i <= this.stop; i++) {\n String ip = this.ipParts[0] + \".\" + this.ipParts[1] + \".\" + this.ipParts[2] + \".\" + i;\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n\n try {\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(ip, 7), 250);\n socket.close();\n } catch (IOException ignored) {\n } finally {\n this.delegate.processFinish(1);\n }\n }\n }\n}\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/erikusaj\/fdroidTvClient\/commit\/e085e0392bfb5b476ab114382663a7ca7fd5ce4e","commit_message":"'\\\\\"PackageReceiver: Only fetch the one PackageInfo\\\\n\\\\nWe were fetching information on all installed packages and doing a linear\\\\nsearch. Which is silly and inefficient since we can directly fetch information\\\\non a single installed package by id.\\\\n\\\\\"'","source_code":"\/*\n * Copyright (C) 2014 Ciaran Gultnieks, ciaran@ciarang.com,\n * Peter Serwylo, peter@serwylo.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.receiver;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.AppProvider;\n\nabstract class PackageReceiver extends BroadcastReceiver {\n\n private static final String TAG = \"PackageReceiver\";\n\n protected abstract boolean toDiscard(Intent intent);\n\n protected abstract void handle(Context context, String appId);\n\n protected PackageInfo getPackageInfo(Context context, String appId) {\n for (PackageInfo info : context.getPackageManager().getInstalledPackages(0)) {\n if (info.packageName.equals(appId)) {\n return info;\n }\n }\n return null;\n }\n\n @Override\n public void onReceive(Context context, Intent intent) {\n Utils.debugLog(TAG, \"PackageReceiver received [action = '\" + intent.getAction() + \"', data = '\" + intent.getData() + \"']\");\n if (toDiscard(intent)) {\n return;\n }\n String appId = intent.getData().getSchemeSpecificPart();\n handle(context, appId);\n context.getContentResolver().notifyChange(AppProvider.getContentUri(appId), null);\n context.getContentResolver().notifyChange(ApkProvider.getAppUri(appId), null);\n }\n\n}\n","target_code":"\/*\n * Copyright (C) 2014 Ciaran Gultnieks, ciaran@ciarang.com,\n * Peter Serwylo, peter@serwylo.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.receiver;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.AppProvider;\n\nabstract class PackageReceiver extends BroadcastReceiver {\n\n private static final String TAG = \"PackageReceiver\";\n\n protected abstract boolean toDiscard(Intent intent);\n\n protected abstract void handle(Context context, String appId);\n\n protected PackageInfo getPackageInfo(Context context, String appId) {\n PackageInfo info = null;\n try {\n info = context.getPackageManager().getPackageInfo(appId, 0);\n } catch (PackageManager.NameNotFoundException e) {\n \/\/ ignore\n }\n return info;\n }\n\n @Override\n public void onReceive(Context context, Intent intent) {\n Utils.debugLog(TAG, \"PackageReceiver received [action = '\" + intent.getAction() + \"', data = '\" + intent.getData() + \"']\");\n if (toDiscard(intent)) {\n return;\n }\n String appId = intent.getData().getSchemeSpecificPart();\n handle(context, appId);\n context.getContentResolver().notifyChange(AppProvider.getContentUri(appId), null);\n context.getContentResolver().notifyChange(ApkProvider.getAppUri(appId), null);\n }\n\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright (C) 2014 Ciaran Gultnieks, ciaran@ciarang.com,\n * Peter Serwylo, peter@serwylo.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.receiver;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.AppProvider;\n\nabstract class PackageReceiver extends BroadcastReceiver {\n\n private static final String TAG = \"PackageReceiver\";\n\n protected abstract boolean toDiscard(Intent intent);\n\n protected abstract void handle(Context context, String appId);\n\n protected PackageInfo getPackageInfo(Context context, String appId) {\n for (PackageInfo info : context.getPackageManager().getInstalledPackages(0)) {\n if (info.packageName.equals(appId)) {\n return info;\n }\n }\n return null;\n }\n\n @Override\n public void onReceive(Context context, Intent intent) {\n Utils.debugLog(TAG, \"PackageReceiver received [action = '\" + intent.getAction() + \"', data = '\" + intent.getData() + \"']\");\n if (toDiscard(intent)) {\n return;\n }\n String appId = intent.getData().getSchemeSpecificPart();\n handle(context, appId);\n context.getContentResolver().notifyChange(AppProvider.getContentUri(appId), null);\n context.getContentResolver().notifyChange(ApkProvider.getAppUri(appId), null);\n }\n\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright (C) 2014 Ciaran Gultnieks, ciaran@ciarang.com,\n * Peter Serwylo, peter@serwylo.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.receiver;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.AppProvider;\n\nabstract class PackageReceiver extends BroadcastReceiver {\n\n private static final String TAG = \"PackageReceiver\";\n\n protected abstract boolean toDiscard(Intent intent);\n\n protected abstract void handle(Context context, String appId);\n\n protected PackageInfo getPackageInfo(Context context, String appId) {\n for (PackageInfo info : context.getPackageManager().getInstalledPackages(0)) {\n if (info.packageName.equals(appId)) {\n return info;\n }\n }\n return null;\n }\n\n @Override\n public void onReceive(Context context, Intent intent) {\n Utils.debugLog(TAG, \"PackageReceiver received [action = '\" + intent.getAction() + \"', data = '\" + intent.getData() + \"']\");\n if (toDiscard(intent)) {\n return;\n }\n String appId = intent.getData().getSchemeSpecificPart();\n handle(context, appId);\n context.getContentResolver().notifyChange(AppProvider.getContentUri(appId), null);\n context.getContentResolver().notifyChange(ApkProvider.getAppUri(appId), null);\n }\n\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright (C) 2014 Ciaran Gultnieks, ciaran@ciarang.com,\n * Peter Serwylo, peter@serwylo.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.receiver;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.AppProvider;\n\nabstract class PackageReceiver extends BroadcastReceiver {\n\n private static final String TAG = \"PackageReceiver\";\n\n protected abstract boolean toDiscard(Intent intent);\n\n protected abstract void handle(Context context, String appId);\n\n protected PackageInfo getPackageInfo(Context context, String appId) {\n for (PackageInfo info : context.getPackageManager().getInstalledPackages(0)) {\n if (info.packageName.equals(appId)) {\n return info;\n }\n }\n return null;\n }\n\n @Override\n public void onReceive(Context context, Intent intent) {\n Utils.debugLog(TAG, \"PackageReceiver received [action = '\" + intent.getAction() + \"', data = '\" + intent.getData() + \"']\");\n if (toDiscard(intent)) {\n return;\n }\n String appId = intent.getData().getSchemeSpecificPart();\n handle(context, appId);\n context.getContentResolver().notifyChange(AppProvider.getContentUri(appId), null);\n context.getContentResolver().notifyChange(ApkProvider.getAppUri(appId), null);\n }\n\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the code to improve execution time. Write the entire code and no other text in the response.\n\n### Concepts:\n[-] linear search\n[+] android.content.pm.PackageManager.getPackageInfo (string, int)\n\n### Given program:\n```java\n\/*\n * Copyright (C) 2014 Ciaran Gultnieks, ciaran@ciarang.com,\n * Peter Serwylo, peter@serwylo.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.receiver;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.AppProvider;\n\nabstract class PackageReceiver extends BroadcastReceiver {\n\n private static final String TAG = \"PackageReceiver\";\n\n protected abstract boolean toDiscard(Intent intent);\n\n protected abstract void handle(Context context, String appId);\n\n protected PackageInfo getPackageInfo(Context context, String appId) {\n for (PackageInfo info : context.getPackageManager().getInstalledPackages(0)) {\n if (info.packageName.equals(appId)) {\n return info;\n }\n }\n return null;\n }\n\n @Override\n public void onReceive(Context context, Intent intent) {\n Utils.debugLog(TAG, \"PackageReceiver received [action = '\" + intent.getAction() + \"', data = '\" + intent.getData() + \"']\");\n if (toDiscard(intent)) {\n return;\n }\n String appId = intent.getData().getSchemeSpecificPart();\n handle(context, appId);\n context.getContentResolver().notifyChange(AppProvider.getContentUri(appId), null);\n context.getContentResolver().notifyChange(ApkProvider.getAppUri(appId), null);\n }\n\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.view.MenuItem;\nimport android.view.View;\n\n\/*\n *NOTE: This activity must not be removed in order to comply with the Mozilla Public License v. 2.0 \n *under which this code is licensed. Unless you plan on providing other attribution in the app to \n *the original source in another visible way, it is advised against the removal of this Activity.\n *\/\npublic class LicenseActivity extends Activity implements View.OnClickListener {\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\tsetContentView(R.layout.license_activity);\n\t\tgetActionBar().setHomeButtonEnabled(true);\n\t\tgetActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tfindViewById(R.id.browserLicense).setOnClickListener(this);\n\t\tfindViewById(R.id.licenseAOSP).setOnClickListener(this);\n\t\tfindViewById(R.id.licenseHosts).setOnClickListener(this);\n\t}\n\t\n\t@Override\n public void onClick(View v) {\n\t switch (v.getId()) {\n\t case R.id.browserLicense:\n actionView(\"http:\/\/www.mozilla.org\/MPL\/2.0\/\");\n break;\n\t case R.id.licenseAOSP:\n\t actionView(\"http:\/\/www.apache.org\/licenses\/LICENSE-2.0\");\n break;\n\t case R.id.licenseHosts:\n\t actionView(\"http:\/\/hosts-file.net\/\");\n break;\n }\n }\n\t\n\tprivate void actionView(String url) {\n\t startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));\n finish();\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tfinish();\n\t\treturn super.onOptionsItemSelected(item);\n\t}\n\n}\n\n\nCode-B:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.LinearLayout;\n\n\/*\n *NOTE: This activity must not be removed in order to comply with the Mozilla Public License v. 2.0 \n *under which this code is licensed. Unless you plan on providing other attribution in the app to \n *the original source in another visible way, it is advised against the removal of this Activity.\n *\/\npublic class LicenseActivity extends Activity {\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\tsetContentView(R.layout.license_activity);\n\t\tgetActionBar().setHomeButtonEnabled(true);\n\t\tgetActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tLinearLayout thunder = (LinearLayout) findViewById(R.id.browserLicense);\n\t\tLinearLayout aosp = (LinearLayout) findViewById(R.id.licenseAOSP);\n\t\tLinearLayout hosts = (LinearLayout) findViewById(R.id.licenseHosts);\n\t\tthunder.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/www.mozilla.org\/MPL\/2.0\/\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\t\taosp.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/www.apache.org\/licenses\/LICENSE-2.0\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\t\t\n\t\thosts.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/hosts-file.net\/\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tfinish();\n\t\treturn super.onOptionsItemSelected(item);\n\t}\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.View.OnClickListener;\nimport android.widget.LinearLayout;\n\n\/*\n *NOTE: This activity must not be removed in order to comply with the Mozilla Public License v. 2.0 \n *under which this code is licensed. Unless you plan on providing other attribution in the app to \n *the original source in another visible way, it is advised against the removal of this Activity.\n *\/\npublic class LicenseActivity extends Activity {\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\tsetContentView(R.layout.license_activity);\n\t\tgetActionBar().setHomeButtonEnabled(true);\n\t\tgetActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tLinearLayout thunder = (LinearLayout) findViewById(R.id.browserLicense);\n\t\tLinearLayout aosp = (LinearLayout) findViewById(R.id.licenseAOSP);\n\t\tLinearLayout hosts = (LinearLayout) findViewById(R.id.licenseHosts);\n\t\tthunder.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/www.mozilla.org\/MPL\/2.0\/\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\t\taosp.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/www.apache.org\/licenses\/LICENSE-2.0\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\t\t\n\t\thosts.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tstartActivity(new Intent(Intent.ACTION_VIEW, Uri\n\t\t\t\t\t\t.parse(\"http:\/\/hosts-file.net\/\")));\n\t\t\t\tfinish();\n\t\t\t}\n\n\t\t});\n\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tfinish();\n\t\treturn super.onOptionsItemSelected(item);\n\t}\n\n}\n\n\nCode-B:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.view.MenuItem;\nimport android.view.View;\n\n\/*\n *NOTE: This activity must not be removed in order to comply with the Mozilla Public License v. 2.0 \n *under which this code is licensed. Unless you plan on providing other attribution in the app to \n *the original source in another visible way, it is advised against the removal of this Activity.\n *\/\npublic class LicenseActivity extends Activity implements View.OnClickListener {\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\tsetContentView(R.layout.license_activity);\n\t\tgetActionBar().setHomeButtonEnabled(true);\n\t\tgetActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tfindViewById(R.id.browserLicense).setOnClickListener(this);\n\t\tfindViewById(R.id.licenseAOSP).setOnClickListener(this);\n\t\tfindViewById(R.id.licenseHosts).setOnClickListener(this);\n\t}\n\t\n\t@Override\n public void onClick(View v) {\n\t switch (v.getId()) {\n\t case R.id.browserLicense:\n actionView(\"http:\/\/www.mozilla.org\/MPL\/2.0\/\");\n break;\n\t case R.id.licenseAOSP:\n\t actionView(\"http:\/\/www.apache.org\/licenses\/LICENSE-2.0\");\n break;\n\t case R.id.licenseHosts:\n\t actionView(\"http:\/\/hosts-file.net\/\");\n break;\n }\n }\n\t\n\tprivate void actionView(String url) {\n\t startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));\n finish();\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tfinish();\n\t\treturn super.onOptionsItemSelected(item);\n\t}\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/ThaiCao\/EasyWatermark\/commit\/b822502acf65173418081102a04c7faabb632379","commit_message":"'\\\\\":zap: :bug:\\\\n[Update]\\\\n- Optimize logo view performance.\\\\n[Fix]\\\\n- Fix the flash problem when the animation ends\\\\n\\\\\"'","source_code":"package me.rosuh.easywatermark.widget\n\nimport android.animation.ObjectAnimator\nimport android.annotation.SuppressLint\nimport android.content.Context\nimport android.graphics.*\nimport android.util.AttributeSet\nimport androidx.appcompat.widget.AppCompatImageView\nimport androidx.core.graphics.drawable.toBitmap\nimport androidx.interpolator.view.animation.FastOutLinearInInterpolator\n\n\nclass ColoredImageVIew : AppCompatImageView {\n constructor(context: Context) : super(context)\n constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)\n constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(\n context,\n attrs,\n defStyleAttr\n )\n\n private val paint by lazy { Paint() }\n\n private val colorList = arrayOf(\n Color.parseColor(\"#FFA51F\"),\n Color.parseColor(\"#FFD703\"),\n Color.parseColor(\"#C0FF39\"),\n Color.parseColor(\"#00FFE0\")\n ).toIntArray()\n\n private val posList = arrayOf(0f, 0.5178f, 0.7654f, 1f).toFloatArray()\n\n private val colorAnimator by lazy {\n ObjectAnimator.ofFloat(1f, 0f)\n .apply {\n addUpdateListener {\n val pos = (it.animatedValue as Float)\n val shader = LinearGradient(\n (1 - pos) * width.toFloat() * 2f,\n pos * height.toFloat(),\n 0f,\n height.toFloat(),\n colorList,\n posList,\n Shader.TileMode.CLAMP\n )\n paint.shader = shader\n postInvalidateOnAnimation()\n }\n duration = 1200\n interpolator = FastOutLinearInInterpolator()\n repeatCount = ObjectAnimator.INFINITE\n repeatMode = ObjectAnimator.REVERSE\n }\n }\n\n\n private var innerBitmap: Bitmap? = null\n\n @SuppressLint(\"DrawAllocation\")\n override fun onDraw(canvas: Canvas?) {\n if (innerBitmap == null) {\n super.onDraw(canvas)\n innerBitmap = drawable.toBitmap(width, height)\n }\n innerBitmap?.let {\n val sc = canvas?.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), null) ?: return\n canvas.drawBitmap(it, 0f, 0f, paint)\n paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)\n canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)\n paint.xfermode = null\n canvas.restoreToCount(sc)\n }\n }\n\n\n fun start() {\n colorAnimator.start()\n }\n\n fun stop() {\n colorAnimator.pause()\n }\n}","target_code":"package me.rosuh.easywatermark.widget\n\nimport android.animation.ObjectAnimator\nimport android.annotation.SuppressLint\nimport android.content.Context\nimport android.graphics.*\nimport android.util.AttributeSet\nimport androidx.appcompat.widget.AppCompatImageView\nimport androidx.core.graphics.drawable.toBitmap\n\n\nclass ColoredImageVIew : AppCompatImageView {\n constructor(context: Context) : super(context)\n constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)\n constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(\n context,\n attrs,\n defStyleAttr\n )\n\n private var sizeHasChanged: Boolean = true\n private val paint by lazy { Paint() }\n\n private val colorList = arrayOf(\n Color.parseColor(\"#FFA51F\"),\n Color.parseColor(\"#FFD703\"),\n Color.parseColor(\"#C0FF39\"),\n Color.parseColor(\"#00FFE0\")\n ).toIntArray()\n\n private val posList = arrayOf(0f, 0.5178f, 0.7654f, 1f).toFloatArray()\n\n private val xfermode by lazy { PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP) }\n\n private val colorAnimator by lazy {\n ObjectAnimator.ofFloat(1f, 0f)\n .apply {\n addUpdateListener {\n val pos = (it.animatedValue as Float)\n val shader = LinearGradient(\n (1 - pos) * width.toFloat() * 2f,\n pos * height.toFloat(),\n 0f,\n height.toFloat(),\n colorList,\n posList,\n Shader.TileMode.CLAMP\n )\n paint.shader = shader\n postInvalidateOnAnimation()\n }\n duration = 1200\n repeatCount = ObjectAnimator.INFINITE\n repeatMode = ObjectAnimator.REVERSE\n }\n }\n\n\n private var innerBitmap: Bitmap? = null\n\n override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {\n super.onSizeChanged(w, h, oldw, oldh)\n sizeHasChanged = w != oldh || h != oldh\n }\n\n @SuppressLint(\"DrawAllocation\")\n override fun onDraw(canvas: Canvas?) {\n if (innerBitmap == null || sizeHasChanged) {\n super.onDraw(canvas)\n innerBitmap = drawable.toBitmap(width, height)\n }\n innerBitmap?.let {\n val sc = canvas?.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), null) ?: return\n canvas.drawBitmap(it, 0f, 0f, paint)\n paint.xfermode = xfermode\n canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)\n paint.xfermode = null\n canvas.restoreToCount(sc)\n }\n }\n\n\n fun start() {\n colorAnimator.start()\n }\n\n fun stop() {\n colorAnimator.pause()\n }\n}","pl":"Kotlin","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given kotlin program to optimize and improve the execution time. Write the entire code and no other text:\npackage me.rosuh.easywatermark.widget\n\nimport android.animation.ObjectAnimator\nimport android.annotation.SuppressLint\nimport android.content.Context\nimport android.graphics.*\nimport android.util.AttributeSet\nimport androidx.appcompat.widget.AppCompatImageView\nimport androidx.core.graphics.drawable.toBitmap\nimport androidx.interpolator.view.animation.FastOutLinearInInterpolator\n\n\nclass ColoredImageVIew : AppCompatImageView {\n constructor(context: Context) : super(context)\n constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)\n constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(\n context,\n attrs,\n defStyleAttr\n )\n\n private val paint by lazy { Paint() }\n\n private val colorList = arrayOf(\n Color.parseColor(\"#FFA51F\"),\n Color.parseColor(\"#FFD703\"),\n Color.parseColor(\"#C0FF39\"),\n Color.parseColor(\"#00FFE0\")\n ).toIntArray()\n\n private val posList = arrayOf(0f, 0.5178f, 0.7654f, 1f).toFloatArray()\n\n private val colorAnimator by lazy {\n ObjectAnimator.ofFloat(1f, 0f)\n .apply {\n addUpdateListener {\n val pos = (it.animatedValue as Float)\n val shader = LinearGradient(\n (1 - pos) * width.toFloat() * 2f,\n pos * height.toFloat(),\n 0f,\n height.toFloat(),\n colorList,\n posList,\n Shader.TileMode.CLAMP\n )\n paint.shader = shader\n postInvalidateOnAnimation()\n }\n duration = 1200\n interpolator = FastOutLinearInInterpolator()\n repeatCount = ObjectAnimator.INFINITE\n repeatMode = ObjectAnimator.REVERSE\n }\n }\n\n\n private var innerBitmap: Bitmap? = null\n\n @SuppressLint(\"DrawAllocation\")\n override fun onDraw(canvas: Canvas?) {\n if (innerBitmap == null) {\n super.onDraw(canvas)\n innerBitmap = drawable.toBitmap(width, height)\n }\n innerBitmap?.let {\n val sc = canvas?.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), null) ?: return\n canvas.drawBitmap(it, 0f, 0f, paint)\n paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)\n canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)\n paint.xfermode = null\n canvas.restoreToCount(sc)\n }\n }\n\n\n fun start() {\n colorAnimator.start()\n }\n\n fun stop() {\n colorAnimator.pause()\n }\n}\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given kotlin program to optimize and improve the execution time. Write the entire code and no other text:\npackage me.rosuh.easywatermark.widget\n\nimport android.animation.ObjectAnimator\nimport android.annotation.SuppressLint\nimport android.content.Context\nimport android.graphics.*\nimport android.util.AttributeSet\nimport androidx.appcompat.widget.AppCompatImageView\nimport androidx.core.graphics.drawable.toBitmap\nimport androidx.interpolator.view.animation.FastOutLinearInInterpolator\n\n\nclass ColoredImageVIew : AppCompatImageView {\n constructor(context: Context) : super(context)\n constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)\n constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(\n context,\n attrs,\n defStyleAttr\n )\n\n private val paint by lazy { Paint() }\n\n private val colorList = arrayOf(\n Color.parseColor(\"#FFA51F\"),\n Color.parseColor(\"#FFD703\"),\n Color.parseColor(\"#C0FF39\"),\n Color.parseColor(\"#00FFE0\")\n ).toIntArray()\n\n private val posList = arrayOf(0f, 0.5178f, 0.7654f, 1f).toFloatArray()\n\n private val colorAnimator by lazy {\n ObjectAnimator.ofFloat(1f, 0f)\n .apply {\n addUpdateListener {\n val pos = (it.animatedValue as Float)\n val shader = LinearGradient(\n (1 - pos) * width.toFloat() * 2f,\n pos * height.toFloat(),\n 0f,\n height.toFloat(),\n colorList,\n posList,\n Shader.TileMode.CLAMP\n )\n paint.shader = shader\n postInvalidateOnAnimation()\n }\n duration = 1200\n interpolator = FastOutLinearInInterpolator()\n repeatCount = ObjectAnimator.INFINITE\n repeatMode = ObjectAnimator.REVERSE\n }\n }\n\n\n private var innerBitmap: Bitmap? = null\n\n @SuppressLint(\"DrawAllocation\")\n override fun onDraw(canvas: Canvas?) {\n if (innerBitmap == null) {\n super.onDraw(canvas)\n innerBitmap = drawable.toBitmap(width, height)\n }\n innerBitmap?.let {\n val sc = canvas?.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), null) ?: return\n canvas.drawBitmap(it, 0f, 0f, paint)\n paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)\n canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)\n paint.xfermode = null\n canvas.restoreToCount(sc)\n }\n }\n\n\n fun start() {\n colorAnimator.start()\n }\n\n fun stop() {\n colorAnimator.pause()\n }\n}\n\n### Response:\n```kotlin","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given kotlin program to optimize and improve the execution time. Write the entire code and no other text:\npackage me.rosuh.easywatermark.widget\n\nimport android.animation.ObjectAnimator\nimport android.annotation.SuppressLint\nimport android.content.Context\nimport android.graphics.*\nimport android.util.AttributeSet\nimport androidx.appcompat.widget.AppCompatImageView\nimport androidx.core.graphics.drawable.toBitmap\nimport androidx.interpolator.view.animation.FastOutLinearInInterpolator\n\n\nclass ColoredImageVIew : AppCompatImageView {\n constructor(context: Context) : super(context)\n constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)\n constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(\n context,\n attrs,\n defStyleAttr\n )\n\n private val paint by lazy { Paint() }\n\n private val colorList = arrayOf(\n Color.parseColor(\"#FFA51F\"),\n Color.parseColor(\"#FFD703\"),\n Color.parseColor(\"#C0FF39\"),\n Color.parseColor(\"#00FFE0\")\n ).toIntArray()\n\n private val posList = arrayOf(0f, 0.5178f, 0.7654f, 1f).toFloatArray()\n\n private val colorAnimator by lazy {\n ObjectAnimator.ofFloat(1f, 0f)\n .apply {\n addUpdateListener {\n val pos = (it.animatedValue as Float)\n val shader = LinearGradient(\n (1 - pos) * width.toFloat() * 2f,\n pos * height.toFloat(),\n 0f,\n height.toFloat(),\n colorList,\n posList,\n Shader.TileMode.CLAMP\n )\n paint.shader = shader\n postInvalidateOnAnimation()\n }\n duration = 1200\n interpolator = FastOutLinearInInterpolator()\n repeatCount = ObjectAnimator.INFINITE\n repeatMode = ObjectAnimator.REVERSE\n }\n }\n\n\n private var innerBitmap: Bitmap? = null\n\n @SuppressLint(\"DrawAllocation\")\n override fun onDraw(canvas: Canvas?) {\n if (innerBitmap == null) {\n super.onDraw(canvas)\n innerBitmap = drawable.toBitmap(width, height)\n }\n innerBitmap?.let {\n val sc = canvas?.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), null) ?: return\n canvas.drawBitmap(it, 0f, 0f, paint)\n paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)\n canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)\n paint.xfermode = null\n canvas.restoreToCount(sc)\n }\n }\n\n\n fun start() {\n colorAnimator.start()\n }\n\n fun stop() {\n colorAnimator.pause()\n }\n}\n\n### Response:\n```kotlin","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the code to optimize logo view performance and user experience of the android application. Write the entire code and no other text in the response.\n\n### Concepts:\n[-] androidx.interpolator.view.animation.FastOutLinearInInterpolator\n[override] onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int)\n\n### Given program:\n```kotlin\npackage me.rosuh.easywatermark.widget\n\nimport android.animation.ObjectAnimator\nimport android.annotation.SuppressLint\nimport android.content.Context\nimport android.graphics.*\nimport android.util.AttributeSet\nimport androidx.appcompat.widget.AppCompatImageView\nimport androidx.core.graphics.drawable.toBitmap\nimport androidx.interpolator.view.animation.FastOutLinearInInterpolator\n\n\nclass ColoredImageVIew : AppCompatImageView {\n constructor(context: Context) : super(context)\n constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)\n constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(\n context,\n attrs,\n defStyleAttr\n )\n\n private val paint by lazy { Paint() }\n\n private val colorList = arrayOf(\n Color.parseColor(\"#FFA51F\"),\n Color.parseColor(\"#FFD703\"),\n Color.parseColor(\"#C0FF39\"),\n Color.parseColor(\"#00FFE0\")\n ).toIntArray()\n\n private val posList = arrayOf(0f, 0.5178f, 0.7654f, 1f).toFloatArray()\n\n private val colorAnimator by lazy {\n ObjectAnimator.ofFloat(1f, 0f)\n .apply {\n addUpdateListener {\n val pos = (it.animatedValue as Float)\n val shader = LinearGradient(\n (1 - pos) * width.toFloat() * 2f,\n pos * height.toFloat(),\n 0f,\n height.toFloat(),\n colorList,\n posList,\n Shader.TileMode.CLAMP\n )\n paint.shader = shader\n postInvalidateOnAnimation()\n }\n duration = 1200\n interpolator = FastOutLinearInInterpolator()\n repeatCount = ObjectAnimator.INFINITE\n repeatMode = ObjectAnimator.REVERSE\n }\n }\n\n\n private var innerBitmap: Bitmap? = null\n\n @SuppressLint(\"DrawAllocation\")\n override fun onDraw(canvas: Canvas?) {\n if (innerBitmap == null) {\n super.onDraw(canvas)\n innerBitmap = drawable.toBitmap(width, height)\n }\n innerBitmap?.let {\n val sc = canvas?.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), null) ?: return\n canvas.drawBitmap(it, 0f, 0f, paint)\n paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)\n canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)\n paint.xfermode = null\n canvas.restoreToCount(sc)\n }\n }\n\n\n fun start() {\n colorAnimator.start()\n }\n\n fun stop() {\n colorAnimator.pause()\n }\n}\n```\n\n### Response:\n```kotlin","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.async;\n\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n\n private static final String TAG = \"ScanPortsAsyncTask\";\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = delegate;\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n * @return\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n final int NUM_THREADS = 500;\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for(int i = 0; i < NUM_THREADS; i++) {\n if(previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(10, TimeUnit.MINUTES);\n }\n catch(InterruptedException ignored) {\n }\n\n this.delegate.processFinish(true);\n\n return null;\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.async;\n\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n\n private static final String TAG = \"ScanPortsAsyncTask\";\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = delegate;\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n * @return\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n final int NUM_THREADS = 500;\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n ExecutorService executor = Executors.newCachedThreadPool();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for(int i = 0; i < NUM_THREADS; i++) {\n if(previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(10, TimeUnit.MINUTES);\n }\n catch(InterruptedException ignored) {\n }\n\n this.delegate.processFinish(true);\n\n return null;\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.async;\n\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n\n private static final String TAG = \"ScanPortsAsyncTask\";\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = delegate;\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n * @return\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n final int NUM_THREADS = 500;\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n ExecutorService executor = Executors.newCachedThreadPool();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for(int i = 0; i < NUM_THREADS; i++) {\n if(previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(10, TimeUnit.MINUTES);\n }\n catch(InterruptedException ignored) {\n }\n\n this.delegate.processFinish(true);\n\n return null;\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.async;\n\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n\n private static final String TAG = \"ScanPortsAsyncTask\";\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = delegate;\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n * @return\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n final int NUM_THREADS = 500;\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for(int i = 0; i < NUM_THREADS; i++) {\n if(previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(10, TimeUnit.MINUTES);\n }\n catch(InterruptedException ignored) {\n }\n\n this.delegate.processFinish(true);\n\n return null;\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/aaronjwood\/PortAuthority\/commit\/ef46ba248bd73d52e071e53e9352e9cc0cd3694b","commit_message":"'\\\\\"Reduce timeout\\\\n\\\\\"'","source_code":"package com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n Context context = (Context) activity;\n final int NUM_THREADS = UserPreference.getPortScanThreads(context);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ExecutorService executor = Executors.newCachedThreadPool();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(10, TimeUnit.MINUTES);\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n","target_code":"package com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n Context context = (Context) activity;\n final int NUM_THREADS = UserPreference.getPortScanThreads(context);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ExecutorService executor = Executors.newCachedThreadPool();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n Context context = (Context) activity;\n final int NUM_THREADS = UserPreference.getPortScanThreads(context);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ExecutorService executor = Executors.newCachedThreadPool();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(10, TimeUnit.MINUTES);\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n Context context = (Context) activity;\n final int NUM_THREADS = UserPreference.getPortScanThreads(context);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ExecutorService executor = Executors.newCachedThreadPool();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(10, TimeUnit.MINUTES);\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n Context context = (Context) activity;\n final int NUM_THREADS = UserPreference.getPortScanThreads(context);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ExecutorService executor = Executors.newCachedThreadPool();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(10, TimeUnit.MINUTES);\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the code to improve execution time. Write the entire code and no other text in the response.\n\n### Concepts:\n[hint] reduce timeout\n[hint] by 5 units\n\n### Given program:\n```java\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n Context context = (Context) activity;\n final int NUM_THREADS = UserPreference.getPortScanThreads(context);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ExecutorService executor = Executors.newCachedThreadPool();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(10, TimeUnit.MINUTES);\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/*\n * Copyright (C) 2014 Ciaran Gultnieks, ciaran@ciarang.com,\n * Peter Serwylo, peter@serwylo.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.receiver;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.AppProvider;\n\nabstract class PackageReceiver extends BroadcastReceiver {\n\n private static final String TAG = \"PackageReceiver\";\n\n protected abstract boolean toDiscard(Intent intent);\n\n protected abstract void handle(Context context, String appId);\n\n protected PackageInfo getPackageInfo(Context context, String appId) {\n PackageInfo info = null;\n try {\n info = context.getPackageManager().getPackageInfo(appId, 0);\n } catch (PackageManager.NameNotFoundException e) {\n \/\/ ignore\n }\n return info;\n }\n\n @Override\n public void onReceive(Context context, Intent intent) {\n Utils.debugLog(TAG, \"PackageReceiver received [action = '\" + intent.getAction() + \"', data = '\" + intent.getData() + \"']\");\n if (toDiscard(intent)) {\n return;\n }\n String appId = intent.getData().getSchemeSpecificPart();\n handle(context, appId);\n context.getContentResolver().notifyChange(AppProvider.getContentUri(appId), null);\n context.getContentResolver().notifyChange(ApkProvider.getAppUri(appId), null);\n }\n\n}\n\n\nCode-B:\n\/*\n * Copyright (C) 2014 Ciaran Gultnieks, ciaran@ciarang.com,\n * Peter Serwylo, peter@serwylo.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.receiver;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.AppProvider;\n\nabstract class PackageReceiver extends BroadcastReceiver {\n\n private static final String TAG = \"PackageReceiver\";\n\n protected abstract boolean toDiscard(Intent intent);\n\n protected abstract void handle(Context context, String appId);\n\n protected PackageInfo getPackageInfo(Context context, String appId) {\n for (PackageInfo info : context.getPackageManager().getInstalledPackages(0)) {\n if (info.packageName.equals(appId)) {\n return info;\n }\n }\n return null;\n }\n\n @Override\n public void onReceive(Context context, Intent intent) {\n Utils.debugLog(TAG, \"PackageReceiver received [action = '\" + intent.getAction() + \"', data = '\" + intent.getData() + \"']\");\n if (toDiscard(intent)) {\n return;\n }\n String appId = intent.getData().getSchemeSpecificPart();\n handle(context, appId);\n context.getContentResolver().notifyChange(AppProvider.getContentUri(appId), null);\n context.getContentResolver().notifyChange(ApkProvider.getAppUri(appId), null);\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/*\n * Copyright (C) 2014 Ciaran Gultnieks, ciaran@ciarang.com,\n * Peter Serwylo, peter@serwylo.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.receiver;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.AppProvider;\n\nabstract class PackageReceiver extends BroadcastReceiver {\n\n private static final String TAG = \"PackageReceiver\";\n\n protected abstract boolean toDiscard(Intent intent);\n\n protected abstract void handle(Context context, String appId);\n\n protected PackageInfo getPackageInfo(Context context, String appId) {\n for (PackageInfo info : context.getPackageManager().getInstalledPackages(0)) {\n if (info.packageName.equals(appId)) {\n return info;\n }\n }\n return null;\n }\n\n @Override\n public void onReceive(Context context, Intent intent) {\n Utils.debugLog(TAG, \"PackageReceiver received [action = '\" + intent.getAction() + \"', data = '\" + intent.getData() + \"']\");\n if (toDiscard(intent)) {\n return;\n }\n String appId = intent.getData().getSchemeSpecificPart();\n handle(context, appId);\n context.getContentResolver().notifyChange(AppProvider.getContentUri(appId), null);\n context.getContentResolver().notifyChange(ApkProvider.getAppUri(appId), null);\n }\n\n}\n\n\nCode-B:\n\/*\n * Copyright (C) 2014 Ciaran Gultnieks, ciaran@ciarang.com,\n * Peter Serwylo, peter@serwylo.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.receiver;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.AppProvider;\n\nabstract class PackageReceiver extends BroadcastReceiver {\n\n private static final String TAG = \"PackageReceiver\";\n\n protected abstract boolean toDiscard(Intent intent);\n\n protected abstract void handle(Context context, String appId);\n\n protected PackageInfo getPackageInfo(Context context, String appId) {\n PackageInfo info = null;\n try {\n info = context.getPackageManager().getPackageInfo(appId, 0);\n } catch (PackageManager.NameNotFoundException e) {\n \/\/ ignore\n }\n return info;\n }\n\n @Override\n public void onReceive(Context context, Intent intent) {\n Utils.debugLog(TAG, \"PackageReceiver received [action = '\" + intent.getAction() + \"', data = '\" + intent.getData() + \"']\");\n if (toDiscard(intent)) {\n return;\n }\n String appId = intent.getData().getSchemeSpecificPart();\n handle(context, appId);\n context.getContentResolver().notifyChange(AppProvider.getContentUri(appId), null);\n context.getContentResolver().notifyChange(ApkProvider.getAppUri(appId), null);\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"framerate","commit":"https:\/\/github.com\/erikusaj\/fdroidTvClient\/commit\/26b35723d30b5d9e5b7fddfdacbcb475db2da0bb","commit_message":"'\\\\\"use AsyncTask for SwapType operations to run in background\\\\n\\\\nThread runs at normal priority by default. AsyncTasks are integrated into\\\\nAndroid for handling things running in the background while keeping the UI\\\\nresponsive.\\\\n\\\\nThis reverts most of commit 828cc272ee5235f868104b009349cc7e835e144f.\\\\n\\\\\"'","source_code":"package org.fdroid.fdroid.localrepo.type;\n\nimport android.content.Context;\nimport android.content.Intent;\nimport android.support.annotation.NonNull;\nimport android.support.v4.content.LocalBroadcastManager;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.localrepo.SwapService;\n\n\/**\n * There is lots of common functionality, and a common API among different communication protocols\n * associated with the swap process. This includes Bluetooth visability, Bonjour visability,\n * and the web server which serves info for swapping. This class provides a common API for\n * starting and stopping these services. In addition, it helps with the process of sending broadcast\n * intents in response to the thing starting or stopping.\n *\/\npublic abstract class SwapType {\n\n private static final String TAG = \"SwapType\";\n\n private boolean isConnected;\n\n @NonNull\n protected final Context context;\n\n public SwapType(@NonNull Context context) {\n this.context = context;\n }\n\n public abstract void start();\n\n public abstract void stop();\n\n protected abstract String getBroadcastAction();\n\n public boolean isDiscoverable() {\n return isConnected();\n }\n\n protected final void setConnected(boolean connected) {\n if (connected) {\n isConnected = true;\n sendBroadcast(SwapService.EXTRA_STARTED);\n } else {\n isConnected = false;\n onStopped();\n sendBroadcast(SwapService.EXTRA_STOPPED);\n }\n }\n\n protected void onStopped() { }\n\n \/**\n * Sends either a {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTING},\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTED} or\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STOPPED} broadcast.\n *\/\n protected final void sendBroadcast(String extra) {\n if (getBroadcastAction() != null) {\n Intent intent = new Intent(getBroadcastAction());\n intent.putExtra(extra, true);\n Utils.debugLog(TAG, \"Sending broadcast \" + extra + \" from \" + getClass().getSimpleName());\n LocalBroadcastManager.getInstance(context).sendBroadcast(intent);\n }\n }\n\n public boolean isConnected() {\n return isConnected;\n }\n\n public void startInBackground() {\n new Thread() {\n @Override\n public void run() {\n SwapType.this.start();\n }\n }.start();\n }\n\n private void ensureRunning() {\n if (!isConnected()) {\n start();\n }\n }\n\n public void ensureRunningInBackground() {\n new Thread() {\n @Override\n public void run() {\n ensureRunning();\n }\n }.start();\n }\n\n public void stopInBackground() {\n new Thread() {\n @Override\n public void run() {\n SwapType.this.stop();\n }\n }.start();\n }\n\n}\n","target_code":"package org.fdroid.fdroid.localrepo.type;\n\nimport android.content.Context;\nimport android.content.Intent;\nimport android.os.AsyncTask;\nimport android.support.annotation.NonNull;\nimport android.support.v4.content.LocalBroadcastManager;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.localrepo.SwapService;\n\n\/**\n * There is lots of common functionality, and a common API among different communication protocols\n * associated with the swap process. This includes Bluetooth visability, Bonjour visability,\n * and the web server which serves info for swapping. This class provides a common API for\n * starting and stopping these services. In addition, it helps with the process of sending broadcast\n * intents in response to the thing starting or stopping.\n *\/\npublic abstract class SwapType {\n\n private static final String TAG = \"SwapType\";\n\n private boolean isConnected;\n\n @NonNull\n protected final Context context;\n\n public SwapType(@NonNull Context context) {\n this.context = context;\n }\n\n public abstract void start();\n\n public abstract void stop();\n\n protected abstract String getBroadcastAction();\n\n public boolean isDiscoverable() {\n return isConnected();\n }\n\n protected final void setConnected(boolean connected) {\n if (connected) {\n isConnected = true;\n sendBroadcast(SwapService.EXTRA_STARTED);\n } else {\n isConnected = false;\n onStopped();\n sendBroadcast(SwapService.EXTRA_STOPPED);\n }\n }\n\n protected void onStopped() { }\n\n \/**\n * Sends either a {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTING},\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTED} or\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STOPPED} broadcast.\n *\/\n protected final void sendBroadcast(String extra) {\n if (getBroadcastAction() != null) {\n Intent intent = new Intent(getBroadcastAction());\n intent.putExtra(extra, true);\n Utils.debugLog(TAG, \"Sending broadcast \" + extra + \" from \" + getClass().getSimpleName());\n LocalBroadcastManager.getInstance(context).sendBroadcast(intent);\n }\n }\n\n public boolean isConnected() {\n return isConnected;\n }\n\n public void startInBackground() {\n new AsyncTask() {\n @Override\n protected Void doInBackground(Void... params) {\n start();\n return null;\n }\n }.execute();\n }\n\n private void ensureRunning() {\n if (!isConnected()) {\n start();\n }\n }\n\n public void ensureRunningInBackground() {\n new AsyncTask() {\n @Override\n protected Void doInBackground(Void... params) {\n ensureRunning();\n return null;\n }\n }.execute();\n }\n\n public void stopInBackground() {\n new AsyncTask() {\n @Override\n protected Void doInBackground(Void... params) {\n stop();\n return null;\n }\n }.execute();\n }\n\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the frame rate. Write the entire code and no other text.\n```java\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n SearchEngineManager.getInstance().init(this);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n```\n\n### Thought:\nThe onCreate() function performs necessary initializations such as loading certain preferences, and sets up SearchEngineManager instance. However, loading preferences depends on the Search Engine manager, because the default search engine preference uses the search engine manager; we therefore need to ensure that preferences aren't loaded until search engines are loaded, to avoid potential hangup of the application for a fresh install. The following optimized code first initializes the search engine manager and then loads preferences.\n\n### Response:\n ```java\n \/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n SearchEngineManager.getInstance().init(this);\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the frame rate. Write the entire code and no other text:\npackage org.fdroid.fdroid.localrepo.type;\n\nimport android.content.Context;\nimport android.content.Intent;\nimport android.support.annotation.NonNull;\nimport android.support.v4.content.LocalBroadcastManager;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.localrepo.SwapService;\n\n\/**\n * There is lots of common functionality, and a common API among different communication protocols\n * associated with the swap process. This includes Bluetooth visability, Bonjour visability,\n * and the web server which serves info for swapping. This class provides a common API for\n * starting and stopping these services. In addition, it helps with the process of sending broadcast\n * intents in response to the thing starting or stopping.\n *\/\npublic abstract class SwapType {\n\n private static final String TAG = \"SwapType\";\n\n private boolean isConnected;\n\n @NonNull\n protected final Context context;\n\n public SwapType(@NonNull Context context) {\n this.context = context;\n }\n\n public abstract void start();\n\n public abstract void stop();\n\n protected abstract String getBroadcastAction();\n\n public boolean isDiscoverable() {\n return isConnected();\n }\n\n protected final void setConnected(boolean connected) {\n if (connected) {\n isConnected = true;\n sendBroadcast(SwapService.EXTRA_STARTED);\n } else {\n isConnected = false;\n onStopped();\n sendBroadcast(SwapService.EXTRA_STOPPED);\n }\n }\n\n protected void onStopped() { }\n\n \/**\n * Sends either a {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTING},\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTED} or\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STOPPED} broadcast.\n *\/\n protected final void sendBroadcast(String extra) {\n if (getBroadcastAction() != null) {\n Intent intent = new Intent(getBroadcastAction());\n intent.putExtra(extra, true);\n Utils.debugLog(TAG, \"Sending broadcast \" + extra + \" from \" + getClass().getSimpleName());\n LocalBroadcastManager.getInstance(context).sendBroadcast(intent);\n }\n }\n\n public boolean isConnected() {\n return isConnected;\n }\n\n public void startInBackground() {\n new Thread() {\n @Override\n public void run() {\n SwapType.this.start();\n }\n }.start();\n }\n\n private void ensureRunning() {\n if (!isConnected()) {\n start();\n }\n }\n\n public void ensureRunningInBackground() {\n new Thread() {\n @Override\n public void run() {\n ensureRunning();\n }\n }.start();\n }\n\n public void stopInBackground() {\n new Thread() {\n @Override\n public void run() {\n SwapType.this.stop();\n }\n }.start();\n }\n\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the frame rate. Write the entire code and no other text.\n```java\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n SearchEngineManager.getInstance().init(this);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n```\n### Response:\n ```java\n \/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n SearchEngineManager.getInstance().init(this);\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the frame rate. Write the entire code and no other text:\npackage org.fdroid.fdroid.localrepo.type;\n\nimport android.content.Context;\nimport android.content.Intent;\nimport android.support.annotation.NonNull;\nimport android.support.v4.content.LocalBroadcastManager;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.localrepo.SwapService;\n\n\/**\n * There is lots of common functionality, and a common API among different communication protocols\n * associated with the swap process. This includes Bluetooth visability, Bonjour visability,\n * and the web server which serves info for swapping. This class provides a common API for\n * starting and stopping these services. In addition, it helps with the process of sending broadcast\n * intents in response to the thing starting or stopping.\n *\/\npublic abstract class SwapType {\n\n private static final String TAG = \"SwapType\";\n\n private boolean isConnected;\n\n @NonNull\n protected final Context context;\n\n public SwapType(@NonNull Context context) {\n this.context = context;\n }\n\n public abstract void start();\n\n public abstract void stop();\n\n protected abstract String getBroadcastAction();\n\n public boolean isDiscoverable() {\n return isConnected();\n }\n\n protected final void setConnected(boolean connected) {\n if (connected) {\n isConnected = true;\n sendBroadcast(SwapService.EXTRA_STARTED);\n } else {\n isConnected = false;\n onStopped();\n sendBroadcast(SwapService.EXTRA_STOPPED);\n }\n }\n\n protected void onStopped() { }\n\n \/**\n * Sends either a {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTING},\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTED} or\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STOPPED} broadcast.\n *\/\n protected final void sendBroadcast(String extra) {\n if (getBroadcastAction() != null) {\n Intent intent = new Intent(getBroadcastAction());\n intent.putExtra(extra, true);\n Utils.debugLog(TAG, \"Sending broadcast \" + extra + \" from \" + getClass().getSimpleName());\n LocalBroadcastManager.getInstance(context).sendBroadcast(intent);\n }\n }\n\n public boolean isConnected() {\n return isConnected;\n }\n\n public void startInBackground() {\n new Thread() {\n @Override\n public void run() {\n SwapType.this.start();\n }\n }.start();\n }\n\n private void ensureRunning() {\n if (!isConnected()) {\n start();\n }\n }\n\n public void ensureRunningInBackground() {\n new Thread() {\n @Override\n public void run() {\n ensureRunning();\n }\n }.start();\n }\n\n public void stopInBackground() {\n new Thread() {\n @Override\n public void run() {\n SwapType.this.stop();\n }\n }.start();\n }\n\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the frame rate. Write the entire code and no other text:\npackage org.fdroid.fdroid.localrepo.type;\n\nimport android.content.Context;\nimport android.content.Intent;\nimport android.support.annotation.NonNull;\nimport android.support.v4.content.LocalBroadcastManager;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.localrepo.SwapService;\n\n\/**\n * There is lots of common functionality, and a common API among different communication protocols\n * associated with the swap process. This includes Bluetooth visability, Bonjour visability,\n * and the web server which serves info for swapping. This class provides a common API for\n * starting and stopping these services. In addition, it helps with the process of sending broadcast\n * intents in response to the thing starting or stopping.\n *\/\npublic abstract class SwapType {\n\n private static final String TAG = \"SwapType\";\n\n private boolean isConnected;\n\n @NonNull\n protected final Context context;\n\n public SwapType(@NonNull Context context) {\n this.context = context;\n }\n\n public abstract void start();\n\n public abstract void stop();\n\n protected abstract String getBroadcastAction();\n\n public boolean isDiscoverable() {\n return isConnected();\n }\n\n protected final void setConnected(boolean connected) {\n if (connected) {\n isConnected = true;\n sendBroadcast(SwapService.EXTRA_STARTED);\n } else {\n isConnected = false;\n onStopped();\n sendBroadcast(SwapService.EXTRA_STOPPED);\n }\n }\n\n protected void onStopped() { }\n\n \/**\n * Sends either a {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTING},\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTED} or\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STOPPED} broadcast.\n *\/\n protected final void sendBroadcast(String extra) {\n if (getBroadcastAction() != null) {\n Intent intent = new Intent(getBroadcastAction());\n intent.putExtra(extra, true);\n Utils.debugLog(TAG, \"Sending broadcast \" + extra + \" from \" + getClass().getSimpleName());\n LocalBroadcastManager.getInstance(context).sendBroadcast(intent);\n }\n }\n\n public boolean isConnected() {\n return isConnected;\n }\n\n public void startInBackground() {\n new Thread() {\n @Override\n public void run() {\n SwapType.this.start();\n }\n }.start();\n }\n\n private void ensureRunning() {\n if (!isConnected()) {\n start();\n }\n }\n\n public void ensureRunningInBackground() {\n new Thread() {\n @Override\n public void run() {\n ensureRunning();\n }\n }.start();\n }\n\n public void stopInBackground() {\n new Thread() {\n @Override\n public void run() {\n SwapType.this.stop();\n }\n }.start();\n }\n\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the code to improve frame rate and user experience of the android application. Write the entire code and no other text in the response.\n\n### Concepts:\n[+] android.os.AsyncTask\n[-] Thread\n\n### Given program:\n```java\npackage org.fdroid.fdroid.localrepo.type;\n\nimport android.content.Context;\nimport android.content.Intent;\nimport android.support.annotation.NonNull;\nimport android.support.v4.content.LocalBroadcastManager;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.localrepo.SwapService;\n\n\/**\n * There is lots of common functionality, and a common API among different communication protocols\n * associated with the swap process. This includes Bluetooth visability, Bonjour visability,\n * and the web server which serves info for swapping. This class provides a common API for\n * starting and stopping these services. In addition, it helps with the process of sending broadcast\n * intents in response to the thing starting or stopping.\n *\/\npublic abstract class SwapType {\n\n private static final String TAG = \"SwapType\";\n\n private boolean isConnected;\n\n @NonNull\n protected final Context context;\n\n public SwapType(@NonNull Context context) {\n this.context = context;\n }\n\n public abstract void start();\n\n public abstract void stop();\n\n protected abstract String getBroadcastAction();\n\n public boolean isDiscoverable() {\n return isConnected();\n }\n\n protected final void setConnected(boolean connected) {\n if (connected) {\n isConnected = true;\n sendBroadcast(SwapService.EXTRA_STARTED);\n } else {\n isConnected = false;\n onStopped();\n sendBroadcast(SwapService.EXTRA_STOPPED);\n }\n }\n\n protected void onStopped() { }\n\n \/**\n * Sends either a {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTING},\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTED} or\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STOPPED} broadcast.\n *\/\n protected final void sendBroadcast(String extra) {\n if (getBroadcastAction() != null) {\n Intent intent = new Intent(getBroadcastAction());\n intent.putExtra(extra, true);\n Utils.debugLog(TAG, \"Sending broadcast \" + extra + \" from \" + getClass().getSimpleName());\n LocalBroadcastManager.getInstance(context).sendBroadcast(intent);\n }\n }\n\n public boolean isConnected() {\n return isConnected;\n }\n\n public void startInBackground() {\n new Thread() {\n @Override\n public void run() {\n SwapType.this.start();\n }\n }.start();\n }\n\n private void ensureRunning() {\n if (!isConnected()) {\n start();\n }\n }\n\n public void ensureRunningInBackground() {\n new Thread() {\n @Override\n public void run() {\n ensureRunning();\n }\n }.start();\n }\n\n public void stopInBackground() {\n new Thread() {\n @Override\n public void run() {\n SwapType.this.stop();\n }\n }.start();\n }\n\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage me.rosuh.easywatermark.widget\n\nimport android.animation.ObjectAnimator\nimport android.annotation.SuppressLint\nimport android.content.Context\nimport android.graphics.*\nimport android.util.AttributeSet\nimport androidx.appcompat.widget.AppCompatImageView\nimport androidx.core.graphics.drawable.toBitmap\n\n\nclass ColoredImageVIew : AppCompatImageView {\n constructor(context: Context) : super(context)\n constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)\n constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(\n context,\n attrs,\n defStyleAttr\n )\n\n private var sizeHasChanged: Boolean = true\n private val paint by lazy { Paint() }\n\n private val colorList = arrayOf(\n Color.parseColor(\"#FFA51F\"),\n Color.parseColor(\"#FFD703\"),\n Color.parseColor(\"#C0FF39\"),\n Color.parseColor(\"#00FFE0\")\n ).toIntArray()\n\n private val posList = arrayOf(0f, 0.5178f, 0.7654f, 1f).toFloatArray()\n\n private val xfermode by lazy { PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP) }\n\n private val colorAnimator by lazy {\n ObjectAnimator.ofFloat(1f, 0f)\n .apply {\n addUpdateListener {\n val pos = (it.animatedValue as Float)\n val shader = LinearGradient(\n (1 - pos) * width.toFloat() * 2f,\n pos * height.toFloat(),\n 0f,\n height.toFloat(),\n colorList,\n posList,\n Shader.TileMode.CLAMP\n )\n paint.shader = shader\n postInvalidateOnAnimation()\n }\n duration = 1200\n repeatCount = ObjectAnimator.INFINITE\n repeatMode = ObjectAnimator.REVERSE\n }\n }\n\n\n private var innerBitmap: Bitmap? = null\n\n override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {\n super.onSizeChanged(w, h, oldw, oldh)\n sizeHasChanged = w != oldh || h != oldh\n }\n\n @SuppressLint(\"DrawAllocation\")\n override fun onDraw(canvas: Canvas?) {\n if (innerBitmap == null || sizeHasChanged) {\n super.onDraw(canvas)\n innerBitmap = drawable.toBitmap(width, height)\n }\n innerBitmap?.let {\n val sc = canvas?.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), null) ?: return\n canvas.drawBitmap(it, 0f, 0f, paint)\n paint.xfermode = xfermode\n canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)\n paint.xfermode = null\n canvas.restoreToCount(sc)\n }\n }\n\n\n fun start() {\n colorAnimator.start()\n }\n\n fun stop() {\n colorAnimator.pause()\n }\n}\n\nCode-B:\npackage me.rosuh.easywatermark.widget\n\nimport android.animation.ObjectAnimator\nimport android.annotation.SuppressLint\nimport android.content.Context\nimport android.graphics.*\nimport android.util.AttributeSet\nimport androidx.appcompat.widget.AppCompatImageView\nimport androidx.core.graphics.drawable.toBitmap\nimport androidx.interpolator.view.animation.FastOutLinearInInterpolator\n\n\nclass ColoredImageVIew : AppCompatImageView {\n constructor(context: Context) : super(context)\n constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)\n constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(\n context,\n attrs,\n defStyleAttr\n )\n\n private val paint by lazy { Paint() }\n\n private val colorList = arrayOf(\n Color.parseColor(\"#FFA51F\"),\n Color.parseColor(\"#FFD703\"),\n Color.parseColor(\"#C0FF39\"),\n Color.parseColor(\"#00FFE0\")\n ).toIntArray()\n\n private val posList = arrayOf(0f, 0.5178f, 0.7654f, 1f).toFloatArray()\n\n private val colorAnimator by lazy {\n ObjectAnimator.ofFloat(1f, 0f)\n .apply {\n addUpdateListener {\n val pos = (it.animatedValue as Float)\n val shader = LinearGradient(\n (1 - pos) * width.toFloat() * 2f,\n pos * height.toFloat(),\n 0f,\n height.toFloat(),\n colorList,\n posList,\n Shader.TileMode.CLAMP\n )\n paint.shader = shader\n postInvalidateOnAnimation()\n }\n duration = 1200\n interpolator = FastOutLinearInInterpolator()\n repeatCount = ObjectAnimator.INFINITE\n repeatMode = ObjectAnimator.REVERSE\n }\n }\n\n\n private var innerBitmap: Bitmap? = null\n\n @SuppressLint(\"DrawAllocation\")\n override fun onDraw(canvas: Canvas?) {\n if (innerBitmap == null) {\n super.onDraw(canvas)\n innerBitmap = drawable.toBitmap(width, height)\n }\n innerBitmap?.let {\n val sc = canvas?.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), null) ?: return\n canvas.drawBitmap(it, 0f, 0f, paint)\n paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)\n canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)\n paint.xfermode = null\n canvas.restoreToCount(sc)\n }\n }\n\n\n fun start() {\n colorAnimator.start()\n }\n\n fun stop() {\n colorAnimator.pause()\n }\n}\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage me.rosuh.easywatermark.widget\n\nimport android.animation.ObjectAnimator\nimport android.annotation.SuppressLint\nimport android.content.Context\nimport android.graphics.*\nimport android.util.AttributeSet\nimport androidx.appcompat.widget.AppCompatImageView\nimport androidx.core.graphics.drawable.toBitmap\nimport androidx.interpolator.view.animation.FastOutLinearInInterpolator\n\n\nclass ColoredImageVIew : AppCompatImageView {\n constructor(context: Context) : super(context)\n constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)\n constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(\n context,\n attrs,\n defStyleAttr\n )\n\n private val paint by lazy { Paint() }\n\n private val colorList = arrayOf(\n Color.parseColor(\"#FFA51F\"),\n Color.parseColor(\"#FFD703\"),\n Color.parseColor(\"#C0FF39\"),\n Color.parseColor(\"#00FFE0\")\n ).toIntArray()\n\n private val posList = arrayOf(0f, 0.5178f, 0.7654f, 1f).toFloatArray()\n\n private val colorAnimator by lazy {\n ObjectAnimator.ofFloat(1f, 0f)\n .apply {\n addUpdateListener {\n val pos = (it.animatedValue as Float)\n val shader = LinearGradient(\n (1 - pos) * width.toFloat() * 2f,\n pos * height.toFloat(),\n 0f,\n height.toFloat(),\n colorList,\n posList,\n Shader.TileMode.CLAMP\n )\n paint.shader = shader\n postInvalidateOnAnimation()\n }\n duration = 1200\n interpolator = FastOutLinearInInterpolator()\n repeatCount = ObjectAnimator.INFINITE\n repeatMode = ObjectAnimator.REVERSE\n }\n }\n\n\n private var innerBitmap: Bitmap? = null\n\n @SuppressLint(\"DrawAllocation\")\n override fun onDraw(canvas: Canvas?) {\n if (innerBitmap == null) {\n super.onDraw(canvas)\n innerBitmap = drawable.toBitmap(width, height)\n }\n innerBitmap?.let {\n val sc = canvas?.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), null) ?: return\n canvas.drawBitmap(it, 0f, 0f, paint)\n paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)\n canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)\n paint.xfermode = null\n canvas.restoreToCount(sc)\n }\n }\n\n\n fun start() {\n colorAnimator.start()\n }\n\n fun stop() {\n colorAnimator.pause()\n }\n}\n\nCode-B:\npackage me.rosuh.easywatermark.widget\n\nimport android.animation.ObjectAnimator\nimport android.annotation.SuppressLint\nimport android.content.Context\nimport android.graphics.*\nimport android.util.AttributeSet\nimport androidx.appcompat.widget.AppCompatImageView\nimport androidx.core.graphics.drawable.toBitmap\n\n\nclass ColoredImageVIew : AppCompatImageView {\n constructor(context: Context) : super(context)\n constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)\n constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(\n context,\n attrs,\n defStyleAttr\n )\n\n private var sizeHasChanged: Boolean = true\n private val paint by lazy { Paint() }\n\n private val colorList = arrayOf(\n Color.parseColor(\"#FFA51F\"),\n Color.parseColor(\"#FFD703\"),\n Color.parseColor(\"#C0FF39\"),\n Color.parseColor(\"#00FFE0\")\n ).toIntArray()\n\n private val posList = arrayOf(0f, 0.5178f, 0.7654f, 1f).toFloatArray()\n\n private val xfermode by lazy { PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP) }\n\n private val colorAnimator by lazy {\n ObjectAnimator.ofFloat(1f, 0f)\n .apply {\n addUpdateListener {\n val pos = (it.animatedValue as Float)\n val shader = LinearGradient(\n (1 - pos) * width.toFloat() * 2f,\n pos * height.toFloat(),\n 0f,\n height.toFloat(),\n colorList,\n posList,\n Shader.TileMode.CLAMP\n )\n paint.shader = shader\n postInvalidateOnAnimation()\n }\n duration = 1200\n repeatCount = ObjectAnimator.INFINITE\n repeatMode = ObjectAnimator.REVERSE\n }\n }\n\n\n private var innerBitmap: Bitmap? = null\n\n override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {\n super.onSizeChanged(w, h, oldw, oldh)\n sizeHasChanged = w != oldh || h != oldh\n }\n\n @SuppressLint(\"DrawAllocation\")\n override fun onDraw(canvas: Canvas?) {\n if (innerBitmap == null || sizeHasChanged) {\n super.onDraw(canvas)\n innerBitmap = drawable.toBitmap(width, height)\n }\n innerBitmap?.let {\n val sc = canvas?.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), null) ?: return\n canvas.drawBitmap(it, 0f, 0f, paint)\n paint.xfermode = xfermode\n canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)\n paint.xfermode = null\n canvas.restoreToCount(sc)\n }\n }\n\n\n fun start() {\n colorAnimator.start()\n }\n\n fun stop() {\n colorAnimator.pause()\n }\n}\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/aaronjwood\/PortAuthority\/commit\/44a588294f7ab129eb50de23897a348e114fc30b","commit_message":"'\\\\\"Set performance options to prefer fast connection when scanning ports. Enable TCP_NODELAY\\\\n\\\\\"'","source_code":"package com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(1);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n\n char[] buffer = new char[1024];\n HashMap portData = new HashMap<>();\n BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n String data = null;\n\n if(i == 22) {\n data = in.readLine();\n in.close();\n }\n else if(i == 80 || i == 443) {\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\");\n out.println(\"Host: \" + this.ip);\n out.println(\"\");\n\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if(data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n }\n else if(data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n }\n else if(data.contains(\"nginx\")) {\n data = \"Nginx\";\n }\n else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n }\n catch(IOException ignored) {\n }\n }\n }\n}\n","target_code":"package com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(1);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n\n char[] buffer = new char[1024];\n HashMap portData = new HashMap<>();\n BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n String data = null;\n\n if(i == 22) {\n data = in.readLine();\n in.close();\n }\n else if(i == 80 || i == 443) {\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\");\n out.println(\"Host: \" + this.ip);\n out.println(\"\");\n\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if(data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n }\n else if(data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n }\n else if(data.contains(\"nginx\")) {\n data = \"Nginx\";\n }\n else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n }\n catch(IOException ignored) {\n }\n }\n }\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(1);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n\n char[] buffer = new char[1024];\n HashMap portData = new HashMap<>();\n BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n String data = null;\n\n if(i == 22) {\n data = in.readLine();\n in.close();\n }\n else if(i == 80 || i == 443) {\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\");\n out.println(\"Host: \" + this.ip);\n out.println(\"\");\n\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if(data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n }\n else if(data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n }\n else if(data.contains(\"nginx\")) {\n data = \"Nginx\";\n }\n else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n }\n catch(IOException ignored) {\n }\n }\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(1);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n\n char[] buffer = new char[1024];\n HashMap portData = new HashMap<>();\n BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n String data = null;\n\n if(i == 22) {\n data = in.readLine();\n in.close();\n }\n else if(i == 80 || i == 443) {\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\");\n out.println(\"Host: \" + this.ip);\n out.println(\"\");\n\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if(data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n }\n else if(data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n }\n else if(data.contains(\"nginx\")) {\n data = \"Nginx\";\n }\n else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n }\n catch(IOException ignored) {\n }\n }\n }\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(1);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n\n char[] buffer = new char[1024];\n HashMap portData = new HashMap<>();\n BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n String data = null;\n\n if(i == 22) {\n data = in.readLine();\n in.close();\n }\n else if(i == 80 || i == 443) {\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\");\n out.println(\"Host: \" + this.ip);\n out.println(\"\");\n\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if(data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n }\n else if(data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n }\n else if(data.contains(\"nginx\")) {\n data = \"Nginx\";\n }\n else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n }\n catch(IOException ignored) {\n }\n }\n }\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite code to prefer fast connection when scanning ports. Write the entire code and no other text in the response.\n\n### Concepts:\n[+] TCP_NODELAY\n[+] setPerformancePreferences\n\n### Given program:\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(1);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n\n char[] buffer = new char[1024];\n HashMap portData = new HashMap<>();\n BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n String data = null;\n\n if(i == 22) {\n data = in.readLine();\n in.close();\n }\n else if(i == 80 || i == 443) {\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\");\n out.println(\"Host: \" + this.ip);\n out.println(\"\");\n\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if(data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n }\n else if(data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n }\n else if(data.contains(\"nginx\")) {\n data = \"Nginx\";\n }\n else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n }\n catch(IOException ignored) {\n }\n }\n }\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n Context context = (Context) activity;\n final int NUM_THREADS = UserPreference.getPortScanThreads(context);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ExecutorService executor = Executors.newCachedThreadPool();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n Context context = (Context) activity;\n final int NUM_THREADS = UserPreference.getPortScanThreads(context);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ExecutorService executor = Executors.newCachedThreadPool();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(10, TimeUnit.MINUTES);\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n Context context = (Context) activity;\n final int NUM_THREADS = UserPreference.getPortScanThreads(context);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ExecutorService executor = Executors.newCachedThreadPool();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(10, TimeUnit.MINUTES);\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n Context context = (Context) activity;\n final int NUM_THREADS = UserPreference.getPortScanThreads(context);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ExecutorService executor = Executors.newCachedThreadPool();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n break;\n }\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, delegate));\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/aaronjwood\/PortAuthority\/commit\/876bb8058fbc12aff4bbab407b11522b80361ebb","commit_message":"'\\\\\"Improve scheduling to increase scan performance but keep load down\\\\n\\\\\"'","source_code":"package com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt(10) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n","target_code":"package com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt(((stopPort - startPort) \/ NUM_THREADS) \/ 2) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt(10) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt(10) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt(10) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite code to improve scheduling and execution time while keeping the load down. Write the entire code and no other text in the response.\n\n### Concepts:\n[in] doInBackground function\n\n### Given program:\n```java\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt(10) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower frame rate.\n\nCode-A:\npackage org.fdroid.fdroid.localrepo.type;\n\nimport android.content.Context;\nimport android.content.Intent;\nimport android.os.AsyncTask;\nimport android.support.annotation.NonNull;\nimport android.support.v4.content.LocalBroadcastManager;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.localrepo.SwapService;\n\n\/**\n * There is lots of common functionality, and a common API among different communication protocols\n * associated with the swap process. This includes Bluetooth visability, Bonjour visability,\n * and the web server which serves info for swapping. This class provides a common API for\n * starting and stopping these services. In addition, it helps with the process of sending broadcast\n * intents in response to the thing starting or stopping.\n *\/\npublic abstract class SwapType {\n\n private static final String TAG = \"SwapType\";\n\n private boolean isConnected;\n\n @NonNull\n protected final Context context;\n\n public SwapType(@NonNull Context context) {\n this.context = context;\n }\n\n public abstract void start();\n\n public abstract void stop();\n\n protected abstract String getBroadcastAction();\n\n public boolean isDiscoverable() {\n return isConnected();\n }\n\n protected final void setConnected(boolean connected) {\n if (connected) {\n isConnected = true;\n sendBroadcast(SwapService.EXTRA_STARTED);\n } else {\n isConnected = false;\n onStopped();\n sendBroadcast(SwapService.EXTRA_STOPPED);\n }\n }\n\n protected void onStopped() { }\n\n \/**\n * Sends either a {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTING},\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTED} or\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STOPPED} broadcast.\n *\/\n protected final void sendBroadcast(String extra) {\n if (getBroadcastAction() != null) {\n Intent intent = new Intent(getBroadcastAction());\n intent.putExtra(extra, true);\n Utils.debugLog(TAG, \"Sending broadcast \" + extra + \" from \" + getClass().getSimpleName());\n LocalBroadcastManager.getInstance(context).sendBroadcast(intent);\n }\n }\n\n public boolean isConnected() {\n return isConnected;\n }\n\n public void startInBackground() {\n new AsyncTask() {\n @Override\n protected Void doInBackground(Void... params) {\n start();\n return null;\n }\n }.execute();\n }\n\n private void ensureRunning() {\n if (!isConnected()) {\n start();\n }\n }\n\n public void ensureRunningInBackground() {\n new AsyncTask() {\n @Override\n protected Void doInBackground(Void... params) {\n ensureRunning();\n return null;\n }\n }.execute();\n }\n\n public void stopInBackground() {\n new AsyncTask() {\n @Override\n protected Void doInBackground(Void... params) {\n stop();\n return null;\n }\n }.execute();\n }\n\n}\n\n\nCode-B:\npackage org.fdroid.fdroid.localrepo.type;\n\nimport android.content.Context;\nimport android.content.Intent;\nimport android.support.annotation.NonNull;\nimport android.support.v4.content.LocalBroadcastManager;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.localrepo.SwapService;\n\n\/**\n * There is lots of common functionality, and a common API among different communication protocols\n * associated with the swap process. This includes Bluetooth visability, Bonjour visability,\n * and the web server which serves info for swapping. This class provides a common API for\n * starting and stopping these services. In addition, it helps with the process of sending broadcast\n * intents in response to the thing starting or stopping.\n *\/\npublic abstract class SwapType {\n\n private static final String TAG = \"SwapType\";\n\n private boolean isConnected;\n\n @NonNull\n protected final Context context;\n\n public SwapType(@NonNull Context context) {\n this.context = context;\n }\n\n public abstract void start();\n\n public abstract void stop();\n\n protected abstract String getBroadcastAction();\n\n public boolean isDiscoverable() {\n return isConnected();\n }\n\n protected final void setConnected(boolean connected) {\n if (connected) {\n isConnected = true;\n sendBroadcast(SwapService.EXTRA_STARTED);\n } else {\n isConnected = false;\n onStopped();\n sendBroadcast(SwapService.EXTRA_STOPPED);\n }\n }\n\n protected void onStopped() { }\n\n \/**\n * Sends either a {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTING},\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTED} or\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STOPPED} broadcast.\n *\/\n protected final void sendBroadcast(String extra) {\n if (getBroadcastAction() != null) {\n Intent intent = new Intent(getBroadcastAction());\n intent.putExtra(extra, true);\n Utils.debugLog(TAG, \"Sending broadcast \" + extra + \" from \" + getClass().getSimpleName());\n LocalBroadcastManager.getInstance(context).sendBroadcast(intent);\n }\n }\n\n public boolean isConnected() {\n return isConnected;\n }\n\n public void startInBackground() {\n new Thread() {\n @Override\n public void run() {\n SwapType.this.start();\n }\n }.start();\n }\n\n private void ensureRunning() {\n if (!isConnected()) {\n start();\n }\n }\n\n public void ensureRunningInBackground() {\n new Thread() {\n @Override\n public void run() {\n ensureRunning();\n }\n }.start();\n }\n\n public void stopInBackground() {\n new Thread() {\n @Override\n public void run() {\n SwapType.this.stop();\n }\n }.start();\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower frame rate utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower frame rate.\n\nCode-A:\npackage org.fdroid.fdroid.localrepo.type;\n\nimport android.content.Context;\nimport android.content.Intent;\nimport android.support.annotation.NonNull;\nimport android.support.v4.content.LocalBroadcastManager;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.localrepo.SwapService;\n\n\/**\n * There is lots of common functionality, and a common API among different communication protocols\n * associated with the swap process. This includes Bluetooth visability, Bonjour visability,\n * and the web server which serves info for swapping. This class provides a common API for\n * starting and stopping these services. In addition, it helps with the process of sending broadcast\n * intents in response to the thing starting or stopping.\n *\/\npublic abstract class SwapType {\n\n private static final String TAG = \"SwapType\";\n\n private boolean isConnected;\n\n @NonNull\n protected final Context context;\n\n public SwapType(@NonNull Context context) {\n this.context = context;\n }\n\n public abstract void start();\n\n public abstract void stop();\n\n protected abstract String getBroadcastAction();\n\n public boolean isDiscoverable() {\n return isConnected();\n }\n\n protected final void setConnected(boolean connected) {\n if (connected) {\n isConnected = true;\n sendBroadcast(SwapService.EXTRA_STARTED);\n } else {\n isConnected = false;\n onStopped();\n sendBroadcast(SwapService.EXTRA_STOPPED);\n }\n }\n\n protected void onStopped() { }\n\n \/**\n * Sends either a {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTING},\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTED} or\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STOPPED} broadcast.\n *\/\n protected final void sendBroadcast(String extra) {\n if (getBroadcastAction() != null) {\n Intent intent = new Intent(getBroadcastAction());\n intent.putExtra(extra, true);\n Utils.debugLog(TAG, \"Sending broadcast \" + extra + \" from \" + getClass().getSimpleName());\n LocalBroadcastManager.getInstance(context).sendBroadcast(intent);\n }\n }\n\n public boolean isConnected() {\n return isConnected;\n }\n\n public void startInBackground() {\n new Thread() {\n @Override\n public void run() {\n SwapType.this.start();\n }\n }.start();\n }\n\n private void ensureRunning() {\n if (!isConnected()) {\n start();\n }\n }\n\n public void ensureRunningInBackground() {\n new Thread() {\n @Override\n public void run() {\n ensureRunning();\n }\n }.start();\n }\n\n public void stopInBackground() {\n new Thread() {\n @Override\n public void run() {\n SwapType.this.stop();\n }\n }.start();\n }\n\n}\n\n\nCode-B:\npackage org.fdroid.fdroid.localrepo.type;\n\nimport android.content.Context;\nimport android.content.Intent;\nimport android.os.AsyncTask;\nimport android.support.annotation.NonNull;\nimport android.support.v4.content.LocalBroadcastManager;\n\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.localrepo.SwapService;\n\n\/**\n * There is lots of common functionality, and a common API among different communication protocols\n * associated with the swap process. This includes Bluetooth visability, Bonjour visability,\n * and the web server which serves info for swapping. This class provides a common API for\n * starting and stopping these services. In addition, it helps with the process of sending broadcast\n * intents in response to the thing starting or stopping.\n *\/\npublic abstract class SwapType {\n\n private static final String TAG = \"SwapType\";\n\n private boolean isConnected;\n\n @NonNull\n protected final Context context;\n\n public SwapType(@NonNull Context context) {\n this.context = context;\n }\n\n public abstract void start();\n\n public abstract void stop();\n\n protected abstract String getBroadcastAction();\n\n public boolean isDiscoverable() {\n return isConnected();\n }\n\n protected final void setConnected(boolean connected) {\n if (connected) {\n isConnected = true;\n sendBroadcast(SwapService.EXTRA_STARTED);\n } else {\n isConnected = false;\n onStopped();\n sendBroadcast(SwapService.EXTRA_STOPPED);\n }\n }\n\n protected void onStopped() { }\n\n \/**\n * Sends either a {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTING},\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STARTED} or\n * {@link org.fdroid.fdroid.localrepo.SwapService#EXTRA_STOPPED} broadcast.\n *\/\n protected final void sendBroadcast(String extra) {\n if (getBroadcastAction() != null) {\n Intent intent = new Intent(getBroadcastAction());\n intent.putExtra(extra, true);\n Utils.debugLog(TAG, \"Sending broadcast \" + extra + \" from \" + getClass().getSimpleName());\n LocalBroadcastManager.getInstance(context).sendBroadcast(intent);\n }\n }\n\n public boolean isConnected() {\n return isConnected;\n }\n\n public void startInBackground() {\n new AsyncTask() {\n @Override\n protected Void doInBackground(Void... params) {\n start();\n return null;\n }\n }.execute();\n }\n\n private void ensureRunning() {\n if (!isConnected()) {\n start();\n }\n }\n\n public void ensureRunningInBackground() {\n new AsyncTask() {\n @Override\n protected Void doInBackground(Void... params) {\n ensureRunning();\n return null;\n }\n }.execute();\n }\n\n public void stopInBackground() {\n new AsyncTask() {\n @Override\n protected Void doInBackground(Void... params) {\n stop();\n return null;\n }\n }.execute();\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower frame rate utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/aaronjwood\/PortAuthority\/commit\/1c4cbcb3c5265f7502d44c95910f5db0c43a2397","commit_message":"'\\\\\"Fix bug that would cause repeated scans of the same port when performing a very small range scan\\\\n\\\\\"'","source_code":"package com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n executor.execute(new ScanPortsRunnable(ip, previousStart, stopPort, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt((int) ((((stopPort - startPort) \/ NUM_THREADS) \/ 1.5)) + 1) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n","target_code":"package com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = startPort + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n executor.execute(new ScanPortsRunnable(ip, previousStart, stopPort, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt((int) ((((stopPort - startPort) \/ NUM_THREADS) \/ 1.5)) + 1) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n executor.execute(new ScanPortsRunnable(ip, previousStart, stopPort, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt((int) ((((stopPort - startPort) \/ NUM_THREADS) \/ 1.5)) + 1) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n executor.execute(new ScanPortsRunnable(ip, previousStart, stopPort, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt((int) ((((stopPort - startPort) \/ NUM_THREADS) \/ 1.5)) + 1) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n executor.execute(new ScanPortsRunnable(ip, previousStart, stopPort, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt((int) ((((stopPort - startPort) \/ NUM_THREADS) \/ 1.5)) + 1) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite code to improve bandwidth usage and performance. Write the entire code and no other text in the response.\n\n### Concepts:\n[hint] avoid repeated scans of the same port when performing a very small range scan\n\n### Given program:\n```java\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n executor.execute(new ScanPortsRunnable(ip, previousStart, stopPort, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt((int) ((((stopPort - startPort) \/ NUM_THREADS) \/ 1.5)) + 1) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(1);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n\n char[] buffer = new char[1024];\n HashMap portData = new HashMap<>();\n BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n String data = null;\n\n if(i == 22) {\n data = in.readLine();\n in.close();\n }\n else if(i == 80 || i == 443) {\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\");\n out.println(\"Host: \" + this.ip);\n out.println(\"\");\n\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if(data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n }\n else if(data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n }\n else if(data.contains(\"nginx\")) {\n data = \"Nginx\";\n }\n else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n }\n catch(IOException ignored) {\n }\n }\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(1);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n\n char[] buffer = new char[1024];\n HashMap portData = new HashMap<>();\n BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n String data = null;\n\n if(i == 22) {\n data = in.readLine();\n in.close();\n }\n else if(i == 80 || i == 443) {\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\");\n out.println(\"Host: \" + this.ip);\n out.println(\"\");\n\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if(data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n }\n else if(data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n }\n else if(data.contains(\"nginx\")) {\n data = \"Nginx\";\n }\n else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n }\n catch(IOException ignored) {\n }\n }\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(1);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n\n char[] buffer = new char[1024];\n HashMap portData = new HashMap<>();\n BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n String data = null;\n\n if(i == 22) {\n data = in.readLine();\n in.close();\n }\n else if(i == 80 || i == 443) {\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\");\n out.println(\"Host: \" + this.ip);\n out.println(\"\");\n\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if(data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n }\n else if(data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n }\n else if(data.contains(\"nginx\")) {\n data = \"Nginx\";\n }\n else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n }\n catch(IOException ignored) {\n }\n }\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(1);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n\n char[] buffer = new char[1024];\n HashMap portData = new HashMap<>();\n BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n String data = null;\n\n if(i == 22) {\n data = in.readLine();\n in.close();\n }\n else if(i == 80 || i == 443) {\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\");\n out.println(\"Host: \" + this.ip);\n out.println(\"\");\n\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if(data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n }\n else if(data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n }\n else if(data.contains(\"nginx\")) {\n data = \"Nginx\";\n }\n else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n }\n catch(IOException ignored) {\n }\n }\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/aaronjwood\/PortAuthority\/commit\/bfd71d38110d1bbd7b9937dfaf2ac45bca034c4a","commit_message":"'\\\\\"Java can often do more optimizations to things outside of try blocks. Take more advantage of the JIT\\\\n\\\\\"'","source_code":"package com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for (int i = this.startPort; i <= this.stopPort; i++) {\n try {\n if (i % 75 == 0) {\n this.delegate.processFinish(1);\n }\n\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n\n HashMap portData = new HashMap<>();\n BufferedReader in;\n String data = null;\n\n if (i == 22) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n data = in.readLine();\n in.close();\n } else if (i == 80 || i == 443 || i == 8080) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\\r\\nHost: \" + this.ip + \"\\r\\n\");\n\n char[] buffer = new char[1024];\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if (data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n } else if (data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n } else if (data.contains(\"nginx\")) {\n data = \"Nginx\";\n } else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n } catch (IOException ignored) {\n }\n }\n }\n}\n","target_code":"package com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for (int i = this.startPort; i <= this.stopPort; i++) {\n if (i % 75 == 0) {\n this.delegate.processFinish(1);\n }\n\n HashMap portData = new HashMap<>();\n BufferedReader in;\n String data = null;\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n\n try {\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n\n if (i == 22) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n data = in.readLine();\n in.close();\n } else if (i == 80 || i == 443 || i == 8080) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\\r\\nHost: \" + this.ip + \"\\r\\n\");\n\n char[] buffer = new char[1024];\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if (data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n } else if (data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n } else if (data.contains(\"nginx\")) {\n data = \"Nginx\";\n } else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n } catch (IOException ignored) {\n }\n }\n }\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for (int i = this.startPort; i <= this.stopPort; i++) {\n try {\n if (i % 75 == 0) {\n this.delegate.processFinish(1);\n }\n\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n\n HashMap portData = new HashMap<>();\n BufferedReader in;\n String data = null;\n\n if (i == 22) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n data = in.readLine();\n in.close();\n } else if (i == 80 || i == 443 || i == 8080) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\\r\\nHost: \" + this.ip + \"\\r\\n\");\n\n char[] buffer = new char[1024];\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if (data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n } else if (data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n } else if (data.contains(\"nginx\")) {\n data = \"Nginx\";\n } else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n } catch (IOException ignored) {\n }\n }\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for (int i = this.startPort; i <= this.stopPort; i++) {\n try {\n if (i % 75 == 0) {\n this.delegate.processFinish(1);\n }\n\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n\n HashMap portData = new HashMap<>();\n BufferedReader in;\n String data = null;\n\n if (i == 22) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n data = in.readLine();\n in.close();\n } else if (i == 80 || i == 443 || i == 8080) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\\r\\nHost: \" + this.ip + \"\\r\\n\");\n\n char[] buffer = new char[1024];\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if (data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n } else if (data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n } else if (data.contains(\"nginx\")) {\n data = \"Nginx\";\n } else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n } catch (IOException ignored) {\n }\n }\n }\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for (int i = this.startPort; i <= this.stopPort; i++) {\n try {\n if (i % 75 == 0) {\n this.delegate.processFinish(1);\n }\n\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n\n HashMap portData = new HashMap<>();\n BufferedReader in;\n String data = null;\n\n if (i == 22) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n data = in.readLine();\n in.close();\n } else if (i == 80 || i == 443 || i == 8080) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\\r\\nHost: \" + this.ip + \"\\r\\n\");\n\n char[] buffer = new char[1024];\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if (data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n } else if (data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n } else if (data.contains(\"nginx\")) {\n data = \"Nginx\";\n } else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n } catch (IOException ignored) {\n }\n }\n }\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the run function to improve execution time. Write the entire code and no other text in the response.\n\n### Concepts:\n [+] statements inside vs outside try...finally block\n[hint] moving statements outside try...finally blocks enables optimizations\n\n### Given program:\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for (int i = this.startPort; i <= this.stopPort; i++) {\n try {\n if (i % 75 == 0) {\n this.delegate.processFinish(1);\n }\n\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n\n HashMap portData = new HashMap<>();\n BufferedReader in;\n String data = null;\n\n if (i == 22) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n data = in.readLine();\n in.close();\n } else if (i == 80 || i == 443 || i == 8080) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\\r\\nHost: \" + this.ip + \"\\r\\n\");\n\n char[] buffer = new char[1024];\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if (data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n } else if (data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n } else if (data.contains(\"nginx\")) {\n data = \"Nginx\";\n } else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n } catch (IOException ignored) {\n }\n }\n }\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt(((stopPort - startPort) \/ NUM_THREADS) \/ 2) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt(10) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt(10) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n previousStop = stopPort;\n executor.execute(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt(((stopPort - startPort) \/ NUM_THREADS) \/ 2) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/PaperAirplane-Dev-Team\/GigaGet\/commit\/4938289639eb7ce67684b59afb003ca10b139f94","commit_message":"'\\\\\"DownloadManagerService: Optimize logic\\\\\"'","source_code":"package us.shandian.giga.service;\n\nimport android.app.Notification;\nimport android.app.PendingIntent;\nimport android.app.Service;\nimport android.content.Intent;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.os.Binder;\nimport android.os.IBinder;\nimport android.util.Log;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.get.DownloadManager;\nimport us.shandian.giga.get.DownloadMission;\nimport us.shandian.giga.ui.main.MainActivity;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class DownloadManagerService extends Service implements DownloadMission.MissionListener\n{\n\t\n\tprivate static final String TAG = DownloadManagerService.class.getSimpleName();\n\t\n\tprivate DMBinder mBinder;\n\tprivate DownloadManager mManager;\n\tprivate Notification mNotification;\n\tprivate int mRunningCount = 0;\n\n\t@Override\n\tpublic void onCreate() {\n\t\tsuper.onCreate();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"onCreate\");\n\t\t}\n\t\t\n\t\tmBinder = new DMBinder();\n\t\tif (mManager == null) {\n\n\t\t\tif (DEBUG) {\n\t\t\t\tLog.d(TAG, \"mManager == null\");\n\t\t\t}\n\n\t\t\tmManager = new DownloadManager(this, \"\/storage\/sdcard0\/GigaGet\");\n\t\t}\n\t\t\n\t\tIntent i = new Intent();\n\t\ti.setAction(Intent.ACTION_MAIN);\n\t\ti.setClass(this, MainActivity.class);\n\t\tmNotification = new Notification.Builder(this)\n\t\t\t.setContentIntent(PendingIntent.getActivity(this, 0, i, 0))\n\t\t\t.setContentTitle(getString(R.string.msg_running))\n\t\t\t.setContentText(getString(R.string.msg_running_detail))\n\t\t\t.setLargeIcon(((BitmapDrawable) getDrawable(R.drawable.gigaget)).getBitmap())\n\t\t\t.setSmallIcon(android.R.drawable.stat_sys_download)\n\t\t\t.build();\n\t\t\n\t}\n\n\t@Override\n\tpublic int onStartCommand(Intent intent, int flags, int startId) {\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Starting\");\n\t\t}\n\t\t\n\t\treturn START_NOT_STICKY;\n\t}\n\n\t@Override\n\tpublic void onDestroy() {\n\t\tsuper.onDestroy();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Destroying\");\n\t\t}\n\t\t\n\t\tfor (int i = 0; i < mManager.getCount(); i++) {\n\t\t\tmManager.pauseMission(i);\n\t\t}\n\t\t\n\t\tstopForeground(true);\n\t}\n\t\n\t@Override\n\tpublic IBinder onBind(Intent intent) {\n\t\treturn mBinder;\n\t}\n\t\n\n\t@Override\n\tpublic void onProgressUpdate(long done, long total) {\n\t\t\/\/ Do nothing\n\t}\n\n\t@Override\n\tpublic void onFinish() {\n\t\tmRunningCount--;\n\t\tupdateState();\n\t}\n\n\t@Override\n\tpublic void onError(int errCode) {\n\t\tmRunningCount--;\n\t\tupdateState();\n\t}\n\t\n\tprivate void updateState() {\n\t\tif (mRunningCount == 0) {\n\t\t\tstopForeground(true);\n\t\t} else {\n\t\t\tstartForeground(1000, mNotification);\n\t\t}\n\t}\n\t\n\t\n\t\/\/ Wrapper of DownloadManager\n\tpublic class DMBinder extends Binder {\n\t\t\/\/ Do not start missions from outside\n\t\tpublic DownloadManager getDownloadManager() {\n\t\t\treturn mManager;\n\t\t}\n\t\t\n\t\tpublic int startMission(final String url, final String name, final int threads) {\n\t\t\tmRunningCount++;\n\t\t\tupdateState();\n\t\t\treturn mManager.startMission(url, name, threads);\n\t\t}\n\t\t\n\t\tpublic void resumeMission(final int id) {\n\t\t\tmRunningCount++;\n\t\t\tupdateState();\n\t\t\tmManager.resumeMission(id);\n\t\t}\n\t\t\n\t\tpublic void pauseMission(final int id) {\n\t\t\tmRunningCount--;\n\t\t\tupdateState();\n\t\t\tmManager.pauseMission(id);\n\t\t}\n\t\t\n\t}\n\n}\n","target_code":"package us.shandian.giga.service;\n\nimport android.app.Notification;\nimport android.app.PendingIntent;\nimport android.app.Service;\nimport android.content.Intent;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.os.Binder;\nimport android.os.Handler;\nimport android.os.HandlerThread;\nimport android.os.IBinder;\nimport android.os.Message;\nimport android.util.Log;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.get.DownloadManager;\nimport us.shandian.giga.get.DownloadMission;\nimport us.shandian.giga.ui.main.MainActivity;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class DownloadManagerService extends Service implements DownloadMission.MissionListener\n{\n\t\n\tprivate static final String TAG = DownloadManagerService.class.getSimpleName();\n\t\n\tprivate DMBinder mBinder;\n\tprivate DownloadManager mManager;\n\tprivate Notification mNotification;\n\tprivate Handler mHandler;\n\n\t@Override\n\tpublic void onCreate() {\n\t\tsuper.onCreate();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"onCreate\");\n\t\t}\n\t\t\n\t\tmBinder = new DMBinder();\n\t\tif (mManager == null) {\n\n\t\t\tif (DEBUG) {\n\t\t\t\tLog.d(TAG, \"mManager == null\");\n\t\t\t}\n\n\t\t\tmManager = new DownloadManager(this, \"\/storage\/sdcard0\/GigaGet\");\n\t\t}\n\t\t\n\t\tIntent i = new Intent();\n\t\ti.setAction(Intent.ACTION_MAIN);\n\t\ti.setClass(this, MainActivity.class);\n\t\tmNotification = new Notification.Builder(this)\n\t\t\t.setContentIntent(PendingIntent.getActivity(this, 0, i, 0))\n\t\t\t.setContentTitle(getString(R.string.msg_running))\n\t\t\t.setContentText(getString(R.string.msg_running_detail))\n\t\t\t.setLargeIcon(((BitmapDrawable) getDrawable(R.drawable.gigaget)).getBitmap())\n\t\t\t.setSmallIcon(android.R.drawable.stat_sys_download)\n\t\t\t.build();\n\t\t\t\n\t\tHandlerThread thread = new HandlerThread(\"ServiceMessenger\");\n\t\tthread.start();\n\t\t\t\n\t\tmHandler = new Handler(thread.getLooper()) {\n\t\t\t@Override\n\t\t\tpublic void handleMessage(Message msg) {\n\t\t\t\tif (msg.what == 0) {\n\t\t\t\t\tint runningCount = 0;\n\t\t\t\t\t\n\t\t\t\t\tfor (int i = 0; i < mManager.getCount(); i++) {\n\t\t\t\t\t\tif (mManager.getMission(i).running) {\n\t\t\t\t\t\t\trunningCount++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tupdateState(runningCount);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\t\n\t}\n\n\t@Override\n\tpublic int onStartCommand(Intent intent, int flags, int startId) {\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Starting\");\n\t\t}\n\t\t\n\t\treturn START_NOT_STICKY;\n\t}\n\n\t@Override\n\tpublic void onDestroy() {\n\t\tsuper.onDestroy();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Destroying\");\n\t\t}\n\t\t\n\t\tfor (int i = 0; i < mManager.getCount(); i++) {\n\t\t\tmManager.pauseMission(i);\n\t\t}\n\t\t\n\t\tstopForeground(true);\n\t}\n\t\n\t@Override\n\tpublic IBinder onBind(Intent intent) {\n\t\treturn mBinder;\n\t}\n\t\n\n\t@Override\n\tpublic void onProgressUpdate(long done, long total) {\n\t\t\/\/ Do nothing\n\t}\n\n\t@Override\n\tpublic void onFinish() {\n\t\tpostUpdateMessage();\n\t}\n\n\t@Override\n\tpublic void onError(int errCode) {\n\t\tpostUpdateMessage();\n\t}\n\t\n\tprivate void postUpdateMessage() {\n\t\tmHandler.sendEmptyMessage(0);\n\t}\n\t\n\tprivate void updateState(int runningCount) {\n\t\tif (runningCount == 0) {\n\t\t\tstopForeground(true);\n\t\t} else {\n\t\t\tstartForeground(1000, mNotification);\n\t\t}\n\t}\n\t\n\t\n\t\/\/ Wrapper of DownloadManager\n\tpublic class DMBinder extends Binder {\n\t\t\/\/ Do not start missions from outside\n\t\tpublic DownloadManager getDownloadManager() {\n\t\t\treturn mManager;\n\t\t}\n\t\t\n\t\tpublic int startMission(final String url, final String name, final int threads) {\n\t\t\tint ret = mManager.startMission(url, name, threads);\n\t\t\tpostUpdateMessage();\n\t\t\treturn ret;\n\t\t}\n\t\t\n\t\tpublic void resumeMission(final int id) {\n\t\t\tmManager.resumeMission(id);\n\t\t\tpostUpdateMessage();\n\t\t}\n\t\t\n\t\tpublic void pauseMission(final int id) {\n\t\t\tmManager.pauseMission(id);\n\t\t\tpostUpdateMessage();\n\t\t}\n\t\t\n\t}\n\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage us.shandian.giga.service;\n\nimport android.app.Notification;\nimport android.app.PendingIntent;\nimport android.app.Service;\nimport android.content.Intent;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.os.Binder;\nimport android.os.IBinder;\nimport android.util.Log;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.get.DownloadManager;\nimport us.shandian.giga.get.DownloadMission;\nimport us.shandian.giga.ui.main.MainActivity;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class DownloadManagerService extends Service implements DownloadMission.MissionListener\n{\n\t\n\tprivate static final String TAG = DownloadManagerService.class.getSimpleName();\n\t\n\tprivate DMBinder mBinder;\n\tprivate DownloadManager mManager;\n\tprivate Notification mNotification;\n\tprivate int mRunningCount = 0;\n\n\t@Override\n\tpublic void onCreate() {\n\t\tsuper.onCreate();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"onCreate\");\n\t\t}\n\t\t\n\t\tmBinder = new DMBinder();\n\t\tif (mManager == null) {\n\n\t\t\tif (DEBUG) {\n\t\t\t\tLog.d(TAG, \"mManager == null\");\n\t\t\t}\n\n\t\t\tmManager = new DownloadManager(this, \"\/storage\/sdcard0\/GigaGet\");\n\t\t}\n\t\t\n\t\tIntent i = new Intent();\n\t\ti.setAction(Intent.ACTION_MAIN);\n\t\ti.setClass(this, MainActivity.class);\n\t\tmNotification = new Notification.Builder(this)\n\t\t\t.setContentIntent(PendingIntent.getActivity(this, 0, i, 0))\n\t\t\t.setContentTitle(getString(R.string.msg_running))\n\t\t\t.setContentText(getString(R.string.msg_running_detail))\n\t\t\t.setLargeIcon(((BitmapDrawable) getDrawable(R.drawable.gigaget)).getBitmap())\n\t\t\t.setSmallIcon(android.R.drawable.stat_sys_download)\n\t\t\t.build();\n\t\t\n\t}\n\n\t@Override\n\tpublic int onStartCommand(Intent intent, int flags, int startId) {\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Starting\");\n\t\t}\n\t\t\n\t\treturn START_NOT_STICKY;\n\t}\n\n\t@Override\n\tpublic void onDestroy() {\n\t\tsuper.onDestroy();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Destroying\");\n\t\t}\n\t\t\n\t\tfor (int i = 0; i < mManager.getCount(); i++) {\n\t\t\tmManager.pauseMission(i);\n\t\t}\n\t\t\n\t\tstopForeground(true);\n\t}\n\t\n\t@Override\n\tpublic IBinder onBind(Intent intent) {\n\t\treturn mBinder;\n\t}\n\t\n\n\t@Override\n\tpublic void onProgressUpdate(long done, long total) {\n\t\t\/\/ Do nothing\n\t}\n\n\t@Override\n\tpublic void onFinish() {\n\t\tmRunningCount--;\n\t\tupdateState();\n\t}\n\n\t@Override\n\tpublic void onError(int errCode) {\n\t\tmRunningCount--;\n\t\tupdateState();\n\t}\n\t\n\tprivate void updateState() {\n\t\tif (mRunningCount == 0) {\n\t\t\tstopForeground(true);\n\t\t} else {\n\t\t\tstartForeground(1000, mNotification);\n\t\t}\n\t}\n\t\n\t\n\t\/\/ Wrapper of DownloadManager\n\tpublic class DMBinder extends Binder {\n\t\t\/\/ Do not start missions from outside\n\t\tpublic DownloadManager getDownloadManager() {\n\t\t\treturn mManager;\n\t\t}\n\t\t\n\t\tpublic int startMission(final String url, final String name, final int threads) {\n\t\t\tmRunningCount++;\n\t\t\tupdateState();\n\t\t\treturn mManager.startMission(url, name, threads);\n\t\t}\n\t\t\n\t\tpublic void resumeMission(final int id) {\n\t\t\tmRunningCount++;\n\t\t\tupdateState();\n\t\t\tmManager.resumeMission(id);\n\t\t}\n\t\t\n\t\tpublic void pauseMission(final int id) {\n\t\t\tmRunningCount--;\n\t\t\tupdateState();\n\t\t\tmManager.pauseMission(id);\n\t\t}\n\t\t\n\t}\n\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage us.shandian.giga.service;\n\nimport android.app.Notification;\nimport android.app.PendingIntent;\nimport android.app.Service;\nimport android.content.Intent;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.os.Binder;\nimport android.os.IBinder;\nimport android.util.Log;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.get.DownloadManager;\nimport us.shandian.giga.get.DownloadMission;\nimport us.shandian.giga.ui.main.MainActivity;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class DownloadManagerService extends Service implements DownloadMission.MissionListener\n{\n\t\n\tprivate static final String TAG = DownloadManagerService.class.getSimpleName();\n\t\n\tprivate DMBinder mBinder;\n\tprivate DownloadManager mManager;\n\tprivate Notification mNotification;\n\tprivate int mRunningCount = 0;\n\n\t@Override\n\tpublic void onCreate() {\n\t\tsuper.onCreate();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"onCreate\");\n\t\t}\n\t\t\n\t\tmBinder = new DMBinder();\n\t\tif (mManager == null) {\n\n\t\t\tif (DEBUG) {\n\t\t\t\tLog.d(TAG, \"mManager == null\");\n\t\t\t}\n\n\t\t\tmManager = new DownloadManager(this, \"\/storage\/sdcard0\/GigaGet\");\n\t\t}\n\t\t\n\t\tIntent i = new Intent();\n\t\ti.setAction(Intent.ACTION_MAIN);\n\t\ti.setClass(this, MainActivity.class);\n\t\tmNotification = new Notification.Builder(this)\n\t\t\t.setContentIntent(PendingIntent.getActivity(this, 0, i, 0))\n\t\t\t.setContentTitle(getString(R.string.msg_running))\n\t\t\t.setContentText(getString(R.string.msg_running_detail))\n\t\t\t.setLargeIcon(((BitmapDrawable) getDrawable(R.drawable.gigaget)).getBitmap())\n\t\t\t.setSmallIcon(android.R.drawable.stat_sys_download)\n\t\t\t.build();\n\t\t\n\t}\n\n\t@Override\n\tpublic int onStartCommand(Intent intent, int flags, int startId) {\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Starting\");\n\t\t}\n\t\t\n\t\treturn START_NOT_STICKY;\n\t}\n\n\t@Override\n\tpublic void onDestroy() {\n\t\tsuper.onDestroy();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Destroying\");\n\t\t}\n\t\t\n\t\tfor (int i = 0; i < mManager.getCount(); i++) {\n\t\t\tmManager.pauseMission(i);\n\t\t}\n\t\t\n\t\tstopForeground(true);\n\t}\n\t\n\t@Override\n\tpublic IBinder onBind(Intent intent) {\n\t\treturn mBinder;\n\t}\n\t\n\n\t@Override\n\tpublic void onProgressUpdate(long done, long total) {\n\t\t\/\/ Do nothing\n\t}\n\n\t@Override\n\tpublic void onFinish() {\n\t\tmRunningCount--;\n\t\tupdateState();\n\t}\n\n\t@Override\n\tpublic void onError(int errCode) {\n\t\tmRunningCount--;\n\t\tupdateState();\n\t}\n\t\n\tprivate void updateState() {\n\t\tif (mRunningCount == 0) {\n\t\t\tstopForeground(true);\n\t\t} else {\n\t\t\tstartForeground(1000, mNotification);\n\t\t}\n\t}\n\t\n\t\n\t\/\/ Wrapper of DownloadManager\n\tpublic class DMBinder extends Binder {\n\t\t\/\/ Do not start missions from outside\n\t\tpublic DownloadManager getDownloadManager() {\n\t\t\treturn mManager;\n\t\t}\n\t\t\n\t\tpublic int startMission(final String url, final String name, final int threads) {\n\t\t\tmRunningCount++;\n\t\t\tupdateState();\n\t\t\treturn mManager.startMission(url, name, threads);\n\t\t}\n\t\t\n\t\tpublic void resumeMission(final int id) {\n\t\t\tmRunningCount++;\n\t\t\tupdateState();\n\t\t\tmManager.resumeMission(id);\n\t\t}\n\t\t\n\t\tpublic void pauseMission(final int id) {\n\t\t\tmRunningCount--;\n\t\t\tupdateState();\n\t\t\tmManager.pauseMission(id);\n\t\t}\n\t\t\n\t}\n\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage us.shandian.giga.service;\n\nimport android.app.Notification;\nimport android.app.PendingIntent;\nimport android.app.Service;\nimport android.content.Intent;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.os.Binder;\nimport android.os.IBinder;\nimport android.util.Log;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.get.DownloadManager;\nimport us.shandian.giga.get.DownloadMission;\nimport us.shandian.giga.ui.main.MainActivity;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class DownloadManagerService extends Service implements DownloadMission.MissionListener\n{\n\t\n\tprivate static final String TAG = DownloadManagerService.class.getSimpleName();\n\t\n\tprivate DMBinder mBinder;\n\tprivate DownloadManager mManager;\n\tprivate Notification mNotification;\n\tprivate int mRunningCount = 0;\n\n\t@Override\n\tpublic void onCreate() {\n\t\tsuper.onCreate();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"onCreate\");\n\t\t}\n\t\t\n\t\tmBinder = new DMBinder();\n\t\tif (mManager == null) {\n\n\t\t\tif (DEBUG) {\n\t\t\t\tLog.d(TAG, \"mManager == null\");\n\t\t\t}\n\n\t\t\tmManager = new DownloadManager(this, \"\/storage\/sdcard0\/GigaGet\");\n\t\t}\n\t\t\n\t\tIntent i = new Intent();\n\t\ti.setAction(Intent.ACTION_MAIN);\n\t\ti.setClass(this, MainActivity.class);\n\t\tmNotification = new Notification.Builder(this)\n\t\t\t.setContentIntent(PendingIntent.getActivity(this, 0, i, 0))\n\t\t\t.setContentTitle(getString(R.string.msg_running))\n\t\t\t.setContentText(getString(R.string.msg_running_detail))\n\t\t\t.setLargeIcon(((BitmapDrawable) getDrawable(R.drawable.gigaget)).getBitmap())\n\t\t\t.setSmallIcon(android.R.drawable.stat_sys_download)\n\t\t\t.build();\n\t\t\n\t}\n\n\t@Override\n\tpublic int onStartCommand(Intent intent, int flags, int startId) {\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Starting\");\n\t\t}\n\t\t\n\t\treturn START_NOT_STICKY;\n\t}\n\n\t@Override\n\tpublic void onDestroy() {\n\t\tsuper.onDestroy();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Destroying\");\n\t\t}\n\t\t\n\t\tfor (int i = 0; i < mManager.getCount(); i++) {\n\t\t\tmManager.pauseMission(i);\n\t\t}\n\t\t\n\t\tstopForeground(true);\n\t}\n\t\n\t@Override\n\tpublic IBinder onBind(Intent intent) {\n\t\treturn mBinder;\n\t}\n\t\n\n\t@Override\n\tpublic void onProgressUpdate(long done, long total) {\n\t\t\/\/ Do nothing\n\t}\n\n\t@Override\n\tpublic void onFinish() {\n\t\tmRunningCount--;\n\t\tupdateState();\n\t}\n\n\t@Override\n\tpublic void onError(int errCode) {\n\t\tmRunningCount--;\n\t\tupdateState();\n\t}\n\t\n\tprivate void updateState() {\n\t\tif (mRunningCount == 0) {\n\t\t\tstopForeground(true);\n\t\t} else {\n\t\t\tstartForeground(1000, mNotification);\n\t\t}\n\t}\n\t\n\t\n\t\/\/ Wrapper of DownloadManager\n\tpublic class DMBinder extends Binder {\n\t\t\/\/ Do not start missions from outside\n\t\tpublic DownloadManager getDownloadManager() {\n\t\t\treturn mManager;\n\t\t}\n\t\t\n\t\tpublic int startMission(final String url, final String name, final int threads) {\n\t\t\tmRunningCount++;\n\t\t\tupdateState();\n\t\t\treturn mManager.startMission(url, name, threads);\n\t\t}\n\t\t\n\t\tpublic void resumeMission(final int id) {\n\t\t\tmRunningCount++;\n\t\t\tupdateState();\n\t\t\tmManager.resumeMission(id);\n\t\t}\n\t\t\n\t\tpublic void pauseMission(final int id) {\n\t\t\tmRunningCount--;\n\t\t\tupdateState();\n\t\t\tmManager.pauseMission(id);\n\t\t}\n\t\t\n\t}\n\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the code to optimize the DownloadManagerService logic and improve execution time. Write the entire code and no other text in the response.\n\n### Concepts:\n[+] android.os.Handler\n[+] android.os.HandlerThread\n[+] android.os.Message\n[implement] void postUpdateMessage()\n[in] onCreate function\n[in] onFinish function\n[in] onError function\n[in] updateState function\n[in] DMBinder.startMission function\n[in] DMBinder.resumeMission function\n[in] DMBinder.pauseMission function\n\n### Given program:\n```java\npackage us.shandian.giga.service;\n\nimport android.app.Notification;\nimport android.app.PendingIntent;\nimport android.app.Service;\nimport android.content.Intent;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.os.Binder;\nimport android.os.IBinder;\nimport android.util.Log;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.get.DownloadManager;\nimport us.shandian.giga.get.DownloadMission;\nimport us.shandian.giga.ui.main.MainActivity;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class DownloadManagerService extends Service implements DownloadMission.MissionListener\n{\n\t\n\tprivate static final String TAG = DownloadManagerService.class.getSimpleName();\n\t\n\tprivate DMBinder mBinder;\n\tprivate DownloadManager mManager;\n\tprivate Notification mNotification;\n\tprivate int mRunningCount = 0;\n\n\t@Override\n\tpublic void onCreate() {\n\t\tsuper.onCreate();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"onCreate\");\n\t\t}\n\t\t\n\t\tmBinder = new DMBinder();\n\t\tif (mManager == null) {\n\n\t\t\tif (DEBUG) {\n\t\t\t\tLog.d(TAG, \"mManager == null\");\n\t\t\t}\n\n\t\t\tmManager = new DownloadManager(this, \"\/storage\/sdcard0\/GigaGet\");\n\t\t}\n\t\t\n\t\tIntent i = new Intent();\n\t\ti.setAction(Intent.ACTION_MAIN);\n\t\ti.setClass(this, MainActivity.class);\n\t\tmNotification = new Notification.Builder(this)\n\t\t\t.setContentIntent(PendingIntent.getActivity(this, 0, i, 0))\n\t\t\t.setContentTitle(getString(R.string.msg_running))\n\t\t\t.setContentText(getString(R.string.msg_running_detail))\n\t\t\t.setLargeIcon(((BitmapDrawable) getDrawable(R.drawable.gigaget)).getBitmap())\n\t\t\t.setSmallIcon(android.R.drawable.stat_sys_download)\n\t\t\t.build();\n\t\t\n\t}\n\n\t@Override\n\tpublic int onStartCommand(Intent intent, int flags, int startId) {\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Starting\");\n\t\t}\n\t\t\n\t\treturn START_NOT_STICKY;\n\t}\n\n\t@Override\n\tpublic void onDestroy() {\n\t\tsuper.onDestroy();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Destroying\");\n\t\t}\n\t\t\n\t\tfor (int i = 0; i < mManager.getCount(); i++) {\n\t\t\tmManager.pauseMission(i);\n\t\t}\n\t\t\n\t\tstopForeground(true);\n\t}\n\t\n\t@Override\n\tpublic IBinder onBind(Intent intent) {\n\t\treturn mBinder;\n\t}\n\t\n\n\t@Override\n\tpublic void onProgressUpdate(long done, long total) {\n\t\t\/\/ Do nothing\n\t}\n\n\t@Override\n\tpublic void onFinish() {\n\t\tmRunningCount--;\n\t\tupdateState();\n\t}\n\n\t@Override\n\tpublic void onError(int errCode) {\n\t\tmRunningCount--;\n\t\tupdateState();\n\t}\n\t\n\tprivate void updateState() {\n\t\tif (mRunningCount == 0) {\n\t\t\tstopForeground(true);\n\t\t} else {\n\t\t\tstartForeground(1000, mNotification);\n\t\t}\n\t}\n\t\n\t\n\t\/\/ Wrapper of DownloadManager\n\tpublic class DMBinder extends Binder {\n\t\t\/\/ Do not start missions from outside\n\t\tpublic DownloadManager getDownloadManager() {\n\t\t\treturn mManager;\n\t\t}\n\t\t\n\t\tpublic int startMission(final String url, final String name, final int threads) {\n\t\t\tmRunningCount++;\n\t\t\tupdateState();\n\t\t\treturn mManager.startMission(url, name, threads);\n\t\t}\n\t\t\n\t\tpublic void resumeMission(final int id) {\n\t\t\tmRunningCount++;\n\t\t\tupdateState();\n\t\t\tmManager.resumeMission(id);\n\t\t}\n\t\t\n\t\tpublic void pauseMission(final int id) {\n\t\t\tmRunningCount--;\n\t\t\tupdateState();\n\t\t\tmManager.pauseMission(id);\n\t\t}\n\t\t\n\t}\n\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = startPort + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n executor.execute(new ScanPortsRunnable(ip, previousStart, stopPort, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt((int) ((((stopPort - startPort) \/ NUM_THREADS) \/ 1.5)) + 1) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n executor.execute(new ScanPortsRunnable(ip, previousStart, stopPort, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt((int) ((((stopPort - startPort) \/ NUM_THREADS) \/ 1.5)) + 1) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = (startPort - 1) + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n executor.execute(new ScanPortsRunnable(ip, previousStart, stopPort, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt((int) ((((stopPort - startPort) \/ NUM_THREADS) \/ 1.5)) + 1) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.async;\n\nimport android.content.Context;\nimport android.os.AsyncTask;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.runnable.ScanPortsRunnable;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.lang.ref.WeakReference;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Random;\nimport java.util.concurrent.ScheduledThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\npublic class ScanPortsAsyncTask extends AsyncTask {\n private final WeakReference delegate;\n\n \/**\n * Constructor to set the delegate\n *\n * @param delegate Called when a port scan has finished\n *\/\n public ScanPortsAsyncTask(HostAsyncResponse delegate) {\n this.delegate = new WeakReference<>(delegate);\n }\n\n \/**\n * Chunks the ports selected for scanning and starts the process\n * Chunked ports are scanned in parallel\n *\n * @param params IP address, start port, and stop port\n *\/\n @Override\n protected Void doInBackground(Object... params) {\n String ip = (String) params[0];\n int startPort = (int) params[1];\n int stopPort = (int) params[2];\n int timeout = (int) params[3];\n\n HostAsyncResponse activity = delegate.get();\n if (activity != null) {\n final int NUM_THREADS = UserPreference.getPortScanThreads((Context) activity);\n\n try {\n InetAddress address = InetAddress.getByName(ip);\n ip = address.getHostAddress();\n } catch (UnknownHostException e) {\n activity.processFinish(false);\n return null;\n }\n\n ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(NUM_THREADS);\n Random rand = new Random();\n\n int chunk = (int) Math.ceil((double) (stopPort - startPort) \/ NUM_THREADS);\n int previousStart = startPort;\n int previousStop = startPort + chunk;\n\n for (int i = 0; i < NUM_THREADS; i++) {\n if (previousStop >= stopPort) {\n executor.execute(new ScanPortsRunnable(ip, previousStart, stopPort, timeout, delegate));\n break;\n }\n\n int schedule = rand.nextInt((int) ((((stopPort - startPort) \/ NUM_THREADS) \/ 1.5)) + 1) + 1;\n executor.schedule(new ScanPortsRunnable(ip, previousStart, previousStop, timeout, delegate), i % schedule, TimeUnit.SECONDS);\n\n previousStart = previousStop + 1;\n previousStop = previousStop + chunk;\n }\n\n executor.shutdown();\n\n try {\n executor.awaitTermination(5, TimeUnit.MINUTES);\n executor.shutdownNow();\n } catch (InterruptedException ignored) {\n }\n\n activity.processFinish(true);\n }\n\n return null;\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/leonardbos\/FirefoxFocusASV\/commit\/3d53ff2966bd527e43c63a4c4b5ef744e29af862","commit_message":"'\\\\\"Avoid URI processing if userinfo doesn\\'t exit\\\\n\\\\nThis seems slightly more efficient for the most common use case\\\\n(i.e. most of the time there\\'s no userinfo).\\\\n\\\\\"'","source_code":"\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.utils;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.text.TextUtils;\n\nimport org.mozilla.focus.BuildConfig;\nimport org.mozilla.focus.search.SearchEngine;\nimport org.mozilla.focus.search.SearchEngineManager;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\npublic class UrlUtils {\n public static String normalize(String input) {\n Uri uri = Uri.parse(input);\n\n if (TextUtils.isEmpty(uri.getScheme())) {\n uri = Uri.parse(\"http:\/\/\" + input);\n }\n\n return uri.toString();\n }\n\n \/**\n * Is the given string a URL or should we perform a search?\n *\n * TODO: This is a super simple and probably stupid implementation.\n *\/\n public static boolean isUrl(String url) {\n if (url.contains(\" \")) {\n return false;\n }\n\n return url.contains(\".\") || url.contains(\":\");\n }\n\n public static boolean isSearchQuery(String text) {\n return text.contains(\" \");\n }\n\n public static String createSearchUrl(Context context, String searchTerm) {\n final SearchEngine searchEngine = SearchEngineManager.getInstance()\n .getDefaultSearchEngine(context);\n\n return searchEngine.buildSearchUrl(searchTerm);\n }\n\n public static String stripUserInfo(String url) {\n try {\n URI uri = new URI(url);\n final String userInfo = uri.getUserInfo();\n if (userInfo != null) {\n \/\/ Strip the userInfo to minimise spoofing ability. This only affects what's shown\n \/\/ during browsing, this information isn't used when we start editing the URL:\n uri = new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());\n }\n\n return uri.toString();\n } catch (URISyntaxException e) {\n \/\/ In general this shouldn't happen. But there are some special cases that URI can't handle,\n \/\/ such as \"http:\" by itself. We allow those individual special cases, but we still want\n \/\/ to catch other special syntaxes in dev builds if possible\n if (url.equals(\"http:\") ||\n url.equals(\"https:\") ||\n url.equals(\"file:\")) {\n return url;\n }\n\n if (BuildConfig.DEBUG) {\n \/\/ WebView should always have supplied a valid URL\n throw new IllegalStateException(\"WebView is expected to always supply a valid URL\");\n } else {\n return url;\n }\n }\n }\n\n public static boolean focusSupportURLProtocol(final String url) {\n return (!url.startsWith(\"http:\")) &&\n (!url.startsWith(\"https:\")) &&\n (!url.startsWith(\"file:\")) &&\n (!url.startsWith(\"data:\")) &&\n (!url.startsWith(\"error:\"));\n }\n}\n","target_code":"\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.utils;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.text.TextUtils;\n\nimport org.mozilla.focus.BuildConfig;\nimport org.mozilla.focus.search.SearchEngine;\nimport org.mozilla.focus.search.SearchEngineManager;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\npublic class UrlUtils {\n public static String normalize(String input) {\n Uri uri = Uri.parse(input);\n\n if (TextUtils.isEmpty(uri.getScheme())) {\n uri = Uri.parse(\"http:\/\/\" + input);\n }\n\n return uri.toString();\n }\n\n \/**\n * Is the given string a URL or should we perform a search?\n *\n * TODO: This is a super simple and probably stupid implementation.\n *\/\n public static boolean isUrl(String url) {\n if (url.contains(\" \")) {\n return false;\n }\n\n return url.contains(\".\") || url.contains(\":\");\n }\n\n public static boolean isSearchQuery(String text) {\n return text.contains(\" \");\n }\n\n public static String createSearchUrl(Context context, String searchTerm) {\n final SearchEngine searchEngine = SearchEngineManager.getInstance()\n .getDefaultSearchEngine(context);\n\n return searchEngine.buildSearchUrl(searchTerm);\n }\n\n public static String stripUserInfo(String url) {\n try {\n URI uri = new URI(url);\n\n final String userInfo = uri.getUserInfo();\n if (userInfo == null) {\n return url;\n }\n\n \/\/ Strip the userInfo to minimise spoofing ability. This only affects what's shown\n \/\/ during browsing, this information isn't used when we start editing the URL:\n uri = new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());\n\n return uri.toString();\n } catch (URISyntaxException e) {\n \/\/ In general this shouldn't happen. But there are some special cases that URI can't handle,\n \/\/ such as \"http:\" by itself. We allow those individual special cases, but we still want\n \/\/ to catch other special syntaxes in dev builds if possible\n if (url.equals(\"http:\") ||\n url.equals(\"https:\") ||\n url.equals(\"file:\")) {\n return url;\n }\n\n if (BuildConfig.DEBUG) {\n \/\/ WebView should always have supplied a valid URL\n throw new IllegalStateException(\"WebView is expected to always supply a valid URL\");\n } else {\n return url;\n }\n }\n }\n\n public static boolean focusSupportURLProtocol(final String url) {\n return (!url.startsWith(\"http:\")) &&\n (!url.startsWith(\"https:\")) &&\n (!url.startsWith(\"file:\")) &&\n (!url.startsWith(\"data:\")) &&\n (!url.startsWith(\"error:\"));\n }\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.utils;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.text.TextUtils;\n\nimport org.mozilla.focus.BuildConfig;\nimport org.mozilla.focus.search.SearchEngine;\nimport org.mozilla.focus.search.SearchEngineManager;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\npublic class UrlUtils {\n public static String normalize(String input) {\n Uri uri = Uri.parse(input);\n\n if (TextUtils.isEmpty(uri.getScheme())) {\n uri = Uri.parse(\"http:\/\/\" + input);\n }\n\n return uri.toString();\n }\n\n \/**\n * Is the given string a URL or should we perform a search?\n *\n * TODO: This is a super simple and probably stupid implementation.\n *\/\n public static boolean isUrl(String url) {\n if (url.contains(\" \")) {\n return false;\n }\n\n return url.contains(\".\") || url.contains(\":\");\n }\n\n public static boolean isSearchQuery(String text) {\n return text.contains(\" \");\n }\n\n public static String createSearchUrl(Context context, String searchTerm) {\n final SearchEngine searchEngine = SearchEngineManager.getInstance()\n .getDefaultSearchEngine(context);\n\n return searchEngine.buildSearchUrl(searchTerm);\n }\n\n public static String stripUserInfo(String url) {\n try {\n URI uri = new URI(url);\n final String userInfo = uri.getUserInfo();\n if (userInfo != null) {\n \/\/ Strip the userInfo to minimise spoofing ability. This only affects what's shown\n \/\/ during browsing, this information isn't used when we start editing the URL:\n uri = new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());\n }\n\n return uri.toString();\n } catch (URISyntaxException e) {\n \/\/ In general this shouldn't happen. But there are some special cases that URI can't handle,\n \/\/ such as \"http:\" by itself. We allow those individual special cases, but we still want\n \/\/ to catch other special syntaxes in dev builds if possible\n if (url.equals(\"http:\") ||\n url.equals(\"https:\") ||\n url.equals(\"file:\")) {\n return url;\n }\n\n if (BuildConfig.DEBUG) {\n \/\/ WebView should always have supplied a valid URL\n throw new IllegalStateException(\"WebView is expected to always supply a valid URL\");\n } else {\n return url;\n }\n }\n }\n\n public static boolean focusSupportURLProtocol(final String url) {\n return (!url.startsWith(\"http:\")) &&\n (!url.startsWith(\"https:\")) &&\n (!url.startsWith(\"file:\")) &&\n (!url.startsWith(\"data:\")) &&\n (!url.startsWith(\"error:\"));\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.utils;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.text.TextUtils;\n\nimport org.mozilla.focus.BuildConfig;\nimport org.mozilla.focus.search.SearchEngine;\nimport org.mozilla.focus.search.SearchEngineManager;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\npublic class UrlUtils {\n public static String normalize(String input) {\n Uri uri = Uri.parse(input);\n\n if (TextUtils.isEmpty(uri.getScheme())) {\n uri = Uri.parse(\"http:\/\/\" + input);\n }\n\n return uri.toString();\n }\n\n \/**\n * Is the given string a URL or should we perform a search?\n *\n * TODO: This is a super simple and probably stupid implementation.\n *\/\n public static boolean isUrl(String url) {\n if (url.contains(\" \")) {\n return false;\n }\n\n return url.contains(\".\") || url.contains(\":\");\n }\n\n public static boolean isSearchQuery(String text) {\n return text.contains(\" \");\n }\n\n public static String createSearchUrl(Context context, String searchTerm) {\n final SearchEngine searchEngine = SearchEngineManager.getInstance()\n .getDefaultSearchEngine(context);\n\n return searchEngine.buildSearchUrl(searchTerm);\n }\n\n public static String stripUserInfo(String url) {\n try {\n URI uri = new URI(url);\n final String userInfo = uri.getUserInfo();\n if (userInfo != null) {\n \/\/ Strip the userInfo to minimise spoofing ability. This only affects what's shown\n \/\/ during browsing, this information isn't used when we start editing the URL:\n uri = new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());\n }\n\n return uri.toString();\n } catch (URISyntaxException e) {\n \/\/ In general this shouldn't happen. But there are some special cases that URI can't handle,\n \/\/ such as \"http:\" by itself. We allow those individual special cases, but we still want\n \/\/ to catch other special syntaxes in dev builds if possible\n if (url.equals(\"http:\") ||\n url.equals(\"https:\") ||\n url.equals(\"file:\")) {\n return url;\n }\n\n if (BuildConfig.DEBUG) {\n \/\/ WebView should always have supplied a valid URL\n throw new IllegalStateException(\"WebView is expected to always supply a valid URL\");\n } else {\n return url;\n }\n }\n }\n\n public static boolean focusSupportURLProtocol(final String url) {\n return (!url.startsWith(\"http:\")) &&\n (!url.startsWith(\"https:\")) &&\n (!url.startsWith(\"file:\")) &&\n (!url.startsWith(\"data:\")) &&\n (!url.startsWith(\"error:\"));\n }\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.utils;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.text.TextUtils;\n\nimport org.mozilla.focus.BuildConfig;\nimport org.mozilla.focus.search.SearchEngine;\nimport org.mozilla.focus.search.SearchEngineManager;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\npublic class UrlUtils {\n public static String normalize(String input) {\n Uri uri = Uri.parse(input);\n\n if (TextUtils.isEmpty(uri.getScheme())) {\n uri = Uri.parse(\"http:\/\/\" + input);\n }\n\n return uri.toString();\n }\n\n \/**\n * Is the given string a URL or should we perform a search?\n *\n * TODO: This is a super simple and probably stupid implementation.\n *\/\n public static boolean isUrl(String url) {\n if (url.contains(\" \")) {\n return false;\n }\n\n return url.contains(\".\") || url.contains(\":\");\n }\n\n public static boolean isSearchQuery(String text) {\n return text.contains(\" \");\n }\n\n public static String createSearchUrl(Context context, String searchTerm) {\n final SearchEngine searchEngine = SearchEngineManager.getInstance()\n .getDefaultSearchEngine(context);\n\n return searchEngine.buildSearchUrl(searchTerm);\n }\n\n public static String stripUserInfo(String url) {\n try {\n URI uri = new URI(url);\n final String userInfo = uri.getUserInfo();\n if (userInfo != null) {\n \/\/ Strip the userInfo to minimise spoofing ability. This only affects what's shown\n \/\/ during browsing, this information isn't used when we start editing the URL:\n uri = new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());\n }\n\n return uri.toString();\n } catch (URISyntaxException e) {\n \/\/ In general this shouldn't happen. But there are some special cases that URI can't handle,\n \/\/ such as \"http:\" by itself. We allow those individual special cases, but we still want\n \/\/ to catch other special syntaxes in dev builds if possible\n if (url.equals(\"http:\") ||\n url.equals(\"https:\") ||\n url.equals(\"file:\")) {\n return url;\n }\n\n if (BuildConfig.DEBUG) {\n \/\/ WebView should always have supplied a valid URL\n throw new IllegalStateException(\"WebView is expected to always supply a valid URL\");\n } else {\n return url;\n }\n }\n }\n\n public static boolean focusSupportURLProtocol(final String url) {\n return (!url.startsWith(\"http:\")) &&\n (!url.startsWith(\"https:\")) &&\n (!url.startsWith(\"file:\")) &&\n (!url.startsWith(\"data:\")) &&\n (!url.startsWith(\"error:\"));\n }\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the code to improve execution time given the most common scenario is that there is no userInfo. Write the entire code and no other text in the response.\n\n### Concepts:\n[in] stripUserInfo function\n\n### Given program:\n```java\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.utils;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.text.TextUtils;\n\nimport org.mozilla.focus.BuildConfig;\nimport org.mozilla.focus.search.SearchEngine;\nimport org.mozilla.focus.search.SearchEngineManager;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\npublic class UrlUtils {\n public static String normalize(String input) {\n Uri uri = Uri.parse(input);\n\n if (TextUtils.isEmpty(uri.getScheme())) {\n uri = Uri.parse(\"http:\/\/\" + input);\n }\n\n return uri.toString();\n }\n\n \/**\n * Is the given string a URL or should we perform a search?\n *\n * TODO: This is a super simple and probably stupid implementation.\n *\/\n public static boolean isUrl(String url) {\n if (url.contains(\" \")) {\n return false;\n }\n\n return url.contains(\".\") || url.contains(\":\");\n }\n\n public static boolean isSearchQuery(String text) {\n return text.contains(\" \");\n }\n\n public static String createSearchUrl(Context context, String searchTerm) {\n final SearchEngine searchEngine = SearchEngineManager.getInstance()\n .getDefaultSearchEngine(context);\n\n return searchEngine.buildSearchUrl(searchTerm);\n }\n\n public static String stripUserInfo(String url) {\n try {\n URI uri = new URI(url);\n final String userInfo = uri.getUserInfo();\n if (userInfo != null) {\n \/\/ Strip the userInfo to minimise spoofing ability. This only affects what's shown\n \/\/ during browsing, this information isn't used when we start editing the URL:\n uri = new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());\n }\n\n return uri.toString();\n } catch (URISyntaxException e) {\n \/\/ In general this shouldn't happen. But there are some special cases that URI can't handle,\n \/\/ such as \"http:\" by itself. We allow those individual special cases, but we still want\n \/\/ to catch other special syntaxes in dev builds if possible\n if (url.equals(\"http:\") ||\n url.equals(\"https:\") ||\n url.equals(\"file:\")) {\n return url;\n }\n\n if (BuildConfig.DEBUG) {\n \/\/ WebView should always have supplied a valid URL\n throw new IllegalStateException(\"WebView is expected to always supply a valid URL\");\n } else {\n return url;\n }\n }\n }\n\n public static boolean focusSupportURLProtocol(final String url) {\n return (!url.startsWith(\"http:\")) &&\n (!url.startsWith(\"https:\")) &&\n (!url.startsWith(\"file:\")) &&\n (!url.startsWith(\"data:\")) &&\n (!url.startsWith(\"error:\"));\n }\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for (int i = this.startPort; i <= this.stopPort; i++) {\n if (i % 75 == 0) {\n this.delegate.processFinish(1);\n }\n\n HashMap portData = new HashMap<>();\n BufferedReader in;\n String data = null;\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n\n try {\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n\n if (i == 22) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n data = in.readLine();\n in.close();\n } else if (i == 80 || i == 443 || i == 8080) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\\r\\nHost: \" + this.ip + \"\\r\\n\");\n\n char[] buffer = new char[1024];\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if (data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n } else if (data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n } else if (data.contains(\"nginx\")) {\n data = \"Nginx\";\n } else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n } catch (IOException ignored) {\n }\n }\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for (int i = this.startPort; i <= this.stopPort; i++) {\n try {\n if (i % 75 == 0) {\n this.delegate.processFinish(1);\n }\n\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n\n HashMap portData = new HashMap<>();\n BufferedReader in;\n String data = null;\n\n if (i == 22) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n data = in.readLine();\n in.close();\n } else if (i == 80 || i == 443 || i == 8080) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\\r\\nHost: \" + this.ip + \"\\r\\n\");\n\n char[] buffer = new char[1024];\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if (data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n } else if (data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n } else if (data.contains(\"nginx\")) {\n data = \"Nginx\";\n } else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n } catch (IOException ignored) {\n }\n }\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for (int i = this.startPort; i <= this.stopPort; i++) {\n try {\n if (i % 75 == 0) {\n this.delegate.processFinish(1);\n }\n\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n\n HashMap portData = new HashMap<>();\n BufferedReader in;\n String data = null;\n\n if (i == 22) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n data = in.readLine();\n in.close();\n } else if (i == 80 || i == 443 || i == 8080) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\\r\\nHost: \" + this.ip + \"\\r\\n\");\n\n char[] buffer = new char[1024];\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if (data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n } else if (data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n } else if (data.contains(\"nginx\")) {\n data = \"Nginx\";\n } else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n } catch (IOException ignored) {\n }\n }\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.runnable;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.util.HashMap;\n\npublic class ScanPortsRunnable implements Runnable {\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n \/**\n * Constructor to set the necessary data to perform a port scan\n *\n * @param ip IP address\n * @param startPort Port to start scanning at\n * @param stopPort Port to stop scanning at\n * @param delegate Called when this chunk of ports has finished scanning\n *\/\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n \/**\n * Starts the port scan\n *\/\n @Override\n public void run() {\n for (int i = this.startPort; i <= this.stopPort; i++) {\n if (i % 75 == 0) {\n this.delegate.processFinish(1);\n }\n\n HashMap portData = new HashMap<>();\n BufferedReader in;\n String data = null;\n Socket socket = new Socket();\n socket.setPerformancePreferences(1, 0, 0);\n\n try {\n socket.setTcpNoDelay(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n\n if (i == 22) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n data = in.readLine();\n in.close();\n } else if (i == 80 || i == 443 || i == 8080) {\n in = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n PrintWriter out = new PrintWriter(socket.getOutputStream(), true);\n out.println(\"GET \/ HTTP\/1.1\\r\\nHost: \" + this.ip + \"\\r\\n\");\n\n char[] buffer = new char[1024];\n in.read(buffer, 0, 1024);\n out.close();\n in.close();\n data = new String(buffer).toLowerCase();\n if (data.contains(\"apache\") || data.contains(\"httpd\")) {\n data = \"Apache\";\n } else if (data.contains(\"iis\") || data.contains(\"microsoft\")) {\n data = \"IIS\";\n } else if (data.contains(\"nginx\")) {\n data = \"Nginx\";\n } else {\n data = null;\n }\n }\n\n portData.put(i, data);\n socket.close();\n\n this.delegate.processFinish(portData);\n } catch (IOException ignored) {\n }\n }\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/minischoolX\/thunder\/commit\/54f0cdbf8b3b6b1ed49eaa9eddbb824fa6aa35a9","commit_message":"'\\\\\"Use \\'url\\' as the primary key in the HostsDatabase for improved performance\\\\n\\\\\"'","source_code":"package acr.browser.lightning.database.adblock\n\nimport acr.browser.lightning.database.databaseDelegate\nimport acr.browser.lightning.extensions.safeUse\nimport acr.browser.lightning.extensions.useMap\nimport android.app.Application\nimport android.content.ContentValues\nimport android.database.Cursor\nimport android.database.DatabaseUtils\nimport android.database.sqlite.SQLiteDatabase\nimport android.database.sqlite.SQLiteOpenHelper\nimport io.reactivex.Completable\nimport io.reactivex.Single\nimport javax.inject.Inject\nimport javax.inject.Singleton\n\n\/**\n * A database that holds hosts, backed by SQLite.\n *\/\n@Singleton\nclass HostsDatabase @Inject constructor(\n application: Application\n) : SQLiteOpenHelper(application, DATABASE_NAME, null, DATABASE_VERSION), HostsRepository {\n\n private val database: SQLiteDatabase by databaseDelegate()\n\n \/\/ Creating Tables\n override fun onCreate(db: SQLiteDatabase) {\n val createHostsTable = \"CREATE TABLE ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}(\" +\n \"${DatabaseUtils.sqlEscapeString(KEY_ID)} INTEGER PRIMARY KEY,\" +\n \"${DatabaseUtils.sqlEscapeString(KEY_NAME)} TEXT\" +\n ')'\n db.execSQL(createHostsTable)\n }\n\n \/\/ Upgrading database\n override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {\n \/\/ Drop older table if it exists\n db.execSQL(\"DROP TABLE IF EXISTS ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}\")\n \/\/ Create tables again\n onCreate(db)\n }\n\n override fun addHosts(hosts: List): Completable = Completable.create {\n database.apply {\n beginTransaction()\n\n for (item in hosts) {\n if (it.isDisposed) {\n endTransaction()\n it.onComplete()\n return@apply\n }\n database.insert(TABLE_HOSTS, null, item.toContentValues())\n }\n\n setTransactionSuccessful()\n endTransaction()\n }\n it.onComplete()\n }\n\n override fun removeAllHosts(): Completable = Completable.fromCallable {\n database.run {\n delete(TABLE_HOSTS, null, null)\n close()\n }\n }\n\n override fun containsHost(host: Host): Boolean {\n database.query(\n TABLE_HOSTS,\n arrayOf(KEY_ID),\n \"$KEY_NAME=?\",\n arrayOf(host.name),\n null,\n null,\n null,\n \"1\"\n ).safeUse {\n return it.moveToFirst()\n }\n\n return false\n }\n\n override fun hasHosts(): Boolean = DatabaseUtils.queryNumEntries(database, TABLE_HOSTS) > 0\n\n override fun allHosts(): Single> = Single.fromCallable {\n return@fromCallable database.query(\n TABLE_HOSTS,\n null,\n null,\n null,\n null,\n null,\n \"$KEY_ID DESC\"\n ).useMap { it.bindToHost() }\n }\n\n \/**\n * Maps the fields of [Host] to [ContentValues].\n *\/\n private fun Host.toContentValues() = ContentValues(3).apply {\n put(KEY_NAME, name)\n }\n\n \/**\n * Binds a [Cursor] to a single [Host].\n *\/\n private fun Cursor.bindToHost() = Host(\n name = getString(getColumnIndex(KEY_NAME))\n )\n\n companion object {\n\n \/\/ Database version\n private const val DATABASE_VERSION = 1\n\n \/\/ Database name\n private const val DATABASE_NAME = \"hostsDatabase\"\n\n \/\/ Host table name\n private const val TABLE_HOSTS = \"hosts\"\n\n \/\/ Host table columns names\n private const val KEY_ID = \"id\"\n private const val KEY_NAME = \"url\"\n }\n\n}\n","target_code":"package acr.browser.lightning.database.adblock\n\nimport acr.browser.lightning.database.databaseDelegate\nimport acr.browser.lightning.extensions.safeUse\nimport acr.browser.lightning.extensions.useMap\nimport android.app.Application\nimport android.content.ContentValues\nimport android.database.Cursor\nimport android.database.DatabaseUtils\nimport android.database.sqlite.SQLiteDatabase\nimport android.database.sqlite.SQLiteOpenHelper\nimport io.reactivex.Completable\nimport io.reactivex.Single\nimport javax.inject.Inject\nimport javax.inject.Singleton\n\n\/**\n * A database that holds hosts, backed by SQLite.\n *\/\n@Singleton\nclass HostsDatabase @Inject constructor(\n application: Application\n) : SQLiteOpenHelper(application, DATABASE_NAME, null, DATABASE_VERSION), HostsRepository {\n\n private val database: SQLiteDatabase by databaseDelegate()\n\n \/\/ Creating Tables\n override fun onCreate(db: SQLiteDatabase) {\n val createHostsTable = \"CREATE TABLE ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}(\" +\n \"${DatabaseUtils.sqlEscapeString(KEY_NAME)} TEXT PRIMARY KEY\" +\n ')'\n db.execSQL(createHostsTable)\n }\n\n \/\/ Upgrading database\n override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {\n \/\/ Drop older table if it exists\n db.execSQL(\"DROP TABLE IF EXISTS ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}\")\n \/\/ Create tables again\n onCreate(db)\n }\n\n override fun addHosts(hosts: List): Completable = Completable.create {\n database.apply {\n beginTransaction()\n\n for (item in hosts) {\n if (it.isDisposed) {\n endTransaction()\n it.onComplete()\n return@apply\n }\n database.insert(TABLE_HOSTS, null, item.toContentValues())\n }\n\n setTransactionSuccessful()\n endTransaction()\n }\n it.onComplete()\n }\n\n override fun removeAllHosts(): Completable = Completable.fromCallable {\n database.run {\n delete(TABLE_HOSTS, null, null)\n close()\n }\n }\n\n override fun containsHost(host: Host): Boolean {\n database.query(\n TABLE_HOSTS,\n arrayOf(KEY_NAME),\n \"$KEY_NAME=?\",\n arrayOf(host.name),\n null,\n null,\n null,\n \"1\"\n ).safeUse {\n return it.moveToFirst()\n }\n\n return false\n }\n\n override fun hasHosts(): Boolean = DatabaseUtils.queryNumEntries(database, TABLE_HOSTS) > 0\n\n override fun allHosts(): Single> = Single.fromCallable {\n return@fromCallable database.query(\n TABLE_HOSTS,\n null,\n null,\n null,\n null,\n null,\n null\n ).useMap { it.bindToHost() }\n }\n\n \/**\n * Maps the fields of [Host] to [ContentValues].\n *\/\n private fun Host.toContentValues() = ContentValues(3).apply {\n put(KEY_NAME, name)\n }\n\n \/**\n * Binds a [Cursor] to a single [Host].\n *\/\n private fun Cursor.bindToHost() = Host(\n name = getString(getColumnIndex(KEY_NAME))\n )\n\n companion object {\n\n \/\/ Database version\n private const val DATABASE_VERSION = 2\n\n \/\/ Database name\n private const val DATABASE_NAME = \"hostsDatabase\"\n\n \/\/ Host table name\n private const val TABLE_HOSTS = \"hosts\"\n\n \/\/ Host table columns names\n private const val KEY_NAME = \"url\"\n }\n\n}\n","pl":"Kotlin","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given kotlin program to optimize and improve the execution time. Write the entire code and no other text:\npackage acr.browser.lightning.database.adblock\n\nimport acr.browser.lightning.database.databaseDelegate\nimport acr.browser.lightning.extensions.safeUse\nimport acr.browser.lightning.extensions.useMap\nimport android.app.Application\nimport android.content.ContentValues\nimport android.database.Cursor\nimport android.database.DatabaseUtils\nimport android.database.sqlite.SQLiteDatabase\nimport android.database.sqlite.SQLiteOpenHelper\nimport io.reactivex.Completable\nimport io.reactivex.Single\nimport javax.inject.Inject\nimport javax.inject.Singleton\n\n\/**\n * A database that holds hosts, backed by SQLite.\n *\/\n@Singleton\nclass HostsDatabase @Inject constructor(\n application: Application\n) : SQLiteOpenHelper(application, DATABASE_NAME, null, DATABASE_VERSION), HostsRepository {\n\n private val database: SQLiteDatabase by databaseDelegate()\n\n \/\/ Creating Tables\n override fun onCreate(db: SQLiteDatabase) {\n val createHostsTable = \"CREATE TABLE ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}(\" +\n \"${DatabaseUtils.sqlEscapeString(KEY_ID)} INTEGER PRIMARY KEY,\" +\n \"${DatabaseUtils.sqlEscapeString(KEY_NAME)} TEXT\" +\n ')'\n db.execSQL(createHostsTable)\n }\n\n \/\/ Upgrading database\n override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {\n \/\/ Drop older table if it exists\n db.execSQL(\"DROP TABLE IF EXISTS ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}\")\n \/\/ Create tables again\n onCreate(db)\n }\n\n override fun addHosts(hosts: List): Completable = Completable.create {\n database.apply {\n beginTransaction()\n\n for (item in hosts) {\n if (it.isDisposed) {\n endTransaction()\n it.onComplete()\n return@apply\n }\n database.insert(TABLE_HOSTS, null, item.toContentValues())\n }\n\n setTransactionSuccessful()\n endTransaction()\n }\n it.onComplete()\n }\n\n override fun removeAllHosts(): Completable = Completable.fromCallable {\n database.run {\n delete(TABLE_HOSTS, null, null)\n close()\n }\n }\n\n override fun containsHost(host: Host): Boolean {\n database.query(\n TABLE_HOSTS,\n arrayOf(KEY_ID),\n \"$KEY_NAME=?\",\n arrayOf(host.name),\n null,\n null,\n null,\n \"1\"\n ).safeUse {\n return it.moveToFirst()\n }\n\n return false\n }\n\n override fun hasHosts(): Boolean = DatabaseUtils.queryNumEntries(database, TABLE_HOSTS) > 0\n\n override fun allHosts(): Single> = Single.fromCallable {\n return@fromCallable database.query(\n TABLE_HOSTS,\n null,\n null,\n null,\n null,\n null,\n \"$KEY_ID DESC\"\n ).useMap { it.bindToHost() }\n }\n\n \/**\n * Maps the fields of [Host] to [ContentValues].\n *\/\n private fun Host.toContentValues() = ContentValues(3).apply {\n put(KEY_NAME, name)\n }\n\n \/**\n * Binds a [Cursor] to a single [Host].\n *\/\n private fun Cursor.bindToHost() = Host(\n name = getString(getColumnIndex(KEY_NAME))\n )\n\n companion object {\n\n \/\/ Database version\n private const val DATABASE_VERSION = 1\n\n \/\/ Database name\n private const val DATABASE_NAME = \"hostsDatabase\"\n\n \/\/ Host table name\n private const val TABLE_HOSTS = \"hosts\"\n\n \/\/ Host table columns names\n private const val KEY_ID = \"id\"\n private const val KEY_NAME = \"url\"\n }\n\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given kotlin program to optimize and improve the execution time. Write the entire code and no other text:\npackage acr.browser.lightning.database.adblock\n\nimport acr.browser.lightning.database.databaseDelegate\nimport acr.browser.lightning.extensions.safeUse\nimport acr.browser.lightning.extensions.useMap\nimport android.app.Application\nimport android.content.ContentValues\nimport android.database.Cursor\nimport android.database.DatabaseUtils\nimport android.database.sqlite.SQLiteDatabase\nimport android.database.sqlite.SQLiteOpenHelper\nimport io.reactivex.Completable\nimport io.reactivex.Single\nimport javax.inject.Inject\nimport javax.inject.Singleton\n\n\/**\n * A database that holds hosts, backed by SQLite.\n *\/\n@Singleton\nclass HostsDatabase @Inject constructor(\n application: Application\n) : SQLiteOpenHelper(application, DATABASE_NAME, null, DATABASE_VERSION), HostsRepository {\n\n private val database: SQLiteDatabase by databaseDelegate()\n\n \/\/ Creating Tables\n override fun onCreate(db: SQLiteDatabase) {\n val createHostsTable = \"CREATE TABLE ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}(\" +\n \"${DatabaseUtils.sqlEscapeString(KEY_ID)} INTEGER PRIMARY KEY,\" +\n \"${DatabaseUtils.sqlEscapeString(KEY_NAME)} TEXT\" +\n ')'\n db.execSQL(createHostsTable)\n }\n\n \/\/ Upgrading database\n override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {\n \/\/ Drop older table if it exists\n db.execSQL(\"DROP TABLE IF EXISTS ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}\")\n \/\/ Create tables again\n onCreate(db)\n }\n\n override fun addHosts(hosts: List): Completable = Completable.create {\n database.apply {\n beginTransaction()\n\n for (item in hosts) {\n if (it.isDisposed) {\n endTransaction()\n it.onComplete()\n return@apply\n }\n database.insert(TABLE_HOSTS, null, item.toContentValues())\n }\n\n setTransactionSuccessful()\n endTransaction()\n }\n it.onComplete()\n }\n\n override fun removeAllHosts(): Completable = Completable.fromCallable {\n database.run {\n delete(TABLE_HOSTS, null, null)\n close()\n }\n }\n\n override fun containsHost(host: Host): Boolean {\n database.query(\n TABLE_HOSTS,\n arrayOf(KEY_ID),\n \"$KEY_NAME=?\",\n arrayOf(host.name),\n null,\n null,\n null,\n \"1\"\n ).safeUse {\n return it.moveToFirst()\n }\n\n return false\n }\n\n override fun hasHosts(): Boolean = DatabaseUtils.queryNumEntries(database, TABLE_HOSTS) > 0\n\n override fun allHosts(): Single> = Single.fromCallable {\n return@fromCallable database.query(\n TABLE_HOSTS,\n null,\n null,\n null,\n null,\n null,\n \"$KEY_ID DESC\"\n ).useMap { it.bindToHost() }\n }\n\n \/**\n * Maps the fields of [Host] to [ContentValues].\n *\/\n private fun Host.toContentValues() = ContentValues(3).apply {\n put(KEY_NAME, name)\n }\n\n \/**\n * Binds a [Cursor] to a single [Host].\n *\/\n private fun Cursor.bindToHost() = Host(\n name = getString(getColumnIndex(KEY_NAME))\n )\n\n companion object {\n\n \/\/ Database version\n private const val DATABASE_VERSION = 1\n\n \/\/ Database name\n private const val DATABASE_NAME = \"hostsDatabase\"\n\n \/\/ Host table name\n private const val TABLE_HOSTS = \"hosts\"\n\n \/\/ Host table columns names\n private const val KEY_ID = \"id\"\n private const val KEY_NAME = \"url\"\n }\n\n}\n\n\n### Response:\n```kotlin","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given kotlin program to optimize and improve the execution time. Write the entire code and no other text:\npackage acr.browser.lightning.database.adblock\n\nimport acr.browser.lightning.database.databaseDelegate\nimport acr.browser.lightning.extensions.safeUse\nimport acr.browser.lightning.extensions.useMap\nimport android.app.Application\nimport android.content.ContentValues\nimport android.database.Cursor\nimport android.database.DatabaseUtils\nimport android.database.sqlite.SQLiteDatabase\nimport android.database.sqlite.SQLiteOpenHelper\nimport io.reactivex.Completable\nimport io.reactivex.Single\nimport javax.inject.Inject\nimport javax.inject.Singleton\n\n\/**\n * A database that holds hosts, backed by SQLite.\n *\/\n@Singleton\nclass HostsDatabase @Inject constructor(\n application: Application\n) : SQLiteOpenHelper(application, DATABASE_NAME, null, DATABASE_VERSION), HostsRepository {\n\n private val database: SQLiteDatabase by databaseDelegate()\n\n \/\/ Creating Tables\n override fun onCreate(db: SQLiteDatabase) {\n val createHostsTable = \"CREATE TABLE ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}(\" +\n \"${DatabaseUtils.sqlEscapeString(KEY_ID)} INTEGER PRIMARY KEY,\" +\n \"${DatabaseUtils.sqlEscapeString(KEY_NAME)} TEXT\" +\n ')'\n db.execSQL(createHostsTable)\n }\n\n \/\/ Upgrading database\n override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {\n \/\/ Drop older table if it exists\n db.execSQL(\"DROP TABLE IF EXISTS ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}\")\n \/\/ Create tables again\n onCreate(db)\n }\n\n override fun addHosts(hosts: List): Completable = Completable.create {\n database.apply {\n beginTransaction()\n\n for (item in hosts) {\n if (it.isDisposed) {\n endTransaction()\n it.onComplete()\n return@apply\n }\n database.insert(TABLE_HOSTS, null, item.toContentValues())\n }\n\n setTransactionSuccessful()\n endTransaction()\n }\n it.onComplete()\n }\n\n override fun removeAllHosts(): Completable = Completable.fromCallable {\n database.run {\n delete(TABLE_HOSTS, null, null)\n close()\n }\n }\n\n override fun containsHost(host: Host): Boolean {\n database.query(\n TABLE_HOSTS,\n arrayOf(KEY_ID),\n \"$KEY_NAME=?\",\n arrayOf(host.name),\n null,\n null,\n null,\n \"1\"\n ).safeUse {\n return it.moveToFirst()\n }\n\n return false\n }\n\n override fun hasHosts(): Boolean = DatabaseUtils.queryNumEntries(database, TABLE_HOSTS) > 0\n\n override fun allHosts(): Single> = Single.fromCallable {\n return@fromCallable database.query(\n TABLE_HOSTS,\n null,\n null,\n null,\n null,\n null,\n \"$KEY_ID DESC\"\n ).useMap { it.bindToHost() }\n }\n\n \/**\n * Maps the fields of [Host] to [ContentValues].\n *\/\n private fun Host.toContentValues() = ContentValues(3).apply {\n put(KEY_NAME, name)\n }\n\n \/**\n * Binds a [Cursor] to a single [Host].\n *\/\n private fun Cursor.bindToHost() = Host(\n name = getString(getColumnIndex(KEY_NAME))\n )\n\n companion object {\n\n \/\/ Database version\n private const val DATABASE_VERSION = 1\n\n \/\/ Database name\n private const val DATABASE_NAME = \"hostsDatabase\"\n\n \/\/ Host table name\n private const val TABLE_HOSTS = \"hosts\"\n\n \/\/ Host table columns names\n private const val KEY_ID = \"id\"\n private const val KEY_NAME = \"url\"\n }\n\n}\n\n\n### Response:\n```kotlin","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the database code to improve performance. Write the entire code and no other text in the response.\n\n### Concepts:\n[+] primary keys\n[hint] use url as the primary key in hostsDatabase\n\n### Given program:\n```kotlin\npackage acr.browser.lightning.database.adblock\n\nimport acr.browser.lightning.database.databaseDelegate\nimport acr.browser.lightning.extensions.safeUse\nimport acr.browser.lightning.extensions.useMap\nimport android.app.Application\nimport android.content.ContentValues\nimport android.database.Cursor\nimport android.database.DatabaseUtils\nimport android.database.sqlite.SQLiteDatabase\nimport android.database.sqlite.SQLiteOpenHelper\nimport io.reactivex.Completable\nimport io.reactivex.Single\nimport javax.inject.Inject\nimport javax.inject.Singleton\n\n\/**\n * A database that holds hosts, backed by SQLite.\n *\/\n@Singleton\nclass HostsDatabase @Inject constructor(\n application: Application\n) : SQLiteOpenHelper(application, DATABASE_NAME, null, DATABASE_VERSION), HostsRepository {\n\n private val database: SQLiteDatabase by databaseDelegate()\n\n \/\/ Creating Tables\n override fun onCreate(db: SQLiteDatabase) {\n val createHostsTable = \"CREATE TABLE ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}(\" +\n \"${DatabaseUtils.sqlEscapeString(KEY_ID)} INTEGER PRIMARY KEY,\" +\n \"${DatabaseUtils.sqlEscapeString(KEY_NAME)} TEXT\" +\n ')'\n db.execSQL(createHostsTable)\n }\n\n \/\/ Upgrading database\n override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {\n \/\/ Drop older table if it exists\n db.execSQL(\"DROP TABLE IF EXISTS ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}\")\n \/\/ Create tables again\n onCreate(db)\n }\n\n override fun addHosts(hosts: List): Completable = Completable.create {\n database.apply {\n beginTransaction()\n\n for (item in hosts) {\n if (it.isDisposed) {\n endTransaction()\n it.onComplete()\n return@apply\n }\n database.insert(TABLE_HOSTS, null, item.toContentValues())\n }\n\n setTransactionSuccessful()\n endTransaction()\n }\n it.onComplete()\n }\n\n override fun removeAllHosts(): Completable = Completable.fromCallable {\n database.run {\n delete(TABLE_HOSTS, null, null)\n close()\n }\n }\n\n override fun containsHost(host: Host): Boolean {\n database.query(\n TABLE_HOSTS,\n arrayOf(KEY_ID),\n \"$KEY_NAME=?\",\n arrayOf(host.name),\n null,\n null,\n null,\n \"1\"\n ).safeUse {\n return it.moveToFirst()\n }\n\n return false\n }\n\n override fun hasHosts(): Boolean = DatabaseUtils.queryNumEntries(database, TABLE_HOSTS) > 0\n\n override fun allHosts(): Single> = Single.fromCallable {\n return@fromCallable database.query(\n TABLE_HOSTS,\n null,\n null,\n null,\n null,\n null,\n \"$KEY_ID DESC\"\n ).useMap { it.bindToHost() }\n }\n\n \/**\n * Maps the fields of [Host] to [ContentValues].\n *\/\n private fun Host.toContentValues() = ContentValues(3).apply {\n put(KEY_NAME, name)\n }\n\n \/**\n * Binds a [Cursor] to a single [Host].\n *\/\n private fun Cursor.bindToHost() = Host(\n name = getString(getColumnIndex(KEY_NAME))\n )\n\n companion object {\n\n \/\/ Database version\n private const val DATABASE_VERSION = 1\n\n \/\/ Database name\n private const val DATABASE_NAME = \"hostsDatabase\"\n\n \/\/ Host table name\n private const val TABLE_HOSTS = \"hosts\"\n\n \/\/ Host table columns names\n private const val KEY_ID = \"id\"\n private const val KEY_NAME = \"url\"\n }\n\n}\n\n```\n\n### Response:\n```kotlin","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage us.shandian.giga.service;\n\nimport android.app.Notification;\nimport android.app.PendingIntent;\nimport android.app.Service;\nimport android.content.Intent;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.os.Binder;\nimport android.os.Handler;\nimport android.os.HandlerThread;\nimport android.os.IBinder;\nimport android.os.Message;\nimport android.util.Log;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.get.DownloadManager;\nimport us.shandian.giga.get.DownloadMission;\nimport us.shandian.giga.ui.main.MainActivity;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class DownloadManagerService extends Service implements DownloadMission.MissionListener\n{\n\t\n\tprivate static final String TAG = DownloadManagerService.class.getSimpleName();\n\t\n\tprivate DMBinder mBinder;\n\tprivate DownloadManager mManager;\n\tprivate Notification mNotification;\n\tprivate Handler mHandler;\n\n\t@Override\n\tpublic void onCreate() {\n\t\tsuper.onCreate();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"onCreate\");\n\t\t}\n\t\t\n\t\tmBinder = new DMBinder();\n\t\tif (mManager == null) {\n\n\t\t\tif (DEBUG) {\n\t\t\t\tLog.d(TAG, \"mManager == null\");\n\t\t\t}\n\n\t\t\tmManager = new DownloadManager(this, \"\/storage\/sdcard0\/GigaGet\");\n\t\t}\n\t\t\n\t\tIntent i = new Intent();\n\t\ti.setAction(Intent.ACTION_MAIN);\n\t\ti.setClass(this, MainActivity.class);\n\t\tmNotification = new Notification.Builder(this)\n\t\t\t.setContentIntent(PendingIntent.getActivity(this, 0, i, 0))\n\t\t\t.setContentTitle(getString(R.string.msg_running))\n\t\t\t.setContentText(getString(R.string.msg_running_detail))\n\t\t\t.setLargeIcon(((BitmapDrawable) getDrawable(R.drawable.gigaget)).getBitmap())\n\t\t\t.setSmallIcon(android.R.drawable.stat_sys_download)\n\t\t\t.build();\n\t\t\t\n\t\tHandlerThread thread = new HandlerThread(\"ServiceMessenger\");\n\t\tthread.start();\n\t\t\t\n\t\tmHandler = new Handler(thread.getLooper()) {\n\t\t\t@Override\n\t\t\tpublic void handleMessage(Message msg) {\n\t\t\t\tif (msg.what == 0) {\n\t\t\t\t\tint runningCount = 0;\n\t\t\t\t\t\n\t\t\t\t\tfor (int i = 0; i < mManager.getCount(); i++) {\n\t\t\t\t\t\tif (mManager.getMission(i).running) {\n\t\t\t\t\t\t\trunningCount++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tupdateState(runningCount);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\t\n\t}\n\n\t@Override\n\tpublic int onStartCommand(Intent intent, int flags, int startId) {\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Starting\");\n\t\t}\n\t\t\n\t\treturn START_NOT_STICKY;\n\t}\n\n\t@Override\n\tpublic void onDestroy() {\n\t\tsuper.onDestroy();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Destroying\");\n\t\t}\n\t\t\n\t\tfor (int i = 0; i < mManager.getCount(); i++) {\n\t\t\tmManager.pauseMission(i);\n\t\t}\n\t\t\n\t\tstopForeground(true);\n\t}\n\t\n\t@Override\n\tpublic IBinder onBind(Intent intent) {\n\t\treturn mBinder;\n\t}\n\t\n\n\t@Override\n\tpublic void onProgressUpdate(long done, long total) {\n\t\t\/\/ Do nothing\n\t}\n\n\t@Override\n\tpublic void onFinish() {\n\t\tpostUpdateMessage();\n\t}\n\n\t@Override\n\tpublic void onError(int errCode) {\n\t\tpostUpdateMessage();\n\t}\n\t\n\tprivate void postUpdateMessage() {\n\t\tmHandler.sendEmptyMessage(0);\n\t}\n\t\n\tprivate void updateState(int runningCount) {\n\t\tif (runningCount == 0) {\n\t\t\tstopForeground(true);\n\t\t} else {\n\t\t\tstartForeground(1000, mNotification);\n\t\t}\n\t}\n\t\n\t\n\t\/\/ Wrapper of DownloadManager\n\tpublic class DMBinder extends Binder {\n\t\t\/\/ Do not start missions from outside\n\t\tpublic DownloadManager getDownloadManager() {\n\t\t\treturn mManager;\n\t\t}\n\t\t\n\t\tpublic int startMission(final String url, final String name, final int threads) {\n\t\t\tint ret = mManager.startMission(url, name, threads);\n\t\t\tpostUpdateMessage();\n\t\t\treturn ret;\n\t\t}\n\t\t\n\t\tpublic void resumeMission(final int id) {\n\t\t\tmManager.resumeMission(id);\n\t\t\tpostUpdateMessage();\n\t\t}\n\t\t\n\t\tpublic void pauseMission(final int id) {\n\t\t\tmManager.pauseMission(id);\n\t\t\tpostUpdateMessage();\n\t\t}\n\t\t\n\t}\n\n}\n\n\nCode-B:\npackage us.shandian.giga.service;\n\nimport android.app.Notification;\nimport android.app.PendingIntent;\nimport android.app.Service;\nimport android.content.Intent;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.os.Binder;\nimport android.os.IBinder;\nimport android.util.Log;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.get.DownloadManager;\nimport us.shandian.giga.get.DownloadMission;\nimport us.shandian.giga.ui.main.MainActivity;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class DownloadManagerService extends Service implements DownloadMission.MissionListener\n{\n\t\n\tprivate static final String TAG = DownloadManagerService.class.getSimpleName();\n\t\n\tprivate DMBinder mBinder;\n\tprivate DownloadManager mManager;\n\tprivate Notification mNotification;\n\tprivate int mRunningCount = 0;\n\n\t@Override\n\tpublic void onCreate() {\n\t\tsuper.onCreate();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"onCreate\");\n\t\t}\n\t\t\n\t\tmBinder = new DMBinder();\n\t\tif (mManager == null) {\n\n\t\t\tif (DEBUG) {\n\t\t\t\tLog.d(TAG, \"mManager == null\");\n\t\t\t}\n\n\t\t\tmManager = new DownloadManager(this, \"\/storage\/sdcard0\/GigaGet\");\n\t\t}\n\t\t\n\t\tIntent i = new Intent();\n\t\ti.setAction(Intent.ACTION_MAIN);\n\t\ti.setClass(this, MainActivity.class);\n\t\tmNotification = new Notification.Builder(this)\n\t\t\t.setContentIntent(PendingIntent.getActivity(this, 0, i, 0))\n\t\t\t.setContentTitle(getString(R.string.msg_running))\n\t\t\t.setContentText(getString(R.string.msg_running_detail))\n\t\t\t.setLargeIcon(((BitmapDrawable) getDrawable(R.drawable.gigaget)).getBitmap())\n\t\t\t.setSmallIcon(android.R.drawable.stat_sys_download)\n\t\t\t.build();\n\t\t\n\t}\n\n\t@Override\n\tpublic int onStartCommand(Intent intent, int flags, int startId) {\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Starting\");\n\t\t}\n\t\t\n\t\treturn START_NOT_STICKY;\n\t}\n\n\t@Override\n\tpublic void onDestroy() {\n\t\tsuper.onDestroy();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Destroying\");\n\t\t}\n\t\t\n\t\tfor (int i = 0; i < mManager.getCount(); i++) {\n\t\t\tmManager.pauseMission(i);\n\t\t}\n\t\t\n\t\tstopForeground(true);\n\t}\n\t\n\t@Override\n\tpublic IBinder onBind(Intent intent) {\n\t\treturn mBinder;\n\t}\n\t\n\n\t@Override\n\tpublic void onProgressUpdate(long done, long total) {\n\t\t\/\/ Do nothing\n\t}\n\n\t@Override\n\tpublic void onFinish() {\n\t\tmRunningCount--;\n\t\tupdateState();\n\t}\n\n\t@Override\n\tpublic void onError(int errCode) {\n\t\tmRunningCount--;\n\t\tupdateState();\n\t}\n\t\n\tprivate void updateState() {\n\t\tif (mRunningCount == 0) {\n\t\t\tstopForeground(true);\n\t\t} else {\n\t\t\tstartForeground(1000, mNotification);\n\t\t}\n\t}\n\t\n\t\n\t\/\/ Wrapper of DownloadManager\n\tpublic class DMBinder extends Binder {\n\t\t\/\/ Do not start missions from outside\n\t\tpublic DownloadManager getDownloadManager() {\n\t\t\treturn mManager;\n\t\t}\n\t\t\n\t\tpublic int startMission(final String url, final String name, final int threads) {\n\t\t\tmRunningCount++;\n\t\t\tupdateState();\n\t\t\treturn mManager.startMission(url, name, threads);\n\t\t}\n\t\t\n\t\tpublic void resumeMission(final int id) {\n\t\t\tmRunningCount++;\n\t\t\tupdateState();\n\t\t\tmManager.resumeMission(id);\n\t\t}\n\t\t\n\t\tpublic void pauseMission(final int id) {\n\t\t\tmRunningCount--;\n\t\t\tupdateState();\n\t\t\tmManager.pauseMission(id);\n\t\t}\n\t\t\n\t}\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage us.shandian.giga.service;\n\nimport android.app.Notification;\nimport android.app.PendingIntent;\nimport android.app.Service;\nimport android.content.Intent;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.os.Binder;\nimport android.os.IBinder;\nimport android.util.Log;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.get.DownloadManager;\nimport us.shandian.giga.get.DownloadMission;\nimport us.shandian.giga.ui.main.MainActivity;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class DownloadManagerService extends Service implements DownloadMission.MissionListener\n{\n\t\n\tprivate static final String TAG = DownloadManagerService.class.getSimpleName();\n\t\n\tprivate DMBinder mBinder;\n\tprivate DownloadManager mManager;\n\tprivate Notification mNotification;\n\tprivate int mRunningCount = 0;\n\n\t@Override\n\tpublic void onCreate() {\n\t\tsuper.onCreate();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"onCreate\");\n\t\t}\n\t\t\n\t\tmBinder = new DMBinder();\n\t\tif (mManager == null) {\n\n\t\t\tif (DEBUG) {\n\t\t\t\tLog.d(TAG, \"mManager == null\");\n\t\t\t}\n\n\t\t\tmManager = new DownloadManager(this, \"\/storage\/sdcard0\/GigaGet\");\n\t\t}\n\t\t\n\t\tIntent i = new Intent();\n\t\ti.setAction(Intent.ACTION_MAIN);\n\t\ti.setClass(this, MainActivity.class);\n\t\tmNotification = new Notification.Builder(this)\n\t\t\t.setContentIntent(PendingIntent.getActivity(this, 0, i, 0))\n\t\t\t.setContentTitle(getString(R.string.msg_running))\n\t\t\t.setContentText(getString(R.string.msg_running_detail))\n\t\t\t.setLargeIcon(((BitmapDrawable) getDrawable(R.drawable.gigaget)).getBitmap())\n\t\t\t.setSmallIcon(android.R.drawable.stat_sys_download)\n\t\t\t.build();\n\t\t\n\t}\n\n\t@Override\n\tpublic int onStartCommand(Intent intent, int flags, int startId) {\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Starting\");\n\t\t}\n\t\t\n\t\treturn START_NOT_STICKY;\n\t}\n\n\t@Override\n\tpublic void onDestroy() {\n\t\tsuper.onDestroy();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Destroying\");\n\t\t}\n\t\t\n\t\tfor (int i = 0; i < mManager.getCount(); i++) {\n\t\t\tmManager.pauseMission(i);\n\t\t}\n\t\t\n\t\tstopForeground(true);\n\t}\n\t\n\t@Override\n\tpublic IBinder onBind(Intent intent) {\n\t\treturn mBinder;\n\t}\n\t\n\n\t@Override\n\tpublic void onProgressUpdate(long done, long total) {\n\t\t\/\/ Do nothing\n\t}\n\n\t@Override\n\tpublic void onFinish() {\n\t\tmRunningCount--;\n\t\tupdateState();\n\t}\n\n\t@Override\n\tpublic void onError(int errCode) {\n\t\tmRunningCount--;\n\t\tupdateState();\n\t}\n\t\n\tprivate void updateState() {\n\t\tif (mRunningCount == 0) {\n\t\t\tstopForeground(true);\n\t\t} else {\n\t\t\tstartForeground(1000, mNotification);\n\t\t}\n\t}\n\t\n\t\n\t\/\/ Wrapper of DownloadManager\n\tpublic class DMBinder extends Binder {\n\t\t\/\/ Do not start missions from outside\n\t\tpublic DownloadManager getDownloadManager() {\n\t\t\treturn mManager;\n\t\t}\n\t\t\n\t\tpublic int startMission(final String url, final String name, final int threads) {\n\t\t\tmRunningCount++;\n\t\t\tupdateState();\n\t\t\treturn mManager.startMission(url, name, threads);\n\t\t}\n\t\t\n\t\tpublic void resumeMission(final int id) {\n\t\t\tmRunningCount++;\n\t\t\tupdateState();\n\t\t\tmManager.resumeMission(id);\n\t\t}\n\t\t\n\t\tpublic void pauseMission(final int id) {\n\t\t\tmRunningCount--;\n\t\t\tupdateState();\n\t\t\tmManager.pauseMission(id);\n\t\t}\n\t\t\n\t}\n\n}\n\n\nCode-B:\npackage us.shandian.giga.service;\n\nimport android.app.Notification;\nimport android.app.PendingIntent;\nimport android.app.Service;\nimport android.content.Intent;\nimport android.graphics.drawable.BitmapDrawable;\nimport android.os.Binder;\nimport android.os.Handler;\nimport android.os.HandlerThread;\nimport android.os.IBinder;\nimport android.os.Message;\nimport android.util.Log;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.get.DownloadManager;\nimport us.shandian.giga.get.DownloadMission;\nimport us.shandian.giga.ui.main.MainActivity;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class DownloadManagerService extends Service implements DownloadMission.MissionListener\n{\n\t\n\tprivate static final String TAG = DownloadManagerService.class.getSimpleName();\n\t\n\tprivate DMBinder mBinder;\n\tprivate DownloadManager mManager;\n\tprivate Notification mNotification;\n\tprivate Handler mHandler;\n\n\t@Override\n\tpublic void onCreate() {\n\t\tsuper.onCreate();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"onCreate\");\n\t\t}\n\t\t\n\t\tmBinder = new DMBinder();\n\t\tif (mManager == null) {\n\n\t\t\tif (DEBUG) {\n\t\t\t\tLog.d(TAG, \"mManager == null\");\n\t\t\t}\n\n\t\t\tmManager = new DownloadManager(this, \"\/storage\/sdcard0\/GigaGet\");\n\t\t}\n\t\t\n\t\tIntent i = new Intent();\n\t\ti.setAction(Intent.ACTION_MAIN);\n\t\ti.setClass(this, MainActivity.class);\n\t\tmNotification = new Notification.Builder(this)\n\t\t\t.setContentIntent(PendingIntent.getActivity(this, 0, i, 0))\n\t\t\t.setContentTitle(getString(R.string.msg_running))\n\t\t\t.setContentText(getString(R.string.msg_running_detail))\n\t\t\t.setLargeIcon(((BitmapDrawable) getDrawable(R.drawable.gigaget)).getBitmap())\n\t\t\t.setSmallIcon(android.R.drawable.stat_sys_download)\n\t\t\t.build();\n\t\t\t\n\t\tHandlerThread thread = new HandlerThread(\"ServiceMessenger\");\n\t\tthread.start();\n\t\t\t\n\t\tmHandler = new Handler(thread.getLooper()) {\n\t\t\t@Override\n\t\t\tpublic void handleMessage(Message msg) {\n\t\t\t\tif (msg.what == 0) {\n\t\t\t\t\tint runningCount = 0;\n\t\t\t\t\t\n\t\t\t\t\tfor (int i = 0; i < mManager.getCount(); i++) {\n\t\t\t\t\t\tif (mManager.getMission(i).running) {\n\t\t\t\t\t\t\trunningCount++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tupdateState(runningCount);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\t\n\t}\n\n\t@Override\n\tpublic int onStartCommand(Intent intent, int flags, int startId) {\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Starting\");\n\t\t}\n\t\t\n\t\treturn START_NOT_STICKY;\n\t}\n\n\t@Override\n\tpublic void onDestroy() {\n\t\tsuper.onDestroy();\n\t\t\n\t\tif (DEBUG) {\n\t\t\tLog.d(TAG, \"Destroying\");\n\t\t}\n\t\t\n\t\tfor (int i = 0; i < mManager.getCount(); i++) {\n\t\t\tmManager.pauseMission(i);\n\t\t}\n\t\t\n\t\tstopForeground(true);\n\t}\n\t\n\t@Override\n\tpublic IBinder onBind(Intent intent) {\n\t\treturn mBinder;\n\t}\n\t\n\n\t@Override\n\tpublic void onProgressUpdate(long done, long total) {\n\t\t\/\/ Do nothing\n\t}\n\n\t@Override\n\tpublic void onFinish() {\n\t\tpostUpdateMessage();\n\t}\n\n\t@Override\n\tpublic void onError(int errCode) {\n\t\tpostUpdateMessage();\n\t}\n\t\n\tprivate void postUpdateMessage() {\n\t\tmHandler.sendEmptyMessage(0);\n\t}\n\t\n\tprivate void updateState(int runningCount) {\n\t\tif (runningCount == 0) {\n\t\t\tstopForeground(true);\n\t\t} else {\n\t\t\tstartForeground(1000, mNotification);\n\t\t}\n\t}\n\t\n\t\n\t\/\/ Wrapper of DownloadManager\n\tpublic class DMBinder extends Binder {\n\t\t\/\/ Do not start missions from outside\n\t\tpublic DownloadManager getDownloadManager() {\n\t\t\treturn mManager;\n\t\t}\n\t\t\n\t\tpublic int startMission(final String url, final String name, final int threads) {\n\t\t\tint ret = mManager.startMission(url, name, threads);\n\t\t\tpostUpdateMessage();\n\t\t\treturn ret;\n\t\t}\n\t\t\n\t\tpublic void resumeMission(final int id) {\n\t\t\tmManager.resumeMission(id);\n\t\t\tpostUpdateMessage();\n\t\t}\n\t\t\n\t\tpublic void pauseMission(final int id) {\n\t\t\tmManager.pauseMission(id);\n\t\t\tpostUpdateMessage();\n\t\t}\n\t\t\n\t}\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/aaronjwood\/PortAuthority\/commit\/80d006522bfdf5552878e54aee4b4868d990deb3","commit_message":"'\\\\\"Optimization of finding elements in the UI. Removed some unnecessary calls that ended up being performed repeatedly due to where they were positioned\\\\n\\\\\"'","source_code":"package com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n private Wireless wifi;\n\n private Button discoverHosts;\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n private ListView hostList;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n TextView macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n macAddress.setText(this.wifi.getMacAddress());\n\n TextView ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n ipAddress.setText(internalIp);\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n TextView signalStrength = (TextView) findViewById(R.id.signalStrength);\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList = (ListView) findViewById(R.id.hostList);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n","target_code":"package com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView ipAddress;\n private TextView signalStrength;\n\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n macAddress.setText(this.wifi.getMacAddress());\n ipAddress.setText(internalIp);\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n private Wireless wifi;\n\n private Button discoverHosts;\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n private ListView hostList;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n TextView macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n macAddress.setText(this.wifi.getMacAddress());\n\n TextView ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n ipAddress.setText(internalIp);\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n TextView signalStrength = (TextView) findViewById(R.id.signalStrength);\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList = (ListView) findViewById(R.id.hostList);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n private Wireless wifi;\n\n private Button discoverHosts;\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n private ListView hostList;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n TextView macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n macAddress.setText(this.wifi.getMacAddress());\n\n TextView ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n ipAddress.setText(internalIp);\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n TextView signalStrength = (TextView) findViewById(R.id.signalStrength);\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList = (ListView) findViewById(R.id.hostList);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n private Wireless wifi;\n\n private Button discoverHosts;\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n private ListView hostList;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n TextView macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n macAddress.setText(this.wifi.getMacAddress());\n\n TextView ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n ipAddress.setText(internalIp);\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n TextView signalStrength = (TextView) findViewById(R.id.signalStrength);\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList = (ListView) findViewById(R.id.hostList);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the code to optimize finding elements in the UI of the android application. Write the entire code and no other text in the response.\n\n### Concepts:\n[hint] remove unncessary calls that are repeatedly performed due to their position in the code. \n\n### Given program:\n```java\npackage com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n private Wireless wifi;\n\n private Button discoverHosts;\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n private ListView hostList;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n TextView macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n macAddress.setText(this.wifi.getMacAddress());\n\n TextView ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n ipAddress.setText(internalIp);\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n TextView signalStrength = (TextView) findViewById(R.id.signalStrength);\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList = (ListView) findViewById(R.id.hostList);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.utils;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.text.TextUtils;\n\nimport org.mozilla.focus.BuildConfig;\nimport org.mozilla.focus.search.SearchEngine;\nimport org.mozilla.focus.search.SearchEngineManager;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\npublic class UrlUtils {\n public static String normalize(String input) {\n Uri uri = Uri.parse(input);\n\n if (TextUtils.isEmpty(uri.getScheme())) {\n uri = Uri.parse(\"http:\/\/\" + input);\n }\n\n return uri.toString();\n }\n\n \/**\n * Is the given string a URL or should we perform a search?\n *\n * TODO: This is a super simple and probably stupid implementation.\n *\/\n public static boolean isUrl(String url) {\n if (url.contains(\" \")) {\n return false;\n }\n\n return url.contains(\".\") || url.contains(\":\");\n }\n\n public static boolean isSearchQuery(String text) {\n return text.contains(\" \");\n }\n\n public static String createSearchUrl(Context context, String searchTerm) {\n final SearchEngine searchEngine = SearchEngineManager.getInstance()\n .getDefaultSearchEngine(context);\n\n return searchEngine.buildSearchUrl(searchTerm);\n }\n\n public static String stripUserInfo(String url) {\n try {\n URI uri = new URI(url);\n\n final String userInfo = uri.getUserInfo();\n if (userInfo == null) {\n return url;\n }\n\n \/\/ Strip the userInfo to minimise spoofing ability. This only affects what's shown\n \/\/ during browsing, this information isn't used when we start editing the URL:\n uri = new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());\n\n return uri.toString();\n } catch (URISyntaxException e) {\n \/\/ In general this shouldn't happen. But there are some special cases that URI can't handle,\n \/\/ such as \"http:\" by itself. We allow those individual special cases, but we still want\n \/\/ to catch other special syntaxes in dev builds if possible\n if (url.equals(\"http:\") ||\n url.equals(\"https:\") ||\n url.equals(\"file:\")) {\n return url;\n }\n\n if (BuildConfig.DEBUG) {\n \/\/ WebView should always have supplied a valid URL\n throw new IllegalStateException(\"WebView is expected to always supply a valid URL\");\n } else {\n return url;\n }\n }\n }\n\n public static boolean focusSupportURLProtocol(final String url) {\n return (!url.startsWith(\"http:\")) &&\n (!url.startsWith(\"https:\")) &&\n (!url.startsWith(\"file:\")) &&\n (!url.startsWith(\"data:\")) &&\n (!url.startsWith(\"error:\"));\n }\n}\n\n\nCode-B:\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.utils;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.text.TextUtils;\n\nimport org.mozilla.focus.BuildConfig;\nimport org.mozilla.focus.search.SearchEngine;\nimport org.mozilla.focus.search.SearchEngineManager;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\npublic class UrlUtils {\n public static String normalize(String input) {\n Uri uri = Uri.parse(input);\n\n if (TextUtils.isEmpty(uri.getScheme())) {\n uri = Uri.parse(\"http:\/\/\" + input);\n }\n\n return uri.toString();\n }\n\n \/**\n * Is the given string a URL or should we perform a search?\n *\n * TODO: This is a super simple and probably stupid implementation.\n *\/\n public static boolean isUrl(String url) {\n if (url.contains(\" \")) {\n return false;\n }\n\n return url.contains(\".\") || url.contains(\":\");\n }\n\n public static boolean isSearchQuery(String text) {\n return text.contains(\" \");\n }\n\n public static String createSearchUrl(Context context, String searchTerm) {\n final SearchEngine searchEngine = SearchEngineManager.getInstance()\n .getDefaultSearchEngine(context);\n\n return searchEngine.buildSearchUrl(searchTerm);\n }\n\n public static String stripUserInfo(String url) {\n try {\n URI uri = new URI(url);\n final String userInfo = uri.getUserInfo();\n if (userInfo != null) {\n \/\/ Strip the userInfo to minimise spoofing ability. This only affects what's shown\n \/\/ during browsing, this information isn't used when we start editing the URL:\n uri = new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());\n }\n\n return uri.toString();\n } catch (URISyntaxException e) {\n \/\/ In general this shouldn't happen. But there are some special cases that URI can't handle,\n \/\/ such as \"http:\" by itself. We allow those individual special cases, but we still want\n \/\/ to catch other special syntaxes in dev builds if possible\n if (url.equals(\"http:\") ||\n url.equals(\"https:\") ||\n url.equals(\"file:\")) {\n return url;\n }\n\n if (BuildConfig.DEBUG) {\n \/\/ WebView should always have supplied a valid URL\n throw new IllegalStateException(\"WebView is expected to always supply a valid URL\");\n } else {\n return url;\n }\n }\n }\n\n public static boolean focusSupportURLProtocol(final String url) {\n return (!url.startsWith(\"http:\")) &&\n (!url.startsWith(\"https:\")) &&\n (!url.startsWith(\"file:\")) &&\n (!url.startsWith(\"data:\")) &&\n (!url.startsWith(\"error:\"));\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.utils;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.text.TextUtils;\n\nimport org.mozilla.focus.BuildConfig;\nimport org.mozilla.focus.search.SearchEngine;\nimport org.mozilla.focus.search.SearchEngineManager;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\npublic class UrlUtils {\n public static String normalize(String input) {\n Uri uri = Uri.parse(input);\n\n if (TextUtils.isEmpty(uri.getScheme())) {\n uri = Uri.parse(\"http:\/\/\" + input);\n }\n\n return uri.toString();\n }\n\n \/**\n * Is the given string a URL or should we perform a search?\n *\n * TODO: This is a super simple and probably stupid implementation.\n *\/\n public static boolean isUrl(String url) {\n if (url.contains(\" \")) {\n return false;\n }\n\n return url.contains(\".\") || url.contains(\":\");\n }\n\n public static boolean isSearchQuery(String text) {\n return text.contains(\" \");\n }\n\n public static String createSearchUrl(Context context, String searchTerm) {\n final SearchEngine searchEngine = SearchEngineManager.getInstance()\n .getDefaultSearchEngine(context);\n\n return searchEngine.buildSearchUrl(searchTerm);\n }\n\n public static String stripUserInfo(String url) {\n try {\n URI uri = new URI(url);\n final String userInfo = uri.getUserInfo();\n if (userInfo != null) {\n \/\/ Strip the userInfo to minimise spoofing ability. This only affects what's shown\n \/\/ during browsing, this information isn't used when we start editing the URL:\n uri = new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());\n }\n\n return uri.toString();\n } catch (URISyntaxException e) {\n \/\/ In general this shouldn't happen. But there are some special cases that URI can't handle,\n \/\/ such as \"http:\" by itself. We allow those individual special cases, but we still want\n \/\/ to catch other special syntaxes in dev builds if possible\n if (url.equals(\"http:\") ||\n url.equals(\"https:\") ||\n url.equals(\"file:\")) {\n return url;\n }\n\n if (BuildConfig.DEBUG) {\n \/\/ WebView should always have supplied a valid URL\n throw new IllegalStateException(\"WebView is expected to always supply a valid URL\");\n } else {\n return url;\n }\n }\n }\n\n public static boolean focusSupportURLProtocol(final String url) {\n return (!url.startsWith(\"http:\")) &&\n (!url.startsWith(\"https:\")) &&\n (!url.startsWith(\"file:\")) &&\n (!url.startsWith(\"data:\")) &&\n (!url.startsWith(\"error:\"));\n }\n}\n\n\nCode-B:\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.utils;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.text.TextUtils;\n\nimport org.mozilla.focus.BuildConfig;\nimport org.mozilla.focus.search.SearchEngine;\nimport org.mozilla.focus.search.SearchEngineManager;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\npublic class UrlUtils {\n public static String normalize(String input) {\n Uri uri = Uri.parse(input);\n\n if (TextUtils.isEmpty(uri.getScheme())) {\n uri = Uri.parse(\"http:\/\/\" + input);\n }\n\n return uri.toString();\n }\n\n \/**\n * Is the given string a URL or should we perform a search?\n *\n * TODO: This is a super simple and probably stupid implementation.\n *\/\n public static boolean isUrl(String url) {\n if (url.contains(\" \")) {\n return false;\n }\n\n return url.contains(\".\") || url.contains(\":\");\n }\n\n public static boolean isSearchQuery(String text) {\n return text.contains(\" \");\n }\n\n public static String createSearchUrl(Context context, String searchTerm) {\n final SearchEngine searchEngine = SearchEngineManager.getInstance()\n .getDefaultSearchEngine(context);\n\n return searchEngine.buildSearchUrl(searchTerm);\n }\n\n public static String stripUserInfo(String url) {\n try {\n URI uri = new URI(url);\n\n final String userInfo = uri.getUserInfo();\n if (userInfo == null) {\n return url;\n }\n\n \/\/ Strip the userInfo to minimise spoofing ability. This only affects what's shown\n \/\/ during browsing, this information isn't used when we start editing the URL:\n uri = new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());\n\n return uri.toString();\n } catch (URISyntaxException e) {\n \/\/ In general this shouldn't happen. But there are some special cases that URI can't handle,\n \/\/ such as \"http:\" by itself. We allow those individual special cases, but we still want\n \/\/ to catch other special syntaxes in dev builds if possible\n if (url.equals(\"http:\") ||\n url.equals(\"https:\") ||\n url.equals(\"file:\")) {\n return url;\n }\n\n if (BuildConfig.DEBUG) {\n \/\/ WebView should always have supplied a valid URL\n throw new IllegalStateException(\"WebView is expected to always supply a valid URL\");\n } else {\n return url;\n }\n }\n }\n\n public static boolean focusSupportURLProtocol(final String url) {\n return (!url.startsWith(\"http:\")) &&\n (!url.startsWith(\"https:\")) &&\n (!url.startsWith(\"file:\")) &&\n (!url.startsWith(\"data:\")) &&\n (!url.startsWith(\"error:\"));\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/experiment322\/controlloid-client\/commit\/ef1de6ce124525ec07275ecd3b76c4396c7967cd","commit_message":"'\\\\\"Optimise Analog control\\\\n\\\\n- check if new position is different from the previous one before\\\\ndispatching it and before updating the animation because it was bandwith\\\\nconsuming and not performant\\\\n\\\\\"'","source_code":"import React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n","target_code":"import React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n \/\/ noinspection JSSuspiciousNameCombination\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n if (clampedPosition.x !== this.translation.x._value \/\/ eslint-disable-line max-len, no-underscore-dangle\n || clampedPosition.y !== this.translation.y._value) { \/\/ eslint-disable-line max-len, no-underscore-dangle\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n }\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n","pl":"JavaScript XML","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given javascript xml program to optimize and improve the execution time. Write the entire code and no other text:\nimport React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given javascript xml program to optimize and improve the execution time. Write the entire code and no other text:\nimport React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n\n\n### Response:\n```javascript xml","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given javascript xml program to optimize and improve the execution time. Write the entire code and no other text:\nimport React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n\n\n### Response:\n```javascript xml","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the code to optimize analog control and improve bandwidth usage and performance of the android application. Write the entire code and no other text in the response.\n\n### Concepts:\n[in] analogMove function\n[hint] check if new position is different from the previous one before dispatching it and before updating the animation because it is bandwidth consuming and not performant.\n\n### Given program:\n```javascript xml\nimport React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n\n```\n\n### Response:\n```javascript xml","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage acr.browser.lightning.database.adblock\n\nimport acr.browser.lightning.database.databaseDelegate\nimport acr.browser.lightning.extensions.safeUse\nimport acr.browser.lightning.extensions.useMap\nimport android.app.Application\nimport android.content.ContentValues\nimport android.database.Cursor\nimport android.database.DatabaseUtils\nimport android.database.sqlite.SQLiteDatabase\nimport android.database.sqlite.SQLiteOpenHelper\nimport io.reactivex.Completable\nimport io.reactivex.Single\nimport javax.inject.Inject\nimport javax.inject.Singleton\n\n\/**\n * A database that holds hosts, backed by SQLite.\n *\/\n@Singleton\nclass HostsDatabase @Inject constructor(\n application: Application\n) : SQLiteOpenHelper(application, DATABASE_NAME, null, DATABASE_VERSION), HostsRepository {\n\n private val database: SQLiteDatabase by databaseDelegate()\n\n \/\/ Creating Tables\n override fun onCreate(db: SQLiteDatabase) {\n val createHostsTable = \"CREATE TABLE ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}(\" +\n \"${DatabaseUtils.sqlEscapeString(KEY_NAME)} TEXT PRIMARY KEY\" +\n ')'\n db.execSQL(createHostsTable)\n }\n\n \/\/ Upgrading database\n override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {\n \/\/ Drop older table if it exists\n db.execSQL(\"DROP TABLE IF EXISTS ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}\")\n \/\/ Create tables again\n onCreate(db)\n }\n\n override fun addHosts(hosts: List): Completable = Completable.create {\n database.apply {\n beginTransaction()\n\n for (item in hosts) {\n if (it.isDisposed) {\n endTransaction()\n it.onComplete()\n return@apply\n }\n database.insert(TABLE_HOSTS, null, item.toContentValues())\n }\n\n setTransactionSuccessful()\n endTransaction()\n }\n it.onComplete()\n }\n\n override fun removeAllHosts(): Completable = Completable.fromCallable {\n database.run {\n delete(TABLE_HOSTS, null, null)\n close()\n }\n }\n\n override fun containsHost(host: Host): Boolean {\n database.query(\n TABLE_HOSTS,\n arrayOf(KEY_NAME),\n \"$KEY_NAME=?\",\n arrayOf(host.name),\n null,\n null,\n null,\n \"1\"\n ).safeUse {\n return it.moveToFirst()\n }\n\n return false\n }\n\n override fun hasHosts(): Boolean = DatabaseUtils.queryNumEntries(database, TABLE_HOSTS) > 0\n\n override fun allHosts(): Single> = Single.fromCallable {\n return@fromCallable database.query(\n TABLE_HOSTS,\n null,\n null,\n null,\n null,\n null,\n null\n ).useMap { it.bindToHost() }\n }\n\n \/**\n * Maps the fields of [Host] to [ContentValues].\n *\/\n private fun Host.toContentValues() = ContentValues(3).apply {\n put(KEY_NAME, name)\n }\n\n \/**\n * Binds a [Cursor] to a single [Host].\n *\/\n private fun Cursor.bindToHost() = Host(\n name = getString(getColumnIndex(KEY_NAME))\n )\n\n companion object {\n\n \/\/ Database version\n private const val DATABASE_VERSION = 2\n\n \/\/ Database name\n private const val DATABASE_NAME = \"hostsDatabase\"\n\n \/\/ Host table name\n private const val TABLE_HOSTS = \"hosts\"\n\n \/\/ Host table columns names\n private const val KEY_NAME = \"url\"\n }\n\n}\n\n\nCode-B:\npackage acr.browser.lightning.database.adblock\n\nimport acr.browser.lightning.database.databaseDelegate\nimport acr.browser.lightning.extensions.safeUse\nimport acr.browser.lightning.extensions.useMap\nimport android.app.Application\nimport android.content.ContentValues\nimport android.database.Cursor\nimport android.database.DatabaseUtils\nimport android.database.sqlite.SQLiteDatabase\nimport android.database.sqlite.SQLiteOpenHelper\nimport io.reactivex.Completable\nimport io.reactivex.Single\nimport javax.inject.Inject\nimport javax.inject.Singleton\n\n\/**\n * A database that holds hosts, backed by SQLite.\n *\/\n@Singleton\nclass HostsDatabase @Inject constructor(\n application: Application\n) : SQLiteOpenHelper(application, DATABASE_NAME, null, DATABASE_VERSION), HostsRepository {\n\n private val database: SQLiteDatabase by databaseDelegate()\n\n \/\/ Creating Tables\n override fun onCreate(db: SQLiteDatabase) {\n val createHostsTable = \"CREATE TABLE ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}(\" +\n \"${DatabaseUtils.sqlEscapeString(KEY_ID)} INTEGER PRIMARY KEY,\" +\n \"${DatabaseUtils.sqlEscapeString(KEY_NAME)} TEXT\" +\n ')'\n db.execSQL(createHostsTable)\n }\n\n \/\/ Upgrading database\n override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {\n \/\/ Drop older table if it exists\n db.execSQL(\"DROP TABLE IF EXISTS ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}\")\n \/\/ Create tables again\n onCreate(db)\n }\n\n override fun addHosts(hosts: List): Completable = Completable.create {\n database.apply {\n beginTransaction()\n\n for (item in hosts) {\n if (it.isDisposed) {\n endTransaction()\n it.onComplete()\n return@apply\n }\n database.insert(TABLE_HOSTS, null, item.toContentValues())\n }\n\n setTransactionSuccessful()\n endTransaction()\n }\n it.onComplete()\n }\n\n override fun removeAllHosts(): Completable = Completable.fromCallable {\n database.run {\n delete(TABLE_HOSTS, null, null)\n close()\n }\n }\n\n override fun containsHost(host: Host): Boolean {\n database.query(\n TABLE_HOSTS,\n arrayOf(KEY_ID),\n \"$KEY_NAME=?\",\n arrayOf(host.name),\n null,\n null,\n null,\n \"1\"\n ).safeUse {\n return it.moveToFirst()\n }\n\n return false\n }\n\n override fun hasHosts(): Boolean = DatabaseUtils.queryNumEntries(database, TABLE_HOSTS) > 0\n\n override fun allHosts(): Single> = Single.fromCallable {\n return@fromCallable database.query(\n TABLE_HOSTS,\n null,\n null,\n null,\n null,\n null,\n \"$KEY_ID DESC\"\n ).useMap { it.bindToHost() }\n }\n\n \/**\n * Maps the fields of [Host] to [ContentValues].\n *\/\n private fun Host.toContentValues() = ContentValues(3).apply {\n put(KEY_NAME, name)\n }\n\n \/**\n * Binds a [Cursor] to a single [Host].\n *\/\n private fun Cursor.bindToHost() = Host(\n name = getString(getColumnIndex(KEY_NAME))\n )\n\n companion object {\n\n \/\/ Database version\n private const val DATABASE_VERSION = 1\n\n \/\/ Database name\n private const val DATABASE_NAME = \"hostsDatabase\"\n\n \/\/ Host table name\n private const val TABLE_HOSTS = \"hosts\"\n\n \/\/ Host table columns names\n private const val KEY_ID = \"id\"\n private const val KEY_NAME = \"url\"\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage acr.browser.lightning.database.adblock\n\nimport acr.browser.lightning.database.databaseDelegate\nimport acr.browser.lightning.extensions.safeUse\nimport acr.browser.lightning.extensions.useMap\nimport android.app.Application\nimport android.content.ContentValues\nimport android.database.Cursor\nimport android.database.DatabaseUtils\nimport android.database.sqlite.SQLiteDatabase\nimport android.database.sqlite.SQLiteOpenHelper\nimport io.reactivex.Completable\nimport io.reactivex.Single\nimport javax.inject.Inject\nimport javax.inject.Singleton\n\n\/**\n * A database that holds hosts, backed by SQLite.\n *\/\n@Singleton\nclass HostsDatabase @Inject constructor(\n application: Application\n) : SQLiteOpenHelper(application, DATABASE_NAME, null, DATABASE_VERSION), HostsRepository {\n\n private val database: SQLiteDatabase by databaseDelegate()\n\n \/\/ Creating Tables\n override fun onCreate(db: SQLiteDatabase) {\n val createHostsTable = \"CREATE TABLE ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}(\" +\n \"${DatabaseUtils.sqlEscapeString(KEY_ID)} INTEGER PRIMARY KEY,\" +\n \"${DatabaseUtils.sqlEscapeString(KEY_NAME)} TEXT\" +\n ')'\n db.execSQL(createHostsTable)\n }\n\n \/\/ Upgrading database\n override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {\n \/\/ Drop older table if it exists\n db.execSQL(\"DROP TABLE IF EXISTS ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}\")\n \/\/ Create tables again\n onCreate(db)\n }\n\n override fun addHosts(hosts: List): Completable = Completable.create {\n database.apply {\n beginTransaction()\n\n for (item in hosts) {\n if (it.isDisposed) {\n endTransaction()\n it.onComplete()\n return@apply\n }\n database.insert(TABLE_HOSTS, null, item.toContentValues())\n }\n\n setTransactionSuccessful()\n endTransaction()\n }\n it.onComplete()\n }\n\n override fun removeAllHosts(): Completable = Completable.fromCallable {\n database.run {\n delete(TABLE_HOSTS, null, null)\n close()\n }\n }\n\n override fun containsHost(host: Host): Boolean {\n database.query(\n TABLE_HOSTS,\n arrayOf(KEY_ID),\n \"$KEY_NAME=?\",\n arrayOf(host.name),\n null,\n null,\n null,\n \"1\"\n ).safeUse {\n return it.moveToFirst()\n }\n\n return false\n }\n\n override fun hasHosts(): Boolean = DatabaseUtils.queryNumEntries(database, TABLE_HOSTS) > 0\n\n override fun allHosts(): Single> = Single.fromCallable {\n return@fromCallable database.query(\n TABLE_HOSTS,\n null,\n null,\n null,\n null,\n null,\n \"$KEY_ID DESC\"\n ).useMap { it.bindToHost() }\n }\n\n \/**\n * Maps the fields of [Host] to [ContentValues].\n *\/\n private fun Host.toContentValues() = ContentValues(3).apply {\n put(KEY_NAME, name)\n }\n\n \/**\n * Binds a [Cursor] to a single [Host].\n *\/\n private fun Cursor.bindToHost() = Host(\n name = getString(getColumnIndex(KEY_NAME))\n )\n\n companion object {\n\n \/\/ Database version\n private const val DATABASE_VERSION = 1\n\n \/\/ Database name\n private const val DATABASE_NAME = \"hostsDatabase\"\n\n \/\/ Host table name\n private const val TABLE_HOSTS = \"hosts\"\n\n \/\/ Host table columns names\n private const val KEY_ID = \"id\"\n private const val KEY_NAME = \"url\"\n }\n\n}\n\n\nCode-B:\npackage acr.browser.lightning.database.adblock\n\nimport acr.browser.lightning.database.databaseDelegate\nimport acr.browser.lightning.extensions.safeUse\nimport acr.browser.lightning.extensions.useMap\nimport android.app.Application\nimport android.content.ContentValues\nimport android.database.Cursor\nimport android.database.DatabaseUtils\nimport android.database.sqlite.SQLiteDatabase\nimport android.database.sqlite.SQLiteOpenHelper\nimport io.reactivex.Completable\nimport io.reactivex.Single\nimport javax.inject.Inject\nimport javax.inject.Singleton\n\n\/**\n * A database that holds hosts, backed by SQLite.\n *\/\n@Singleton\nclass HostsDatabase @Inject constructor(\n application: Application\n) : SQLiteOpenHelper(application, DATABASE_NAME, null, DATABASE_VERSION), HostsRepository {\n\n private val database: SQLiteDatabase by databaseDelegate()\n\n \/\/ Creating Tables\n override fun onCreate(db: SQLiteDatabase) {\n val createHostsTable = \"CREATE TABLE ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}(\" +\n \"${DatabaseUtils.sqlEscapeString(KEY_NAME)} TEXT PRIMARY KEY\" +\n ')'\n db.execSQL(createHostsTable)\n }\n\n \/\/ Upgrading database\n override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {\n \/\/ Drop older table if it exists\n db.execSQL(\"DROP TABLE IF EXISTS ${DatabaseUtils.sqlEscapeString(TABLE_HOSTS)}\")\n \/\/ Create tables again\n onCreate(db)\n }\n\n override fun addHosts(hosts: List): Completable = Completable.create {\n database.apply {\n beginTransaction()\n\n for (item in hosts) {\n if (it.isDisposed) {\n endTransaction()\n it.onComplete()\n return@apply\n }\n database.insert(TABLE_HOSTS, null, item.toContentValues())\n }\n\n setTransactionSuccessful()\n endTransaction()\n }\n it.onComplete()\n }\n\n override fun removeAllHosts(): Completable = Completable.fromCallable {\n database.run {\n delete(TABLE_HOSTS, null, null)\n close()\n }\n }\n\n override fun containsHost(host: Host): Boolean {\n database.query(\n TABLE_HOSTS,\n arrayOf(KEY_NAME),\n \"$KEY_NAME=?\",\n arrayOf(host.name),\n null,\n null,\n null,\n \"1\"\n ).safeUse {\n return it.moveToFirst()\n }\n\n return false\n }\n\n override fun hasHosts(): Boolean = DatabaseUtils.queryNumEntries(database, TABLE_HOSTS) > 0\n\n override fun allHosts(): Single> = Single.fromCallable {\n return@fromCallable database.query(\n TABLE_HOSTS,\n null,\n null,\n null,\n null,\n null,\n null\n ).useMap { it.bindToHost() }\n }\n\n \/**\n * Maps the fields of [Host] to [ContentValues].\n *\/\n private fun Host.toContentValues() = ContentValues(3).apply {\n put(KEY_NAME, name)\n }\n\n \/**\n * Binds a [Cursor] to a single [Host].\n *\/\n private fun Cursor.bindToHost() = Host(\n name = getString(getColumnIndex(KEY_NAME))\n )\n\n companion object {\n\n \/\/ Database version\n private const val DATABASE_VERSION = 2\n\n \/\/ Database name\n private const val DATABASE_NAME = \"hostsDatabase\"\n\n \/\/ Host table name\n private const val TABLE_HOSTS = \"hosts\"\n\n \/\/ Host table columns names\n private const val KEY_NAME = \"url\"\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/aaronjwood\/PortAuthority\/commit\/c0fc2206d1dfef826f150dc70a2ec34fd4695a8b","commit_message":"'\\\\\"Dont try to scan for hosts if the user isnt connected to the network\\\\n\\\\\"'","source_code":"package com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView ipAddress;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n macAddress.setText(this.wifi.getMacAddress());\n ipAddress.setText(internalIp);\n ssid.setText(this.wifi.getSSID());\n bssid.setText(this.wifi.getBSSID());\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n","target_code":"package com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView ipAddress;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n macAddress.setText(this.wifi.getMacAddress());\n ipAddress.setText(internalIp);\n ssid.setText(this.wifi.getSSID());\n bssid.setText(this.wifi.getBSSID());\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView ipAddress;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n macAddress.setText(this.wifi.getMacAddress());\n ipAddress.setText(internalIp);\n ssid.setText(this.wifi.getSSID());\n bssid.setText(this.wifi.getBSSID());\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView ipAddress;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n macAddress.setText(this.wifi.getMacAddress());\n ipAddress.setText(internalIp);\n ssid.setText(this.wifi.getSSID());\n bssid.setText(this.wifi.getBSSID());\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView ipAddress;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n macAddress.setText(this.wifi.getMacAddress());\n ipAddress.setText(internalIp);\n ssid.setText(this.wifi.getSSID());\n bssid.setText(this.wifi.getBSSID());\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the host scanning part of the code to improve execution time. Write the entire code and no other text in the response.\n\n### Concepts:\n[+] wifi.isConnected()\n[in] onClick function\n\n### Given program:\n```java\npackage com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView ipAddress;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n macAddress.setText(this.wifi.getMacAddress());\n ipAddress.setText(internalIp);\n ssid.setText(this.wifi.getSSID());\n bssid.setText(this.wifi.getBSSID());\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView ipAddress;\n private TextView signalStrength;\n\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n macAddress.setText(this.wifi.getMacAddress());\n ipAddress.setText(internalIp);\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n private Wireless wifi;\n\n private Button discoverHosts;\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n private ListView hostList;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n TextView macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n macAddress.setText(this.wifi.getMacAddress());\n\n TextView ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n ipAddress.setText(internalIp);\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n TextView signalStrength = (TextView) findViewById(R.id.signalStrength);\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList = (ListView) findViewById(R.id.hostList);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n private Wireless wifi;\n\n private Button discoverHosts;\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n private ListView hostList;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n TextView macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n macAddress.setText(this.wifi.getMacAddress());\n\n TextView ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n ipAddress.setText(internalIp);\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n TextView signalStrength = (TextView) findViewById(R.id.signalStrength);\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList = (ListView) findViewById(R.id.hostList);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView ipAddress;\n private TextView signalStrength;\n\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n macAddress.setText(this.wifi.getMacAddress());\n ipAddress.setText(internalIp);\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/experiment322\/controlloid-client\/commit\/0b27363a8326e29d11ff75878450c31f986b8c22","commit_message":"'\\\\\"Optimise analog again\\\\n\\\\n- forgot to apply the optimisation to the function which resets the\\\\nanalog to center","source_code":"import React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n \/\/ noinspection JSSuspiciousNameCombination\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n if (clampedPosition.x !== this.translation.x._value \/\/ eslint-disable-line max-len, no-underscore-dangle\n || clampedPosition.y !== this.translation.y._value) { \/\/ eslint-disable-line max-len, no-underscore-dangle\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n }\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n","target_code":"import React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n \/\/ noinspection JSSuspiciousNameCombination\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n if (clampedPosition.x !== this.translation.x._value \/\/ eslint-disable-line max-len, no-underscore-dangle\n || clampedPosition.y !== this.translation.y._value) { \/\/ eslint-disable-line max-len, no-underscore-dangle\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n }\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n if (this.translation.x._value !== 0 \/\/ eslint-disable-line no-underscore-dangle\n || this.translation.y._value !== 0) { \/\/ eslint-disable-line no-underscore-dangle\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n","pl":"JavaScript XML","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given javascript xml program to optimize and improve the execution time. Write the entire code and no other text:\nimport React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n \/\/ noinspection JSSuspiciousNameCombination\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n if (clampedPosition.x !== this.translation.x._value \/\/ eslint-disable-line max-len, no-underscore-dangle\n || clampedPosition.y !== this.translation.y._value) { \/\/ eslint-disable-line max-len, no-underscore-dangle\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n }\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given javascript xml program to optimize and improve the execution time. Write the entire code and no other text:\nimport React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n \/\/ noinspection JSSuspiciousNameCombination\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n if (clampedPosition.x !== this.translation.x._value \/\/ eslint-disable-line max-len, no-underscore-dangle\n || clampedPosition.y !== this.translation.y._value) { \/\/ eslint-disable-line max-len, no-underscore-dangle\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n }\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n\n\n### Response:\n```javascript xml","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given javascript xml program to optimize and improve the execution time. Write the entire code and no other text:\nimport React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n \/\/ noinspection JSSuspiciousNameCombination\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n if (clampedPosition.x !== this.translation.x._value \/\/ eslint-disable-line max-len, no-underscore-dangle\n || clampedPosition.y !== this.translation.y._value) { \/\/ eslint-disable-line max-len, no-underscore-dangle\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n }\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n\n\n### Response:\n```javascript xml","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the code to optimize analog control and improve bandwidth usage and performance of the android application. Write the entire code and no other text in the response.\n\n### Concepts:\n[in] analogReset function\n[hint] avoid bandwith flooding with position (0, 0)\n[+] translation.x._value\n[+] translation.y._value\n\n### Given program:\n```javascript xml\nimport React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n \/\/ noinspection JSSuspiciousNameCombination\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n if (clampedPosition.x !== this.translation.x._value \/\/ eslint-disable-line max-len, no-underscore-dangle\n || clampedPosition.y !== this.translation.y._value) { \/\/ eslint-disable-line max-len, no-underscore-dangle\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n }\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n\n```\n\n### Response:\n```javascript xml","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\nimport React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n \/\/ noinspection JSSuspiciousNameCombination\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n if (clampedPosition.x !== this.translation.x._value \/\/ eslint-disable-line max-len, no-underscore-dangle\n || clampedPosition.y !== this.translation.y._value) { \/\/ eslint-disable-line max-len, no-underscore-dangle\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n }\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n\n\nCode-B:\nimport React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\nimport React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n\n\nCode-B:\nimport React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n \/\/ noinspection JSSuspiciousNameCombination\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n if (clampedPosition.x !== this.translation.x._value \/\/ eslint-disable-line max-len, no-underscore-dangle\n || clampedPosition.y !== this.translation.y._value) { \/\/ eslint-disable-line max-len, no-underscore-dangle\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n }\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/erikusaj\/fdroidTvClient\/commit\/4d0c4babe6929116b1bddbb271c1f7cb07aceb07","commit_message":"'\\\\\"Various speedups in the app views. Compact layout still needs restarting.\\\\n\\\\\"'","source_code":"package org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.R;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n View v = convertView;\n if (v == null) {\n LayoutInflater vi = (LayoutInflater) mContext\n .getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n v = vi.inflate(R.layout.applistitem, null);\n }\n DB.App app = items.get(position);\n\n TextView name = (TextView) v.findViewById(R.id.name);\n name.setText(app.name);\n\n TextView summary = (TextView) v.findViewById(R.id.summary);\n summary.setText(app.summary);\n\n TextView status = (TextView) v.findViewById(R.id.status);\n TextView license = (TextView) v.findViewById(R.id.license);\n\n ImageView iconUpdates = (ImageView)v.findViewById(R.id.icon_status_has_updates);\n ImageView iconInstalled = (ImageView)v.findViewById(R.id.icon_status_installed);\n\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);\n\n if (prefs.getBoolean(\"compactlayout\", false)) {\n\n status.setVisibility(View.GONE);\n license.setVisibility(View.GONE);\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(RelativeLayout.RIGHT_OF, R.id.icon);\n summary.setLayoutParams(summaryLayout);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n iconUpdates.setVisibility(View.VISIBLE);\n } else {\n iconUpdates.setVisibility(View.GONE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconInstalled.setVisibility(View.VISIBLE);\n } else {\n iconInstalled.setVisibility(View.GONE);\n }\n\n } else {\n\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n\n iconUpdates.setVisibility(View.GONE);\n iconInstalled.setVisibility(View.GONE);\n }\n\n ImageView icon = (ImageView) v.findViewById(R.id.icon);\n File icn = new File(DB.getIconsPath(), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n icon.setImageURI(Uri.parse(icn.getPath()));\n } else {\n icon.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n \/\/ Disable it all if it isn't compatible...\n View[] views = { v, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(app.compatible);\n }\n\n return v;\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n","target_code":"package org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.R;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n boolean pref_compactlayout;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n boolean init = false;\n\n if (convertView == null) {\n convertView = ((LayoutInflater) mContext.getSystemService(\n Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.applistitem, null);\n init = true;\n }\n\n ImageView iconUpdates = (ImageView) convertView.findViewById(R.id.icon_status_has_updates);\n ImageView iconInstalled = (ImageView) convertView.findViewById(R.id.icon_status_installed);\n\n TextView name = (TextView) convertView.findViewById(R.id.name);\n TextView summary = (TextView) convertView.findViewById(R.id.summary);\n TextView status = (TextView) convertView.findViewById(R.id.status);\n TextView license = (TextView) convertView.findViewById(R.id.license);\n\n DB.App app = items.get(position);\n\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n\n name.setText(app.name);\n summary.setText(app.summary);\n\n ImageView icon = (ImageView) convertView.findViewById(R.id.icon);\n File icn = new File(DB.getIconsPath(), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n icon.setImageURI(Uri.parse(icn.getPath()));\n } else {\n icon.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n iconUpdates.setVisibility(View.GONE);\n iconInstalled.setVisibility(View.GONE);\n\n if (init) {\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(mContext);\n pref_compactlayout = prefs.getBoolean(\"compactlayout\", false);\n\n if (pref_compactlayout == true) {\n status.setVisibility(View.GONE);\n license.setVisibility(View.GONE);\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(RelativeLayout.END_OF, R.id.icon);\n summary.setLayoutParams(summaryLayout);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setVisibility(View.VISIBLE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setVisibility(View.VISIBLE);\n }\n }\n }\n\n \/\/ Disable it all if it isn't compatible...\n View[] views = { convertView, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(app.compatible);\n }\n\n return convertView;\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.R;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n View v = convertView;\n if (v == null) {\n LayoutInflater vi = (LayoutInflater) mContext\n .getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n v = vi.inflate(R.layout.applistitem, null);\n }\n DB.App app = items.get(position);\n\n TextView name = (TextView) v.findViewById(R.id.name);\n name.setText(app.name);\n\n TextView summary = (TextView) v.findViewById(R.id.summary);\n summary.setText(app.summary);\n\n TextView status = (TextView) v.findViewById(R.id.status);\n TextView license = (TextView) v.findViewById(R.id.license);\n\n ImageView iconUpdates = (ImageView)v.findViewById(R.id.icon_status_has_updates);\n ImageView iconInstalled = (ImageView)v.findViewById(R.id.icon_status_installed);\n\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);\n\n if (prefs.getBoolean(\"compactlayout\", false)) {\n\n status.setVisibility(View.GONE);\n license.setVisibility(View.GONE);\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(RelativeLayout.RIGHT_OF, R.id.icon);\n summary.setLayoutParams(summaryLayout);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n iconUpdates.setVisibility(View.VISIBLE);\n } else {\n iconUpdates.setVisibility(View.GONE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconInstalled.setVisibility(View.VISIBLE);\n } else {\n iconInstalled.setVisibility(View.GONE);\n }\n\n } else {\n\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n\n iconUpdates.setVisibility(View.GONE);\n iconInstalled.setVisibility(View.GONE);\n }\n\n ImageView icon = (ImageView) v.findViewById(R.id.icon);\n File icn = new File(DB.getIconsPath(), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n icon.setImageURI(Uri.parse(icn.getPath()));\n } else {\n icon.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n \/\/ Disable it all if it isn't compatible...\n View[] views = { v, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(app.compatible);\n }\n\n return v;\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.R;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n View v = convertView;\n if (v == null) {\n LayoutInflater vi = (LayoutInflater) mContext\n .getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n v = vi.inflate(R.layout.applistitem, null);\n }\n DB.App app = items.get(position);\n\n TextView name = (TextView) v.findViewById(R.id.name);\n name.setText(app.name);\n\n TextView summary = (TextView) v.findViewById(R.id.summary);\n summary.setText(app.summary);\n\n TextView status = (TextView) v.findViewById(R.id.status);\n TextView license = (TextView) v.findViewById(R.id.license);\n\n ImageView iconUpdates = (ImageView)v.findViewById(R.id.icon_status_has_updates);\n ImageView iconInstalled = (ImageView)v.findViewById(R.id.icon_status_installed);\n\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);\n\n if (prefs.getBoolean(\"compactlayout\", false)) {\n\n status.setVisibility(View.GONE);\n license.setVisibility(View.GONE);\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(RelativeLayout.RIGHT_OF, R.id.icon);\n summary.setLayoutParams(summaryLayout);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n iconUpdates.setVisibility(View.VISIBLE);\n } else {\n iconUpdates.setVisibility(View.GONE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconInstalled.setVisibility(View.VISIBLE);\n } else {\n iconInstalled.setVisibility(View.GONE);\n }\n\n } else {\n\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n\n iconUpdates.setVisibility(View.GONE);\n iconInstalled.setVisibility(View.GONE);\n }\n\n ImageView icon = (ImageView) v.findViewById(R.id.icon);\n File icn = new File(DB.getIconsPath(), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n icon.setImageURI(Uri.parse(icn.getPath()));\n } else {\n icon.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n \/\/ Disable it all if it isn't compatible...\n View[] views = { v, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(app.compatible);\n }\n\n return v;\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.R;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n View v = convertView;\n if (v == null) {\n LayoutInflater vi = (LayoutInflater) mContext\n .getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n v = vi.inflate(R.layout.applistitem, null);\n }\n DB.App app = items.get(position);\n\n TextView name = (TextView) v.findViewById(R.id.name);\n name.setText(app.name);\n\n TextView summary = (TextView) v.findViewById(R.id.summary);\n summary.setText(app.summary);\n\n TextView status = (TextView) v.findViewById(R.id.status);\n TextView license = (TextView) v.findViewById(R.id.license);\n\n ImageView iconUpdates = (ImageView)v.findViewById(R.id.icon_status_has_updates);\n ImageView iconInstalled = (ImageView)v.findViewById(R.id.icon_status_installed);\n\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);\n\n if (prefs.getBoolean(\"compactlayout\", false)) {\n\n status.setVisibility(View.GONE);\n license.setVisibility(View.GONE);\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(RelativeLayout.RIGHT_OF, R.id.icon);\n summary.setLayoutParams(summaryLayout);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n iconUpdates.setVisibility(View.VISIBLE);\n } else {\n iconUpdates.setVisibility(View.GONE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconInstalled.setVisibility(View.VISIBLE);\n } else {\n iconInstalled.setVisibility(View.GONE);\n }\n\n } else {\n\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n\n iconUpdates.setVisibility(View.GONE);\n iconInstalled.setVisibility(View.GONE);\n }\n\n ImageView icon = (ImageView) v.findViewById(R.id.icon);\n File icn = new File(DB.getIconsPath(), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n icon.setImageURI(Uri.parse(icn.getPath()));\n } else {\n icon.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n \/\/ Disable it all if it isn't compatible...\n View[] views = { v, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(app.compatible);\n }\n\n return v;\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the app view code to improve execution time. Write the entire code and no other text in the response.\n\n### Concepts:\n[in] getView function\n[hint] reuse 'convertView' instead of making a copy\nperform layout operations only when convertView is initialized and compactlayout is preferred.\n\n### Given program:\n```java\npackage org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.R;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n View v = convertView;\n if (v == null) {\n LayoutInflater vi = (LayoutInflater) mContext\n .getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n v = vi.inflate(R.layout.applistitem, null);\n }\n DB.App app = items.get(position);\n\n TextView name = (TextView) v.findViewById(R.id.name);\n name.setText(app.name);\n\n TextView summary = (TextView) v.findViewById(R.id.summary);\n summary.setText(app.summary);\n\n TextView status = (TextView) v.findViewById(R.id.status);\n TextView license = (TextView) v.findViewById(R.id.license);\n\n ImageView iconUpdates = (ImageView)v.findViewById(R.id.icon_status_has_updates);\n ImageView iconInstalled = (ImageView)v.findViewById(R.id.icon_status_installed);\n\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);\n\n if (prefs.getBoolean(\"compactlayout\", false)) {\n\n status.setVisibility(View.GONE);\n license.setVisibility(View.GONE);\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(RelativeLayout.RIGHT_OF, R.id.icon);\n summary.setLayoutParams(summaryLayout);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n iconUpdates.setVisibility(View.VISIBLE);\n } else {\n iconUpdates.setVisibility(View.GONE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconInstalled.setVisibility(View.VISIBLE);\n } else {\n iconInstalled.setVisibility(View.GONE);\n }\n\n } else {\n\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n\n iconUpdates.setVisibility(View.GONE);\n iconInstalled.setVisibility(View.GONE);\n }\n\n ImageView icon = (ImageView) v.findViewById(R.id.icon);\n File icn = new File(DB.getIconsPath(), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n icon.setImageURI(Uri.parse(icn.getPath()));\n } else {\n icon.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n \/\/ Disable it all if it isn't compatible...\n View[] views = { v, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(app.compatible);\n }\n\n return v;\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView ipAddress;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n macAddress.setText(this.wifi.getMacAddress());\n ipAddress.setText(internalIp);\n ssid.setText(this.wifi.getSSID());\n bssid.setText(this.wifi.getBSSID());\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView ipAddress;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n macAddress.setText(this.wifi.getMacAddress());\n ipAddress.setText(internalIp);\n ssid.setText(this.wifi.getSSID());\n bssid.setText(this.wifi.getBSSID());\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView ipAddress;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n macAddress.setText(this.wifi.getMacAddress());\n ipAddress.setText(internalIp);\n ssid.setText(this.wifi.getSSID());\n bssid.setText(this.wifi.getBSSID());\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.Network.Discovery;\nimport com.aaronjwood.portauthority.Network.Wireless;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends Activity {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView ipAddress;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n\n private ArrayList hosts = new ArrayList<>();\n private ArrayAdapter adapter;\n\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.ipAddress = (TextView) findViewById(R.id.internalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n if(savedInstanceState != null) {\n this.hosts = savedInstanceState.getStringArrayList(\"hosts\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.hosts);\n this.hostList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n\n this.wifi = new Wireless(this);\n this.wifi.getExternalIpAddress();\n\n final String internalIp = this.wifi.getInternalIpAddress();\n\n macAddress.setText(this.wifi.getMacAddress());\n ipAddress.setText(internalIp);\n ssid.setText(this.wifi.getSSID());\n bssid.setText(this.wifi.getBSSID());\n\n final Handler mHandler = new Handler();\n mHandler.postDelayed(new Runnable() {\n\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n Toast.makeText(getApplicationContext(), \"Finding hosts on your network...\", Toast.LENGTH_SHORT).show();\n\n hosts.clear();\n\n adapter = new ArrayAdapter<>(v.getContext(), android.R.layout.simple_list_item_1, hosts);\n hostList.setAdapter(adapter);\n\n Discovery discovery = new Discovery((Activity) v.getContext(), internalIp);\n discovery.execute();\n }\n });\n }\n\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"hosts\", this.hosts);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n\n \/\/ Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n \/\/ Handle action bar item clicks here. The action bar will\n \/\/ automatically handle clicks on the Home\/Up button, so long\n \/\/ as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n if(id == R.id.action_settings) {\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/leonardbos\/FirefoxFocusASV\/commit\/85ead3bd940bd445bbaff6a4a4d30ebca6b7c7a6","commit_message":"'\\\\\"[detekt] UrlAutoCompleteFilter: Avoid using spread operator. (#1308)\\\\n\\\\nSpreadOperator - [getAvailableDomainLists] at app\/src\/main\/java\/org\/mozilla\/focus\/autocomplete\/UrlAutoCompleteFilter.kt:112:31\\\\n\\\\n \\\\\"Using Kotlin\\'s spread operator","source_code":"\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.autocomplete\n\nimport android.content.Context\nimport android.util.Log\nimport kotlinx.coroutines.experimental.CommonPool\nimport kotlinx.coroutines.experimental.android.UI\nimport kotlinx.coroutines.experimental.async\nimport kotlinx.coroutines.experimental.launch\nimport org.mozilla.focus.locale.Locales\nimport org.mozilla.focus.utils.Settings\nimport org.mozilla.focus.widget.InlineAutocompleteEditText\nimport java.io.IOException\nimport java.util.*\nimport kotlin.collections.LinkedHashSet\n\nclass UrlAutoCompleteFilter : InlineAutocompleteEditText.OnFilterListener {\n companion object {\n private val LOG_TAG = \"UrlAutoCompleteFilter\"\n }\n\n private var settings : Settings? = null\n\n private var customDomains : List = emptyList()\n private var preInstalledDomains : List = emptyList()\n\n override fun onFilter(rawSearchText: String, view: InlineAutocompleteEditText?) {\n if (view == null) {\n return\n }\n\n \/\/ Search terms are all lowercase already, we just need to lowercase the search text\n val searchText = rawSearchText.toLowerCase(Locale.US)\n\n settings?.let {\n if (it.shouldAutocompleteFromCustomDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, customDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n\n if (it.shouldAutocompleteFromShippedDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, preInstalledDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n }\n }\n\n private fun tryToAutocomplete(searchText: String, domains: List): String? {\n domains.forEach {\n val wwwDomain = \"www.\" + it\n if (wwwDomain.startsWith(searchText)) {\n return wwwDomain\n }\n\n if (it.startsWith(searchText)) {\n return it\n }\n }\n\n return null\n }\n\n internal fun onDomainsLoaded(domains: List, customDomains: List) {\n this.preInstalledDomains = domains\n this.customDomains = customDomains\n }\n\n fun load(context: Context, loadDomainsFromDisk: Boolean = true) {\n settings = Settings.getInstance(context)\n\n if (loadDomainsFromDisk) {\n launch(UI) {\n val domains = async(CommonPool) { loadDomains(context) }\n val customDomains = async(CommonPool) { CustomAutocomplete.loadCustomAutoCompleteDomains(context) }\n\n onDomainsLoaded(domains.await(), customDomains.await())\n }\n }\n }\n\n private suspend fun loadDomains(context: Context): List {\n val domains = LinkedHashSet()\n val availableLists = getAvailableDomainLists(context)\n\n \/\/ First load the country specific lists following the default locale order\n Locales.getCountriesInDefaultLocaleList()\n .asSequence()\n .filter { availableLists.contains(it) }\n .forEach { loadDomainsForLanguage(context, domains, it) }\n\n \/\/ And then add domains from the global list\n loadDomainsForLanguage(context, domains, \"global\")\n\n return domains.toList()\n }\n\n private fun getAvailableDomainLists(context: Context): Set {\n val availableDomains = LinkedHashSet()\n\n val assetManager = context.assets\n\n try {\n Collections.addAll(availableDomains, *assetManager.list(\"domains\"))\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not list domain list directory\")\n }\n\n return availableDomains\n }\n\n private fun loadDomainsForLanguage(context: Context, domains: MutableSet, country: String) {\n val assetManager = context.assets\n\n try {\n domains.addAll(\n assetManager.open(\"domains\/\" + country).bufferedReader().readLines())\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not load domain list: \" + country)\n }\n }\n\n \/**\n * Our autocomplete list is all lower case, however the search text might be mixed case.\n * Our autocomplete EditText code does more string comparison, which fails if the suggestion\n * doesn't exactly match searchText (ie. if casing differs). It's simplest to just build a suggestion\n * that exactly matches the search text - which is what this method is for:\n *\/\n private fun prepareAutocompleteResult(rawSearchText: String, lowerCaseResult: String) =\n rawSearchText + lowerCaseResult.substring(rawSearchText.length)\n}\n","target_code":"\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.autocomplete\n\nimport android.content.Context\nimport android.util.Log\nimport kotlinx.coroutines.experimental.CommonPool\nimport kotlinx.coroutines.experimental.android.UI\nimport kotlinx.coroutines.experimental.async\nimport kotlinx.coroutines.experimental.launch\nimport org.mozilla.focus.locale.Locales\nimport org.mozilla.focus.utils.Settings\nimport org.mozilla.focus.widget.InlineAutocompleteEditText\nimport java.io.IOException\nimport java.util.*\nimport kotlin.collections.LinkedHashSet\n\nclass UrlAutoCompleteFilter : InlineAutocompleteEditText.OnFilterListener {\n companion object {\n private val LOG_TAG = \"UrlAutoCompleteFilter\"\n }\n\n private var settings : Settings? = null\n\n private var customDomains : List = emptyList()\n private var preInstalledDomains : List = emptyList()\n\n override fun onFilter(rawSearchText: String, view: InlineAutocompleteEditText?) {\n if (view == null) {\n return\n }\n\n \/\/ Search terms are all lowercase already, we just need to lowercase the search text\n val searchText = rawSearchText.toLowerCase(Locale.US)\n\n settings?.let {\n if (it.shouldAutocompleteFromCustomDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, customDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n\n if (it.shouldAutocompleteFromShippedDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, preInstalledDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n }\n }\n\n private fun tryToAutocomplete(searchText: String, domains: List): String? {\n domains.forEach {\n val wwwDomain = \"www.\" + it\n if (wwwDomain.startsWith(searchText)) {\n return wwwDomain\n }\n\n if (it.startsWith(searchText)) {\n return it\n }\n }\n\n return null\n }\n\n internal fun onDomainsLoaded(domains: List, customDomains: List) {\n this.preInstalledDomains = domains\n this.customDomains = customDomains\n }\n\n fun load(context: Context, loadDomainsFromDisk: Boolean = true) {\n settings = Settings.getInstance(context)\n\n if (loadDomainsFromDisk) {\n launch(UI) {\n val domains = async(CommonPool) { loadDomains(context) }\n val customDomains = async(CommonPool) { CustomAutocomplete.loadCustomAutoCompleteDomains(context) }\n\n onDomainsLoaded(domains.await(), customDomains.await())\n }\n }\n }\n\n private suspend fun loadDomains(context: Context): List {\n val domains = LinkedHashSet()\n val availableLists = getAvailableDomainLists(context)\n\n \/\/ First load the country specific lists following the default locale order\n Locales.getCountriesInDefaultLocaleList()\n .asSequence()\n .filter { availableLists.contains(it) }\n .forEach { loadDomainsForLanguage(context, domains, it) }\n\n \/\/ And then add domains from the global list\n loadDomainsForLanguage(context, domains, \"global\")\n\n return domains.toList()\n }\n\n private fun getAvailableDomainLists(context: Context): Set {\n val availableDomains = LinkedHashSet()\n\n val assetManager = context.assets\n\n try {\n availableDomains.addAll(assetManager.list(\"domains\"))\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not list domain list directory\")\n }\n\n return availableDomains\n }\n\n private fun loadDomainsForLanguage(context: Context, domains: MutableSet, country: String) {\n val assetManager = context.assets\n\n try {\n domains.addAll(\n assetManager.open(\"domains\/\" + country).bufferedReader().readLines())\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not load domain list: \" + country)\n }\n }\n\n \/**\n * Our autocomplete list is all lower case, however the search text might be mixed case.\n * Our autocomplete EditText code does more string comparison, which fails if the suggestion\n * doesn't exactly match searchText (ie. if casing differs). It's simplest to just build a suggestion\n * that exactly matches the search text - which is what this method is for:\n *\/\n private fun prepareAutocompleteResult(rawSearchText: String, lowerCaseResult: String) =\n rawSearchText + lowerCaseResult.substring(rawSearchText.length)\n}\n","pl":"Kotlin","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given kotlin program to optimize and improve the execution time. Write the entire code and no other text:\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.autocomplete\n\nimport android.content.Context\nimport android.util.Log\nimport kotlinx.coroutines.experimental.CommonPool\nimport kotlinx.coroutines.experimental.android.UI\nimport kotlinx.coroutines.experimental.async\nimport kotlinx.coroutines.experimental.launch\nimport org.mozilla.focus.locale.Locales\nimport org.mozilla.focus.utils.Settings\nimport org.mozilla.focus.widget.InlineAutocompleteEditText\nimport java.io.IOException\nimport java.util.*\nimport kotlin.collections.LinkedHashSet\n\nclass UrlAutoCompleteFilter : InlineAutocompleteEditText.OnFilterListener {\n companion object {\n private val LOG_TAG = \"UrlAutoCompleteFilter\"\n }\n\n private var settings : Settings? = null\n\n private var customDomains : List = emptyList()\n private var preInstalledDomains : List = emptyList()\n\n override fun onFilter(rawSearchText: String, view: InlineAutocompleteEditText?) {\n if (view == null) {\n return\n }\n\n \/\/ Search terms are all lowercase already, we just need to lowercase the search text\n val searchText = rawSearchText.toLowerCase(Locale.US)\n\n settings?.let {\n if (it.shouldAutocompleteFromCustomDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, customDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n\n if (it.shouldAutocompleteFromShippedDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, preInstalledDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n }\n }\n\n private fun tryToAutocomplete(searchText: String, domains: List): String? {\n domains.forEach {\n val wwwDomain = \"www.\" + it\n if (wwwDomain.startsWith(searchText)) {\n return wwwDomain\n }\n\n if (it.startsWith(searchText)) {\n return it\n }\n }\n\n return null\n }\n\n internal fun onDomainsLoaded(domains: List, customDomains: List) {\n this.preInstalledDomains = domains\n this.customDomains = customDomains\n }\n\n fun load(context: Context, loadDomainsFromDisk: Boolean = true) {\n settings = Settings.getInstance(context)\n\n if (loadDomainsFromDisk) {\n launch(UI) {\n val domains = async(CommonPool) { loadDomains(context) }\n val customDomains = async(CommonPool) { CustomAutocomplete.loadCustomAutoCompleteDomains(context) }\n\n onDomainsLoaded(domains.await(), customDomains.await())\n }\n }\n }\n\n private suspend fun loadDomains(context: Context): List {\n val domains = LinkedHashSet()\n val availableLists = getAvailableDomainLists(context)\n\n \/\/ First load the country specific lists following the default locale order\n Locales.getCountriesInDefaultLocaleList()\n .asSequence()\n .filter { availableLists.contains(it) }\n .forEach { loadDomainsForLanguage(context, domains, it) }\n\n \/\/ And then add domains from the global list\n loadDomainsForLanguage(context, domains, \"global\")\n\n return domains.toList()\n }\n\n private fun getAvailableDomainLists(context: Context): Set {\n val availableDomains = LinkedHashSet()\n\n val assetManager = context.assets\n\n try {\n Collections.addAll(availableDomains, *assetManager.list(\"domains\"))\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not list domain list directory\")\n }\n\n return availableDomains\n }\n\n private fun loadDomainsForLanguage(context: Context, domains: MutableSet, country: String) {\n val assetManager = context.assets\n\n try {\n domains.addAll(\n assetManager.open(\"domains\/\" + country).bufferedReader().readLines())\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not load domain list: \" + country)\n }\n }\n\n \/**\n * Our autocomplete list is all lower case, however the search text might be mixed case.\n * Our autocomplete EditText code does more string comparison, which fails if the suggestion\n * doesn't exactly match searchText (ie. if casing differs). It's simplest to just build a suggestion\n * that exactly matches the search text - which is what this method is for:\n *\/\n private fun prepareAutocompleteResult(rawSearchText: String, lowerCaseResult: String) =\n rawSearchText + lowerCaseResult.substring(rawSearchText.length)\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given kotlin program to optimize and improve the execution time. Write the entire code and no other text:\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.autocomplete\n\nimport android.content.Context\nimport android.util.Log\nimport kotlinx.coroutines.experimental.CommonPool\nimport kotlinx.coroutines.experimental.android.UI\nimport kotlinx.coroutines.experimental.async\nimport kotlinx.coroutines.experimental.launch\nimport org.mozilla.focus.locale.Locales\nimport org.mozilla.focus.utils.Settings\nimport org.mozilla.focus.widget.InlineAutocompleteEditText\nimport java.io.IOException\nimport java.util.*\nimport kotlin.collections.LinkedHashSet\n\nclass UrlAutoCompleteFilter : InlineAutocompleteEditText.OnFilterListener {\n companion object {\n private val LOG_TAG = \"UrlAutoCompleteFilter\"\n }\n\n private var settings : Settings? = null\n\n private var customDomains : List = emptyList()\n private var preInstalledDomains : List = emptyList()\n\n override fun onFilter(rawSearchText: String, view: InlineAutocompleteEditText?) {\n if (view == null) {\n return\n }\n\n \/\/ Search terms are all lowercase already, we just need to lowercase the search text\n val searchText = rawSearchText.toLowerCase(Locale.US)\n\n settings?.let {\n if (it.shouldAutocompleteFromCustomDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, customDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n\n if (it.shouldAutocompleteFromShippedDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, preInstalledDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n }\n }\n\n private fun tryToAutocomplete(searchText: String, domains: List): String? {\n domains.forEach {\n val wwwDomain = \"www.\" + it\n if (wwwDomain.startsWith(searchText)) {\n return wwwDomain\n }\n\n if (it.startsWith(searchText)) {\n return it\n }\n }\n\n return null\n }\n\n internal fun onDomainsLoaded(domains: List, customDomains: List) {\n this.preInstalledDomains = domains\n this.customDomains = customDomains\n }\n\n fun load(context: Context, loadDomainsFromDisk: Boolean = true) {\n settings = Settings.getInstance(context)\n\n if (loadDomainsFromDisk) {\n launch(UI) {\n val domains = async(CommonPool) { loadDomains(context) }\n val customDomains = async(CommonPool) { CustomAutocomplete.loadCustomAutoCompleteDomains(context) }\n\n onDomainsLoaded(domains.await(), customDomains.await())\n }\n }\n }\n\n private suspend fun loadDomains(context: Context): List {\n val domains = LinkedHashSet()\n val availableLists = getAvailableDomainLists(context)\n\n \/\/ First load the country specific lists following the default locale order\n Locales.getCountriesInDefaultLocaleList()\n .asSequence()\n .filter { availableLists.contains(it) }\n .forEach { loadDomainsForLanguage(context, domains, it) }\n\n \/\/ And then add domains from the global list\n loadDomainsForLanguage(context, domains, \"global\")\n\n return domains.toList()\n }\n\n private fun getAvailableDomainLists(context: Context): Set {\n val availableDomains = LinkedHashSet()\n\n val assetManager = context.assets\n\n try {\n Collections.addAll(availableDomains, *assetManager.list(\"domains\"))\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not list domain list directory\")\n }\n\n return availableDomains\n }\n\n private fun loadDomainsForLanguage(context: Context, domains: MutableSet, country: String) {\n val assetManager = context.assets\n\n try {\n domains.addAll(\n assetManager.open(\"domains\/\" + country).bufferedReader().readLines())\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not load domain list: \" + country)\n }\n }\n\n \/**\n * Our autocomplete list is all lower case, however the search text might be mixed case.\n * Our autocomplete EditText code does more string comparison, which fails if the suggestion\n * doesn't exactly match searchText (ie. if casing differs). It's simplest to just build a suggestion\n * that exactly matches the search text - which is what this method is for:\n *\/\n private fun prepareAutocompleteResult(rawSearchText: String, lowerCaseResult: String) =\n rawSearchText + lowerCaseResult.substring(rawSearchText.length)\n}\n\n\n### Response:\n```kotlin","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given kotlin program to optimize and improve the execution time. Write the entire code and no other text:\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.autocomplete\n\nimport android.content.Context\nimport android.util.Log\nimport kotlinx.coroutines.experimental.CommonPool\nimport kotlinx.coroutines.experimental.android.UI\nimport kotlinx.coroutines.experimental.async\nimport kotlinx.coroutines.experimental.launch\nimport org.mozilla.focus.locale.Locales\nimport org.mozilla.focus.utils.Settings\nimport org.mozilla.focus.widget.InlineAutocompleteEditText\nimport java.io.IOException\nimport java.util.*\nimport kotlin.collections.LinkedHashSet\n\nclass UrlAutoCompleteFilter : InlineAutocompleteEditText.OnFilterListener {\n companion object {\n private val LOG_TAG = \"UrlAutoCompleteFilter\"\n }\n\n private var settings : Settings? = null\n\n private var customDomains : List = emptyList()\n private var preInstalledDomains : List = emptyList()\n\n override fun onFilter(rawSearchText: String, view: InlineAutocompleteEditText?) {\n if (view == null) {\n return\n }\n\n \/\/ Search terms are all lowercase already, we just need to lowercase the search text\n val searchText = rawSearchText.toLowerCase(Locale.US)\n\n settings?.let {\n if (it.shouldAutocompleteFromCustomDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, customDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n\n if (it.shouldAutocompleteFromShippedDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, preInstalledDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n }\n }\n\n private fun tryToAutocomplete(searchText: String, domains: List): String? {\n domains.forEach {\n val wwwDomain = \"www.\" + it\n if (wwwDomain.startsWith(searchText)) {\n return wwwDomain\n }\n\n if (it.startsWith(searchText)) {\n return it\n }\n }\n\n return null\n }\n\n internal fun onDomainsLoaded(domains: List, customDomains: List) {\n this.preInstalledDomains = domains\n this.customDomains = customDomains\n }\n\n fun load(context: Context, loadDomainsFromDisk: Boolean = true) {\n settings = Settings.getInstance(context)\n\n if (loadDomainsFromDisk) {\n launch(UI) {\n val domains = async(CommonPool) { loadDomains(context) }\n val customDomains = async(CommonPool) { CustomAutocomplete.loadCustomAutoCompleteDomains(context) }\n\n onDomainsLoaded(domains.await(), customDomains.await())\n }\n }\n }\n\n private suspend fun loadDomains(context: Context): List {\n val domains = LinkedHashSet()\n val availableLists = getAvailableDomainLists(context)\n\n \/\/ First load the country specific lists following the default locale order\n Locales.getCountriesInDefaultLocaleList()\n .asSequence()\n .filter { availableLists.contains(it) }\n .forEach { loadDomainsForLanguage(context, domains, it) }\n\n \/\/ And then add domains from the global list\n loadDomainsForLanguage(context, domains, \"global\")\n\n return domains.toList()\n }\n\n private fun getAvailableDomainLists(context: Context): Set {\n val availableDomains = LinkedHashSet()\n\n val assetManager = context.assets\n\n try {\n Collections.addAll(availableDomains, *assetManager.list(\"domains\"))\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not list domain list directory\")\n }\n\n return availableDomains\n }\n\n private fun loadDomainsForLanguage(context: Context, domains: MutableSet, country: String) {\n val assetManager = context.assets\n\n try {\n domains.addAll(\n assetManager.open(\"domains\/\" + country).bufferedReader().readLines())\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not load domain list: \" + country)\n }\n }\n\n \/**\n * Our autocomplete list is all lower case, however the search text might be mixed case.\n * Our autocomplete EditText code does more string comparison, which fails if the suggestion\n * doesn't exactly match searchText (ie. if casing differs). It's simplest to just build a suggestion\n * that exactly matches the search text - which is what this method is for:\n *\/\n private fun prepareAutocompleteResult(rawSearchText: String, lowerCaseResult: String) =\n rawSearchText + lowerCaseResult.substring(rawSearchText.length)\n}\n\n\n### Response:\n```kotlin","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite getAvailableDomainLists functions to improve execution time by avoiding spread operator. Write the entire code and no other text in the response.\n\n### Concepts:\n[in] getAvailableDomainLists function\n[hint] Using Kotlin's spread operator, which causes a full copy of the array to be created before calling a method, has a very high performance penalty (and that might increase with the size of the array).\n\n### Given program:\n```kotlin\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.autocomplete\n\nimport android.content.Context\nimport android.util.Log\nimport kotlinx.coroutines.experimental.CommonPool\nimport kotlinx.coroutines.experimental.android.UI\nimport kotlinx.coroutines.experimental.async\nimport kotlinx.coroutines.experimental.launch\nimport org.mozilla.focus.locale.Locales\nimport org.mozilla.focus.utils.Settings\nimport org.mozilla.focus.widget.InlineAutocompleteEditText\nimport java.io.IOException\nimport java.util.*\nimport kotlin.collections.LinkedHashSet\n\nclass UrlAutoCompleteFilter : InlineAutocompleteEditText.OnFilterListener {\n companion object {\n private val LOG_TAG = \"UrlAutoCompleteFilter\"\n }\n\n private var settings : Settings? = null\n\n private var customDomains : List = emptyList()\n private var preInstalledDomains : List = emptyList()\n\n override fun onFilter(rawSearchText: String, view: InlineAutocompleteEditText?) {\n if (view == null) {\n return\n }\n\n \/\/ Search terms are all lowercase already, we just need to lowercase the search text\n val searchText = rawSearchText.toLowerCase(Locale.US)\n\n settings?.let {\n if (it.shouldAutocompleteFromCustomDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, customDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n\n if (it.shouldAutocompleteFromShippedDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, preInstalledDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n }\n }\n\n private fun tryToAutocomplete(searchText: String, domains: List): String? {\n domains.forEach {\n val wwwDomain = \"www.\" + it\n if (wwwDomain.startsWith(searchText)) {\n return wwwDomain\n }\n\n if (it.startsWith(searchText)) {\n return it\n }\n }\n\n return null\n }\n\n internal fun onDomainsLoaded(domains: List, customDomains: List) {\n this.preInstalledDomains = domains\n this.customDomains = customDomains\n }\n\n fun load(context: Context, loadDomainsFromDisk: Boolean = true) {\n settings = Settings.getInstance(context)\n\n if (loadDomainsFromDisk) {\n launch(UI) {\n val domains = async(CommonPool) { loadDomains(context) }\n val customDomains = async(CommonPool) { CustomAutocomplete.loadCustomAutoCompleteDomains(context) }\n\n onDomainsLoaded(domains.await(), customDomains.await())\n }\n }\n }\n\n private suspend fun loadDomains(context: Context): List {\n val domains = LinkedHashSet()\n val availableLists = getAvailableDomainLists(context)\n\n \/\/ First load the country specific lists following the default locale order\n Locales.getCountriesInDefaultLocaleList()\n .asSequence()\n .filter { availableLists.contains(it) }\n .forEach { loadDomainsForLanguage(context, domains, it) }\n\n \/\/ And then add domains from the global list\n loadDomainsForLanguage(context, domains, \"global\")\n\n return domains.toList()\n }\n\n private fun getAvailableDomainLists(context: Context): Set {\n val availableDomains = LinkedHashSet()\n\n val assetManager = context.assets\n\n try {\n Collections.addAll(availableDomains, *assetManager.list(\"domains\"))\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not list domain list directory\")\n }\n\n return availableDomains\n }\n\n private fun loadDomainsForLanguage(context: Context, domains: MutableSet, country: String) {\n val assetManager = context.assets\n\n try {\n domains.addAll(\n assetManager.open(\"domains\/\" + country).bufferedReader().readLines())\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not load domain list: \" + country)\n }\n }\n\n \/**\n * Our autocomplete list is all lower case, however the search text might be mixed case.\n * Our autocomplete EditText code does more string comparison, which fails if the suggestion\n * doesn't exactly match searchText (ie. if casing differs). It's simplest to just build a suggestion\n * that exactly matches the search text - which is what this method is for:\n *\/\n private fun prepareAutocompleteResult(rawSearchText: String, lowerCaseResult: String) =\n rawSearchText + lowerCaseResult.substring(rawSearchText.length)\n}\n\n```\n\n### Response:\n```kotlin","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\nimport React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n \/\/ noinspection JSSuspiciousNameCombination\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n if (clampedPosition.x !== this.translation.x._value \/\/ eslint-disable-line max-len, no-underscore-dangle\n || clampedPosition.y !== this.translation.y._value) { \/\/ eslint-disable-line max-len, no-underscore-dangle\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n }\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n if (this.translation.x._value !== 0 \/\/ eslint-disable-line no-underscore-dangle\n || this.translation.y._value !== 0) { \/\/ eslint-disable-line no-underscore-dangle\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n\n\nCode-B:\nimport React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n \/\/ noinspection JSSuspiciousNameCombination\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n if (clampedPosition.x !== this.translation.x._value \/\/ eslint-disable-line max-len, no-underscore-dangle\n || clampedPosition.y !== this.translation.y._value) { \/\/ eslint-disable-line max-len, no-underscore-dangle\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n }\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\nimport React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n \/\/ noinspection JSSuspiciousNameCombination\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n if (clampedPosition.x !== this.translation.x._value \/\/ eslint-disable-line max-len, no-underscore-dangle\n || clampedPosition.y !== this.translation.y._value) { \/\/ eslint-disable-line max-len, no-underscore-dangle\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n }\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n\n\nCode-B:\nimport React from 'react';\nimport SvgUri from 'react-native-svg-uri';\nimport MaterialIcon from 'react-native-vector-icons\/MaterialCommunityIcons';\nimport { Animated, View, ViewPropTypes } from 'react-native';\nimport * as Types from '..\/..\/types';\nimport { TouchReceiverMixin } from '..\/utils';\nimport Styles, { buildContainerStyle } from '.\/styles';\n\nexport default class Analog extends TouchReceiverMixin(React.PureComponent) {\n static defaultProps = {\n dispatch: () => null,\n stickerIcon: 'star-three-points',\n analogDeadZone: 0,\n analogStickMax: 32767,\n };\n\n static propTypes = {\n x: Types.number.isRequired,\n y: Types.number.isRequired,\n size: Types.number.isRequired,\n emitX: Types.string.isRequired,\n emitY: Types.string.isRequired,\n theme: Types.controllerTheme.isRequired,\n style: ViewPropTypes.style,\n dispatch: Types.func,\n stickerIcon: Types.string,\n analogDeadZone: Types.number,\n analogStickMax: Types.number,\n };\n\n static getDerivedStateFromProps({ x, y, size }, { centerX, centerY, halfSize }) {\n if (halfSize !== size \/ 2 || x + size \/ 2 !== centerX || y + size \/ 2 !== centerY) {\n return {\n centerX: x + size \/ 2,\n centerY: y + size \/ 2,\n halfSize: size \/ 2,\n };\n }\n return null;\n }\n\n constructor(props) {\n super(props);\n this.state = {\n centerX: 0,\n centerY: 0,\n halfSize: 0,\n };\n this.touchId = null;\n this.translation = new Animated.ValueXY();\n }\n\n analogMove(position) {\n const { centerX, centerY, halfSize } = this.state;\n const {\n dispatch, emitX, emitY, analogDeadZone, analogStickMax,\n } = this.props;\n const clampedPosition = {\n x: Math.min(halfSize, Math.max(-halfSize, position.x - centerX)),\n y: Math.min(halfSize, Math.max(-halfSize, position.y - centerY)),\n };\n \/\/ noinspection JSSuspiciousNameCombination\n if (Math.abs(clampedPosition.x) >= (analogDeadZone \/ 100) * halfSize\n || Math.abs(clampedPosition.y) >= (analogDeadZone \/ 100) * halfSize) {\n if (clampedPosition.x !== this.translation.x._value \/\/ eslint-disable-line max-len, no-underscore-dangle\n || clampedPosition.y !== this.translation.y._value) { \/\/ eslint-disable-line max-len, no-underscore-dangle\n dispatch({\n [emitX]: Math.round((clampedPosition.x \/ halfSize) * analogStickMax),\n [emitY]: Math.round((clampedPosition.y \/ halfSize) * analogStickMax),\n }, false);\n this.translation.setValue(clampedPosition);\n }\n } else {\n this.analogReset();\n }\n }\n\n analogReset() {\n const { dispatch, emitX, emitY } = this.props;\n if (this.translation.x._value !== 0 \/\/ eslint-disable-line no-underscore-dangle\n || this.translation.y._value !== 0) { \/\/ eslint-disable-line no-underscore-dangle\n dispatch({\n [emitX]: 0,\n [emitY]: 0,\n }, true);\n this.translation.setValue({\n x: 0,\n y: 0,\n });\n }\n }\n\n onTouchDown(id) {\n if (this.touchId === null) {\n this.touchId = id;\n this.analogReset();\n return true;\n }\n return false;\n }\n\n onTouchMove(touch) {\n if (this.touchId === touch.identifier) {\n this.analogMove({\n x: touch.locationX,\n y: touch.locationY,\n });\n return true;\n }\n return false;\n }\n\n onTouchUp(id) {\n if (this.touchId === id) {\n this.touchId = null;\n this.analogReset();\n }\n }\n\n render() {\n const {\n x, y, size, theme, stickerIcon, style, ...viewProps\n } = this.props;\n const knobSize = size * 0.75;\n return (\n \n \n \n <\/View>\n \n \n \n \n <\/View>\n <\/Animated.View>\n <\/Animated.View>\n );\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/TeamNewPipe\/NewPipe\/commit\/6ea0f6290a7b2c166f4b78395484f62060f88542","commit_message":"'\\\\\"Downloader: Notify the progress every 64K instead of every 512 Bytes\\\\n\\\\nThis improves downloading performance dramatically when cpu bound:\\\\nBefore","source_code":"package us.shandian.giga.get;\n\nimport android.util.Log;\n\nimport java.io.BufferedInputStream;\nimport java.io.RandomAccessFile;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\n\nimport static org.schabi.newpipe.BuildConfig.DEBUG;\n\n\/**\n * Runnable to download blocks of a file until the file is completely downloaded,\n * an error occurs or the process is stopped.\n *\/\npublic class DownloadRunnable implements Runnable {\n private static final String TAG = DownloadRunnable.class.getSimpleName();\n\n private final DownloadMission mMission;\n private final int mId;\n\n public DownloadRunnable(DownloadMission mission, int id) {\n if (mission == null) throw new NullPointerException(\"mission is null\");\n mMission = mission;\n mId = id;\n }\n\n @Override\n public void run() {\n boolean retry = mMission.recovered;\n long position = mMission.getPosition(mId);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":default pos \" + position);\n Log.d(TAG, mId + \":recovered: \" + mMission.recovered);\n }\n\n while (mMission.errCode == -1 && mMission.running && position < mMission.blocks) {\n\n if (Thread.currentThread().isInterrupted()) {\n mMission.pause();\n return;\n }\n\n if (DEBUG && retry) {\n Log.d(TAG, mId + \":retry is true. Resuming at \" + position);\n }\n\n \/\/ Wait for an unblocked position\n while (!retry && position < mMission.blocks && mMission.isBlockPreserved(position)) {\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" preserved, passing\");\n }\n\n position++;\n }\n\n retry = false;\n\n if (position >= mMission.blocks) {\n break;\n }\n\n if (DEBUG) {\n Log.d(TAG, mId + \":preserving position \" + position);\n }\n\n mMission.preserveBlock(position);\n mMission.setPosition(mId, position);\n\n long start = position * DownloadManager.BLOCK_SIZE;\n long end = start + DownloadManager.BLOCK_SIZE - 1;\n\n if (end >= mMission.length) {\n end = mMission.length - 1;\n }\n\n HttpURLConnection conn = null;\n\n int total = 0;\n\n try {\n URL url = new URL(mMission.url);\n conn = (HttpURLConnection) url.openConnection();\n conn.setRequestProperty(\"Range\", \"bytes=\" + start + \"-\" + end);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":\" + conn.getRequestProperty(\"Range\"));\n Log.d(TAG, mId + \":Content-Length=\" + conn.getContentLength() + \" Code:\" + conn.getResponseCode());\n }\n\n \/\/ A server may be ignoring the range request\n if (conn.getResponseCode() != 206) {\n mMission.errCode = DownloadMission.ERROR_SERVER_UNSUPPORTED;\n notifyError(DownloadMission.ERROR_SERVER_UNSUPPORTED);\n\n if (DEBUG) {\n Log.e(TAG, mId + \":Unsupported \" + conn.getResponseCode());\n }\n\n break;\n }\n\n RandomAccessFile f = new RandomAccessFile(mMission.location + \"\/\" + mMission.name, \"rw\");\n f.seek(start);\n BufferedInputStream ipt = new BufferedInputStream(conn.getInputStream());\n byte[] buf = new byte[512];\n\n while (start < end && mMission.running) {\n int len = ipt.read(buf, 0, 512);\n\n if (len == -1) {\n break;\n } else {\n start += len;\n total += len;\n f.write(buf, 0, len);\n notifyProgress(len);\n }\n }\n\n if (DEBUG && mMission.running) {\n Log.d(TAG, mId + \":position \" + position + \" finished, total length \" + total);\n }\n\n f.close();\n ipt.close();\n\n \/\/ TODO We should save progress for each thread\n } catch (Exception e) {\n \/\/ TODO Retry count limit & notify error\n retry = true;\n\n notifyProgress(-total);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" retrying\", e);\n }\n }\n }\n\n if (DEBUG) {\n Log.d(TAG, \"thread \" + mId + \" exited main loop\");\n }\n\n if (mMission.errCode == -1 && mMission.running) {\n if (DEBUG) {\n Log.d(TAG, \"no error has happened, notifying\");\n }\n notifyFinished();\n }\n\n if (DEBUG && !mMission.running) {\n Log.d(TAG, \"The mission has been paused. Passing.\");\n }\n }\n\n private void notifyProgress(final long len) {\n synchronized (mMission) {\n mMission.notifyProgress(len);\n }\n }\n\n private void notifyError(final int err) {\n synchronized (mMission) {\n mMission.notifyError(err);\n mMission.pause();\n }\n }\n\n private void notifyFinished() {\n synchronized (mMission) {\n mMission.notifyFinished();\n }\n }\n}\n","target_code":"package us.shandian.giga.get;\n\nimport android.util.Log;\n\nimport java.io.RandomAccessFile;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\n\nimport static org.schabi.newpipe.BuildConfig.DEBUG;\n\n\/**\n * Runnable to download blocks of a file until the file is completely downloaded,\n * an error occurs or the process is stopped.\n *\/\npublic class DownloadRunnable implements Runnable {\n private static final String TAG = DownloadRunnable.class.getSimpleName();\n\n private final DownloadMission mMission;\n private final int mId;\n\n public DownloadRunnable(DownloadMission mission, int id) {\n if (mission == null) throw new NullPointerException(\"mission is null\");\n mMission = mission;\n mId = id;\n }\n\n @Override\n public void run() {\n boolean retry = mMission.recovered;\n long position = mMission.getPosition(mId);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":default pos \" + position);\n Log.d(TAG, mId + \":recovered: \" + mMission.recovered);\n }\n\n while (mMission.errCode == -1 && mMission.running && position < mMission.blocks) {\n\n if (Thread.currentThread().isInterrupted()) {\n mMission.pause();\n return;\n }\n\n if (DEBUG && retry) {\n Log.d(TAG, mId + \":retry is true. Resuming at \" + position);\n }\n\n \/\/ Wait for an unblocked position\n while (!retry && position < mMission.blocks && mMission.isBlockPreserved(position)) {\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" preserved, passing\");\n }\n\n position++;\n }\n\n retry = false;\n\n if (position >= mMission.blocks) {\n break;\n }\n\n if (DEBUG) {\n Log.d(TAG, mId + \":preserving position \" + position);\n }\n\n mMission.preserveBlock(position);\n mMission.setPosition(mId, position);\n\n long start = position * DownloadManager.BLOCK_SIZE;\n long end = start + DownloadManager.BLOCK_SIZE - 1;\n\n if (end >= mMission.length) {\n end = mMission.length - 1;\n }\n\n HttpURLConnection conn = null;\n\n int total = 0;\n\n try {\n URL url = new URL(mMission.url);\n conn = (HttpURLConnection) url.openConnection();\n conn.setRequestProperty(\"Range\", \"bytes=\" + start + \"-\" + end);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":\" + conn.getRequestProperty(\"Range\"));\n Log.d(TAG, mId + \":Content-Length=\" + conn.getContentLength() + \" Code:\" + conn.getResponseCode());\n }\n\n \/\/ A server may be ignoring the range request\n if (conn.getResponseCode() != 206) {\n mMission.errCode = DownloadMission.ERROR_SERVER_UNSUPPORTED;\n notifyError(DownloadMission.ERROR_SERVER_UNSUPPORTED);\n\n if (DEBUG) {\n Log.e(TAG, mId + \":Unsupported \" + conn.getResponseCode());\n }\n\n break;\n }\n\n RandomAccessFile f = new RandomAccessFile(mMission.location + \"\/\" + mMission.name, \"rw\");\n f.seek(start);\n java.io.InputStream ipt = conn.getInputStream();\n byte[] buf = new byte[64*1024];\n\n while (start < end && mMission.running) {\n int len = ipt.read(buf, 0, buf.length);\n\n if (len == -1) {\n break;\n } else {\n start += len;\n total += len;\n f.write(buf, 0, len);\n notifyProgress(len);\n }\n }\n\n if (DEBUG && mMission.running) {\n Log.d(TAG, mId + \":position \" + position + \" finished, total length \" + total);\n }\n\n f.close();\n ipt.close();\n\n \/\/ TODO We should save progress for each thread\n } catch (Exception e) {\n \/\/ TODO Retry count limit & notify error\n retry = true;\n\n notifyProgress(-total);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" retrying\", e);\n }\n }\n }\n\n if (DEBUG) {\n Log.d(TAG, \"thread \" + mId + \" exited main loop\");\n }\n\n if (mMission.errCode == -1 && mMission.running) {\n if (DEBUG) {\n Log.d(TAG, \"no error has happened, notifying\");\n }\n notifyFinished();\n }\n\n if (DEBUG && !mMission.running) {\n Log.d(TAG, \"The mission has been paused. Passing.\");\n }\n }\n\n private void notifyProgress(final long len) {\n synchronized (mMission) {\n mMission.notifyProgress(len);\n }\n }\n\n private void notifyError(final int err) {\n synchronized (mMission) {\n mMission.notifyError(err);\n mMission.pause();\n }\n }\n\n private void notifyFinished() {\n synchronized (mMission) {\n mMission.notifyFinished();\n }\n }\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage us.shandian.giga.get;\n\nimport android.util.Log;\n\nimport java.io.BufferedInputStream;\nimport java.io.RandomAccessFile;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\n\nimport static org.schabi.newpipe.BuildConfig.DEBUG;\n\n\/**\n * Runnable to download blocks of a file until the file is completely downloaded,\n * an error occurs or the process is stopped.\n *\/\npublic class DownloadRunnable implements Runnable {\n private static final String TAG = DownloadRunnable.class.getSimpleName();\n\n private final DownloadMission mMission;\n private final int mId;\n\n public DownloadRunnable(DownloadMission mission, int id) {\n if (mission == null) throw new NullPointerException(\"mission is null\");\n mMission = mission;\n mId = id;\n }\n\n @Override\n public void run() {\n boolean retry = mMission.recovered;\n long position = mMission.getPosition(mId);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":default pos \" + position);\n Log.d(TAG, mId + \":recovered: \" + mMission.recovered);\n }\n\n while (mMission.errCode == -1 && mMission.running && position < mMission.blocks) {\n\n if (Thread.currentThread().isInterrupted()) {\n mMission.pause();\n return;\n }\n\n if (DEBUG && retry) {\n Log.d(TAG, mId + \":retry is true. Resuming at \" + position);\n }\n\n \/\/ Wait for an unblocked position\n while (!retry && position < mMission.blocks && mMission.isBlockPreserved(position)) {\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" preserved, passing\");\n }\n\n position++;\n }\n\n retry = false;\n\n if (position >= mMission.blocks) {\n break;\n }\n\n if (DEBUG) {\n Log.d(TAG, mId + \":preserving position \" + position);\n }\n\n mMission.preserveBlock(position);\n mMission.setPosition(mId, position);\n\n long start = position * DownloadManager.BLOCK_SIZE;\n long end = start + DownloadManager.BLOCK_SIZE - 1;\n\n if (end >= mMission.length) {\n end = mMission.length - 1;\n }\n\n HttpURLConnection conn = null;\n\n int total = 0;\n\n try {\n URL url = new URL(mMission.url);\n conn = (HttpURLConnection) url.openConnection();\n conn.setRequestProperty(\"Range\", \"bytes=\" + start + \"-\" + end);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":\" + conn.getRequestProperty(\"Range\"));\n Log.d(TAG, mId + \":Content-Length=\" + conn.getContentLength() + \" Code:\" + conn.getResponseCode());\n }\n\n \/\/ A server may be ignoring the range request\n if (conn.getResponseCode() != 206) {\n mMission.errCode = DownloadMission.ERROR_SERVER_UNSUPPORTED;\n notifyError(DownloadMission.ERROR_SERVER_UNSUPPORTED);\n\n if (DEBUG) {\n Log.e(TAG, mId + \":Unsupported \" + conn.getResponseCode());\n }\n\n break;\n }\n\n RandomAccessFile f = new RandomAccessFile(mMission.location + \"\/\" + mMission.name, \"rw\");\n f.seek(start);\n BufferedInputStream ipt = new BufferedInputStream(conn.getInputStream());\n byte[] buf = new byte[512];\n\n while (start < end && mMission.running) {\n int len = ipt.read(buf, 0, 512);\n\n if (len == -1) {\n break;\n } else {\n start += len;\n total += len;\n f.write(buf, 0, len);\n notifyProgress(len);\n }\n }\n\n if (DEBUG && mMission.running) {\n Log.d(TAG, mId + \":position \" + position + \" finished, total length \" + total);\n }\n\n f.close();\n ipt.close();\n\n \/\/ TODO We should save progress for each thread\n } catch (Exception e) {\n \/\/ TODO Retry count limit & notify error\n retry = true;\n\n notifyProgress(-total);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" retrying\", e);\n }\n }\n }\n\n if (DEBUG) {\n Log.d(TAG, \"thread \" + mId + \" exited main loop\");\n }\n\n if (mMission.errCode == -1 && mMission.running) {\n if (DEBUG) {\n Log.d(TAG, \"no error has happened, notifying\");\n }\n notifyFinished();\n }\n\n if (DEBUG && !mMission.running) {\n Log.d(TAG, \"The mission has been paused. Passing.\");\n }\n }\n\n private void notifyProgress(final long len) {\n synchronized (mMission) {\n mMission.notifyProgress(len);\n }\n }\n\n private void notifyError(final int err) {\n synchronized (mMission) {\n mMission.notifyError(err);\n mMission.pause();\n }\n }\n\n private void notifyFinished() {\n synchronized (mMission) {\n mMission.notifyFinished();\n }\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage us.shandian.giga.get;\n\nimport android.util.Log;\n\nimport java.io.BufferedInputStream;\nimport java.io.RandomAccessFile;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\n\nimport static org.schabi.newpipe.BuildConfig.DEBUG;\n\n\/**\n * Runnable to download blocks of a file until the file is completely downloaded,\n * an error occurs or the process is stopped.\n *\/\npublic class DownloadRunnable implements Runnable {\n private static final String TAG = DownloadRunnable.class.getSimpleName();\n\n private final DownloadMission mMission;\n private final int mId;\n\n public DownloadRunnable(DownloadMission mission, int id) {\n if (mission == null) throw new NullPointerException(\"mission is null\");\n mMission = mission;\n mId = id;\n }\n\n @Override\n public void run() {\n boolean retry = mMission.recovered;\n long position = mMission.getPosition(mId);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":default pos \" + position);\n Log.d(TAG, mId + \":recovered: \" + mMission.recovered);\n }\n\n while (mMission.errCode == -1 && mMission.running && position < mMission.blocks) {\n\n if (Thread.currentThread().isInterrupted()) {\n mMission.pause();\n return;\n }\n\n if (DEBUG && retry) {\n Log.d(TAG, mId + \":retry is true. Resuming at \" + position);\n }\n\n \/\/ Wait for an unblocked position\n while (!retry && position < mMission.blocks && mMission.isBlockPreserved(position)) {\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" preserved, passing\");\n }\n\n position++;\n }\n\n retry = false;\n\n if (position >= mMission.blocks) {\n break;\n }\n\n if (DEBUG) {\n Log.d(TAG, mId + \":preserving position \" + position);\n }\n\n mMission.preserveBlock(position);\n mMission.setPosition(mId, position);\n\n long start = position * DownloadManager.BLOCK_SIZE;\n long end = start + DownloadManager.BLOCK_SIZE - 1;\n\n if (end >= mMission.length) {\n end = mMission.length - 1;\n }\n\n HttpURLConnection conn = null;\n\n int total = 0;\n\n try {\n URL url = new URL(mMission.url);\n conn = (HttpURLConnection) url.openConnection();\n conn.setRequestProperty(\"Range\", \"bytes=\" + start + \"-\" + end);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":\" + conn.getRequestProperty(\"Range\"));\n Log.d(TAG, mId + \":Content-Length=\" + conn.getContentLength() + \" Code:\" + conn.getResponseCode());\n }\n\n \/\/ A server may be ignoring the range request\n if (conn.getResponseCode() != 206) {\n mMission.errCode = DownloadMission.ERROR_SERVER_UNSUPPORTED;\n notifyError(DownloadMission.ERROR_SERVER_UNSUPPORTED);\n\n if (DEBUG) {\n Log.e(TAG, mId + \":Unsupported \" + conn.getResponseCode());\n }\n\n break;\n }\n\n RandomAccessFile f = new RandomAccessFile(mMission.location + \"\/\" + mMission.name, \"rw\");\n f.seek(start);\n BufferedInputStream ipt = new BufferedInputStream(conn.getInputStream());\n byte[] buf = new byte[512];\n\n while (start < end && mMission.running) {\n int len = ipt.read(buf, 0, 512);\n\n if (len == -1) {\n break;\n } else {\n start += len;\n total += len;\n f.write(buf, 0, len);\n notifyProgress(len);\n }\n }\n\n if (DEBUG && mMission.running) {\n Log.d(TAG, mId + \":position \" + position + \" finished, total length \" + total);\n }\n\n f.close();\n ipt.close();\n\n \/\/ TODO We should save progress for each thread\n } catch (Exception e) {\n \/\/ TODO Retry count limit & notify error\n retry = true;\n\n notifyProgress(-total);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" retrying\", e);\n }\n }\n }\n\n if (DEBUG) {\n Log.d(TAG, \"thread \" + mId + \" exited main loop\");\n }\n\n if (mMission.errCode == -1 && mMission.running) {\n if (DEBUG) {\n Log.d(TAG, \"no error has happened, notifying\");\n }\n notifyFinished();\n }\n\n if (DEBUG && !mMission.running) {\n Log.d(TAG, \"The mission has been paused. Passing.\");\n }\n }\n\n private void notifyProgress(final long len) {\n synchronized (mMission) {\n mMission.notifyProgress(len);\n }\n }\n\n private void notifyError(final int err) {\n synchronized (mMission) {\n mMission.notifyError(err);\n mMission.pause();\n }\n }\n\n private void notifyFinished() {\n synchronized (mMission) {\n mMission.notifyFinished();\n }\n }\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage us.shandian.giga.get;\n\nimport android.util.Log;\n\nimport java.io.BufferedInputStream;\nimport java.io.RandomAccessFile;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\n\nimport static org.schabi.newpipe.BuildConfig.DEBUG;\n\n\/**\n * Runnable to download blocks of a file until the file is completely downloaded,\n * an error occurs or the process is stopped.\n *\/\npublic class DownloadRunnable implements Runnable {\n private static final String TAG = DownloadRunnable.class.getSimpleName();\n\n private final DownloadMission mMission;\n private final int mId;\n\n public DownloadRunnable(DownloadMission mission, int id) {\n if (mission == null) throw new NullPointerException(\"mission is null\");\n mMission = mission;\n mId = id;\n }\n\n @Override\n public void run() {\n boolean retry = mMission.recovered;\n long position = mMission.getPosition(mId);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":default pos \" + position);\n Log.d(TAG, mId + \":recovered: \" + mMission.recovered);\n }\n\n while (mMission.errCode == -1 && mMission.running && position < mMission.blocks) {\n\n if (Thread.currentThread().isInterrupted()) {\n mMission.pause();\n return;\n }\n\n if (DEBUG && retry) {\n Log.d(TAG, mId + \":retry is true. Resuming at \" + position);\n }\n\n \/\/ Wait for an unblocked position\n while (!retry && position < mMission.blocks && mMission.isBlockPreserved(position)) {\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" preserved, passing\");\n }\n\n position++;\n }\n\n retry = false;\n\n if (position >= mMission.blocks) {\n break;\n }\n\n if (DEBUG) {\n Log.d(TAG, mId + \":preserving position \" + position);\n }\n\n mMission.preserveBlock(position);\n mMission.setPosition(mId, position);\n\n long start = position * DownloadManager.BLOCK_SIZE;\n long end = start + DownloadManager.BLOCK_SIZE - 1;\n\n if (end >= mMission.length) {\n end = mMission.length - 1;\n }\n\n HttpURLConnection conn = null;\n\n int total = 0;\n\n try {\n URL url = new URL(mMission.url);\n conn = (HttpURLConnection) url.openConnection();\n conn.setRequestProperty(\"Range\", \"bytes=\" + start + \"-\" + end);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":\" + conn.getRequestProperty(\"Range\"));\n Log.d(TAG, mId + \":Content-Length=\" + conn.getContentLength() + \" Code:\" + conn.getResponseCode());\n }\n\n \/\/ A server may be ignoring the range request\n if (conn.getResponseCode() != 206) {\n mMission.errCode = DownloadMission.ERROR_SERVER_UNSUPPORTED;\n notifyError(DownloadMission.ERROR_SERVER_UNSUPPORTED);\n\n if (DEBUG) {\n Log.e(TAG, mId + \":Unsupported \" + conn.getResponseCode());\n }\n\n break;\n }\n\n RandomAccessFile f = new RandomAccessFile(mMission.location + \"\/\" + mMission.name, \"rw\");\n f.seek(start);\n BufferedInputStream ipt = new BufferedInputStream(conn.getInputStream());\n byte[] buf = new byte[512];\n\n while (start < end && mMission.running) {\n int len = ipt.read(buf, 0, 512);\n\n if (len == -1) {\n break;\n } else {\n start += len;\n total += len;\n f.write(buf, 0, len);\n notifyProgress(len);\n }\n }\n\n if (DEBUG && mMission.running) {\n Log.d(TAG, mId + \":position \" + position + \" finished, total length \" + total);\n }\n\n f.close();\n ipt.close();\n\n \/\/ TODO We should save progress for each thread\n } catch (Exception e) {\n \/\/ TODO Retry count limit & notify error\n retry = true;\n\n notifyProgress(-total);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" retrying\", e);\n }\n }\n }\n\n if (DEBUG) {\n Log.d(TAG, \"thread \" + mId + \" exited main loop\");\n }\n\n if (mMission.errCode == -1 && mMission.running) {\n if (DEBUG) {\n Log.d(TAG, \"no error has happened, notifying\");\n }\n notifyFinished();\n }\n\n if (DEBUG && !mMission.running) {\n Log.d(TAG, \"The mission has been paused. Passing.\");\n }\n }\n\n private void notifyProgress(final long len) {\n synchronized (mMission) {\n mMission.notifyProgress(len);\n }\n }\n\n private void notifyError(final int err) {\n synchronized (mMission) {\n mMission.notifyError(err);\n mMission.pause();\n }\n }\n\n private void notifyFinished() {\n synchronized (mMission) {\n mMission.notifyFinished();\n }\n }\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite run() function to improve downloading performance dramatically when the application is cpu bound. Write the entire code and no other text in the response.\n\n### Concepts:\n[hint] Notify the progress every 64K instead of every 512 Bytes\n[-] java.io.BufferedInputStream\n[+] java.io.InputStream\n\n### Given program:\n```java\npackage us.shandian.giga.get;\n\nimport android.util.Log;\n\nimport java.io.BufferedInputStream;\nimport java.io.RandomAccessFile;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\n\nimport static org.schabi.newpipe.BuildConfig.DEBUG;\n\n\/**\n * Runnable to download blocks of a file until the file is completely downloaded,\n * an error occurs or the process is stopped.\n *\/\npublic class DownloadRunnable implements Runnable {\n private static final String TAG = DownloadRunnable.class.getSimpleName();\n\n private final DownloadMission mMission;\n private final int mId;\n\n public DownloadRunnable(DownloadMission mission, int id) {\n if (mission == null) throw new NullPointerException(\"mission is null\");\n mMission = mission;\n mId = id;\n }\n\n @Override\n public void run() {\n boolean retry = mMission.recovered;\n long position = mMission.getPosition(mId);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":default pos \" + position);\n Log.d(TAG, mId + \":recovered: \" + mMission.recovered);\n }\n\n while (mMission.errCode == -1 && mMission.running && position < mMission.blocks) {\n\n if (Thread.currentThread().isInterrupted()) {\n mMission.pause();\n return;\n }\n\n if (DEBUG && retry) {\n Log.d(TAG, mId + \":retry is true. Resuming at \" + position);\n }\n\n \/\/ Wait for an unblocked position\n while (!retry && position < mMission.blocks && mMission.isBlockPreserved(position)) {\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" preserved, passing\");\n }\n\n position++;\n }\n\n retry = false;\n\n if (position >= mMission.blocks) {\n break;\n }\n\n if (DEBUG) {\n Log.d(TAG, mId + \":preserving position \" + position);\n }\n\n mMission.preserveBlock(position);\n mMission.setPosition(mId, position);\n\n long start = position * DownloadManager.BLOCK_SIZE;\n long end = start + DownloadManager.BLOCK_SIZE - 1;\n\n if (end >= mMission.length) {\n end = mMission.length - 1;\n }\n\n HttpURLConnection conn = null;\n\n int total = 0;\n\n try {\n URL url = new URL(mMission.url);\n conn = (HttpURLConnection) url.openConnection();\n conn.setRequestProperty(\"Range\", \"bytes=\" + start + \"-\" + end);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":\" + conn.getRequestProperty(\"Range\"));\n Log.d(TAG, mId + \":Content-Length=\" + conn.getContentLength() + \" Code:\" + conn.getResponseCode());\n }\n\n \/\/ A server may be ignoring the range request\n if (conn.getResponseCode() != 206) {\n mMission.errCode = DownloadMission.ERROR_SERVER_UNSUPPORTED;\n notifyError(DownloadMission.ERROR_SERVER_UNSUPPORTED);\n\n if (DEBUG) {\n Log.e(TAG, mId + \":Unsupported \" + conn.getResponseCode());\n }\n\n break;\n }\n\n RandomAccessFile f = new RandomAccessFile(mMission.location + \"\/\" + mMission.name, \"rw\");\n f.seek(start);\n BufferedInputStream ipt = new BufferedInputStream(conn.getInputStream());\n byte[] buf = new byte[512];\n\n while (start < end && mMission.running) {\n int len = ipt.read(buf, 0, 512);\n\n if (len == -1) {\n break;\n } else {\n start += len;\n total += len;\n f.write(buf, 0, len);\n notifyProgress(len);\n }\n }\n\n if (DEBUG && mMission.running) {\n Log.d(TAG, mId + \":position \" + position + \" finished, total length \" + total);\n }\n\n f.close();\n ipt.close();\n\n \/\/ TODO We should save progress for each thread\n } catch (Exception e) {\n \/\/ TODO Retry count limit & notify error\n retry = true;\n\n notifyProgress(-total);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" retrying\", e);\n }\n }\n }\n\n if (DEBUG) {\n Log.d(TAG, \"thread \" + mId + \" exited main loop\");\n }\n\n if (mMission.errCode == -1 && mMission.running) {\n if (DEBUG) {\n Log.d(TAG, \"no error has happened, notifying\");\n }\n notifyFinished();\n }\n\n if (DEBUG && !mMission.running) {\n Log.d(TAG, \"The mission has been paused. Passing.\");\n }\n }\n\n private void notifyProgress(final long len) {\n synchronized (mMission) {\n mMission.notifyProgress(len);\n }\n }\n\n private void notifyError(final int err) {\n synchronized (mMission) {\n mMission.notifyError(err);\n mMission.pause();\n }\n }\n\n private void notifyFinished() {\n synchronized (mMission) {\n mMission.notifyFinished();\n }\n }\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.R;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n boolean pref_compactlayout;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n boolean init = false;\n\n if (convertView == null) {\n convertView = ((LayoutInflater) mContext.getSystemService(\n Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.applistitem, null);\n init = true;\n }\n\n ImageView iconUpdates = (ImageView) convertView.findViewById(R.id.icon_status_has_updates);\n ImageView iconInstalled = (ImageView) convertView.findViewById(R.id.icon_status_installed);\n\n TextView name = (TextView) convertView.findViewById(R.id.name);\n TextView summary = (TextView) convertView.findViewById(R.id.summary);\n TextView status = (TextView) convertView.findViewById(R.id.status);\n TextView license = (TextView) convertView.findViewById(R.id.license);\n\n DB.App app = items.get(position);\n\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n\n name.setText(app.name);\n summary.setText(app.summary);\n\n ImageView icon = (ImageView) convertView.findViewById(R.id.icon);\n File icn = new File(DB.getIconsPath(), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n icon.setImageURI(Uri.parse(icn.getPath()));\n } else {\n icon.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n iconUpdates.setVisibility(View.GONE);\n iconInstalled.setVisibility(View.GONE);\n\n if (init) {\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(mContext);\n pref_compactlayout = prefs.getBoolean(\"compactlayout\", false);\n\n if (pref_compactlayout == true) {\n status.setVisibility(View.GONE);\n license.setVisibility(View.GONE);\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(RelativeLayout.END_OF, R.id.icon);\n summary.setLayoutParams(summaryLayout);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setVisibility(View.VISIBLE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setVisibility(View.VISIBLE);\n }\n }\n }\n\n \/\/ Disable it all if it isn't compatible...\n View[] views = { convertView, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(app.compatible);\n }\n\n return convertView;\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n\n\nCode-B:\npackage org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.R;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n View v = convertView;\n if (v == null) {\n LayoutInflater vi = (LayoutInflater) mContext\n .getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n v = vi.inflate(R.layout.applistitem, null);\n }\n DB.App app = items.get(position);\n\n TextView name = (TextView) v.findViewById(R.id.name);\n name.setText(app.name);\n\n TextView summary = (TextView) v.findViewById(R.id.summary);\n summary.setText(app.summary);\n\n TextView status = (TextView) v.findViewById(R.id.status);\n TextView license = (TextView) v.findViewById(R.id.license);\n\n ImageView iconUpdates = (ImageView)v.findViewById(R.id.icon_status_has_updates);\n ImageView iconInstalled = (ImageView)v.findViewById(R.id.icon_status_installed);\n\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);\n\n if (prefs.getBoolean(\"compactlayout\", false)) {\n\n status.setVisibility(View.GONE);\n license.setVisibility(View.GONE);\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(RelativeLayout.RIGHT_OF, R.id.icon);\n summary.setLayoutParams(summaryLayout);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n iconUpdates.setVisibility(View.VISIBLE);\n } else {\n iconUpdates.setVisibility(View.GONE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconInstalled.setVisibility(View.VISIBLE);\n } else {\n iconInstalled.setVisibility(View.GONE);\n }\n\n } else {\n\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n\n iconUpdates.setVisibility(View.GONE);\n iconInstalled.setVisibility(View.GONE);\n }\n\n ImageView icon = (ImageView) v.findViewById(R.id.icon);\n File icn = new File(DB.getIconsPath(), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n icon.setImageURI(Uri.parse(icn.getPath()));\n } else {\n icon.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n \/\/ Disable it all if it isn't compatible...\n View[] views = { v, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(app.compatible);\n }\n\n return v;\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.R;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n View v = convertView;\n if (v == null) {\n LayoutInflater vi = (LayoutInflater) mContext\n .getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n v = vi.inflate(R.layout.applistitem, null);\n }\n DB.App app = items.get(position);\n\n TextView name = (TextView) v.findViewById(R.id.name);\n name.setText(app.name);\n\n TextView summary = (TextView) v.findViewById(R.id.summary);\n summary.setText(app.summary);\n\n TextView status = (TextView) v.findViewById(R.id.status);\n TextView license = (TextView) v.findViewById(R.id.license);\n\n ImageView iconUpdates = (ImageView)v.findViewById(R.id.icon_status_has_updates);\n ImageView iconInstalled = (ImageView)v.findViewById(R.id.icon_status_installed);\n\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);\n\n if (prefs.getBoolean(\"compactlayout\", false)) {\n\n status.setVisibility(View.GONE);\n license.setVisibility(View.GONE);\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(RelativeLayout.RIGHT_OF, R.id.icon);\n summary.setLayoutParams(summaryLayout);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n iconUpdates.setVisibility(View.VISIBLE);\n } else {\n iconUpdates.setVisibility(View.GONE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconInstalled.setVisibility(View.VISIBLE);\n } else {\n iconInstalled.setVisibility(View.GONE);\n }\n\n } else {\n\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n\n iconUpdates.setVisibility(View.GONE);\n iconInstalled.setVisibility(View.GONE);\n }\n\n ImageView icon = (ImageView) v.findViewById(R.id.icon);\n File icn = new File(DB.getIconsPath(), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n icon.setImageURI(Uri.parse(icn.getPath()));\n } else {\n icon.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n \/\/ Disable it all if it isn't compatible...\n View[] views = { v, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(app.compatible);\n }\n\n return v;\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n\n\nCode-B:\npackage org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.R;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n boolean pref_compactlayout;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n boolean init = false;\n\n if (convertView == null) {\n convertView = ((LayoutInflater) mContext.getSystemService(\n Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.applistitem, null);\n init = true;\n }\n\n ImageView iconUpdates = (ImageView) convertView.findViewById(R.id.icon_status_has_updates);\n ImageView iconInstalled = (ImageView) convertView.findViewById(R.id.icon_status_installed);\n\n TextView name = (TextView) convertView.findViewById(R.id.name);\n TextView summary = (TextView) convertView.findViewById(R.id.summary);\n TextView status = (TextView) convertView.findViewById(R.id.status);\n TextView license = (TextView) convertView.findViewById(R.id.license);\n\n DB.App app = items.get(position);\n\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n\n name.setText(app.name);\n summary.setText(app.summary);\n\n ImageView icon = (ImageView) convertView.findViewById(R.id.icon);\n File icn = new File(DB.getIconsPath(), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n icon.setImageURI(Uri.parse(icn.getPath()));\n } else {\n icon.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n iconUpdates.setVisibility(View.GONE);\n iconInstalled.setVisibility(View.GONE);\n\n if (init) {\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(mContext);\n pref_compactlayout = prefs.getBoolean(\"compactlayout\", false);\n\n if (pref_compactlayout == true) {\n status.setVisibility(View.GONE);\n license.setVisibility(View.GONE);\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(RelativeLayout.END_OF, R.id.icon);\n summary.setLayoutParams(summaryLayout);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setVisibility(View.VISIBLE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setVisibility(View.VISIBLE);\n }\n }\n }\n\n \/\/ Disable it all if it isn't compatible...\n View[] views = { convertView, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(app.compatible);\n }\n\n return convertView;\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/TeamNewPipe\/NewPipe\/commit\/a026143a840b9ac57534357a2074a50175be388a","commit_message":"'\\\\\"linkify optimizations\\\\n\\\\\"'","source_code":"package org.schabi.newpipe.info_list.holder;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.text.util.Linkify;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\n\nimport org.schabi.newpipe.R;\nimport org.schabi.newpipe.extractor.InfoItem;\nimport org.schabi.newpipe.extractor.comments.CommentsInfoItem;\nimport org.schabi.newpipe.info_list.InfoItemBuilder;\nimport org.schabi.newpipe.report.ErrorActivity;\nimport org.schabi.newpipe.util.CommentTextOnTouchListener;\nimport org.schabi.newpipe.util.ImageDisplayConstants;\nimport org.schabi.newpipe.util.NavigationHelper;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport de.hdodenhof.circleimageview.CircleImageView;\n\npublic class CommentsMiniInfoItemHolder extends InfoItemHolder {\n public final CircleImageView itemThumbnailView;\n private final TextView itemContentView;\n private final TextView itemLikesCountView;\n private final TextView itemDislikesCountView;\n private final TextView itemPublishedTime;\n\n private static final int commentDefaultLines = 2;\n private static final int commentExpandedLines = 1000;\n\n private String commentText;\n private String streamUrl;\n\n private static final Pattern pattern = Pattern.compile(\"(\\\\d+:)?(\\\\d+)?:(\\\\d+)\");\n\n private final Linkify.TransformFilter timestampLink = new Linkify.TransformFilter() {\n @Override\n public String transformUrl(Matcher match, String url) {\n int timestamp = 0;\n String hours = match.group(1);\n String minutes = match.group(2);\n String seconds = match.group(3);\n if(hours != null) timestamp += (Integer.parseInt(hours.replace(\":\", \"\"))*3600);\n if(minutes != null) timestamp += (Integer.parseInt(minutes.replace(\":\", \"\"))*60);\n if(seconds != null) timestamp += (Integer.parseInt(seconds));\n return streamUrl + url.replace(match.group(0), \"#timestamp=\" + String.valueOf(timestamp));\n }\n };\n\n CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, int layoutId, ViewGroup parent) {\n super(infoItemBuilder, layoutId, parent);\n\n itemThumbnailView = itemView.findViewById(R.id.itemThumbnailView);\n itemLikesCountView = itemView.findViewById(R.id.detail_thumbs_up_count_view);\n itemDislikesCountView = itemView.findViewById(R.id.detail_thumbs_down_count_view);\n itemPublishedTime = itemView.findViewById(R.id.itemPublishedTime);\n itemContentView = itemView.findViewById(R.id.itemCommentContentView);\n }\n\n public CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, ViewGroup parent) {\n this(infoItemBuilder, R.layout.list_comments_mini_item, parent);\n }\n\n @Override\n public void updateFromItem(final InfoItem infoItem) {\n if (!(infoItem instanceof CommentsInfoItem)) return;\n final CommentsInfoItem item = (CommentsInfoItem) infoItem;\n\n itemBuilder.getImageLoader()\n .displayImage(item.getAuthorThumbnail(),\n itemThumbnailView,\n ImageDisplayConstants.DISPLAY_THUMBNAIL_OPTIONS);\n\n itemThumbnailView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n try {\n final AppCompatActivity activity = (AppCompatActivity) itemBuilder.getContext();\n NavigationHelper.openChannelFragment(\n activity.getSupportFragmentManager(),\n item.getServiceId(),\n item.getAuthorEndpoint(),\n item.getAuthorName());\n } catch (Exception e) {\n ErrorActivity.reportUiError((AppCompatActivity) itemBuilder.getContext(), e);\n }\n }\n });\n\n streamUrl = item.getUrl();\n\n itemContentView.setMaxLines(commentDefaultLines);\n commentText = item.getCommentText();\n itemContentView.setText(commentText);\n linkify();\n itemContentView.setOnTouchListener(CommentTextOnTouchListener.INSTANCE);\n\n if(itemContentView.getLineCount() == 0){\n itemContentView.post(() -> ellipsize());\n }else{\n ellipsize();\n }\n\n if (null != item.getLikeCount()) {\n itemLikesCountView.setText(String.valueOf(item.getLikeCount()));\n }\n itemPublishedTime.setText(item.getPublishedTime());\n\n itemView.setOnClickListener(view -> {\n toggleEllipsize();\n if (itemBuilder.getOnCommentsSelectedListener() != null) {\n itemBuilder.getOnCommentsSelectedListener().selected(item);\n }\n });\n }\n\n private void ellipsize() {\n if (itemContentView.getLineCount() > commentDefaultLines){\n int endOfLastLine = itemContentView.getLayout().getLineEnd(commentDefaultLines - 1);\n String newVal = itemContentView.getText().subSequence(0, endOfLastLine - 3) + \"...\";\n itemContentView.setText(newVal);\n linkify();\n }\n }\n\n private void toggleEllipsize() {\n if (itemContentView.getText().toString().equals(commentText)) {\n ellipsize();\n } else {\n expand();\n }\n }\n\n private void expand() {\n itemContentView.setMaxLines(commentExpandedLines);\n itemContentView.setText(commentText);\n linkify();\n }\n\n private void linkify(){\n Linkify.addLinks(itemContentView, Linkify.WEB_URLS);\n Linkify.addLinks(itemContentView, pattern, null, null, timestampLink);\n itemContentView.setMovementMethod(null);\n }\n}\n","target_code":"package org.schabi.newpipe.info_list.holder;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.text.util.Linkify;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\n\nimport org.schabi.newpipe.R;\nimport org.schabi.newpipe.extractor.InfoItem;\nimport org.schabi.newpipe.extractor.comments.CommentsInfoItem;\nimport org.schabi.newpipe.info_list.InfoItemBuilder;\nimport org.schabi.newpipe.report.ErrorActivity;\nimport org.schabi.newpipe.util.CommentTextOnTouchListener;\nimport org.schabi.newpipe.util.ImageDisplayConstants;\nimport org.schabi.newpipe.util.NavigationHelper;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport de.hdodenhof.circleimageview.CircleImageView;\n\npublic class CommentsMiniInfoItemHolder extends InfoItemHolder {\n public final CircleImageView itemThumbnailView;\n private final TextView itemContentView;\n private final TextView itemLikesCountView;\n private final TextView itemDislikesCountView;\n private final TextView itemPublishedTime;\n\n private static final int commentDefaultLines = 2;\n private static final int commentExpandedLines = 1000;\n\n private String commentText;\n private String streamUrl;\n\n private static final Pattern pattern = Pattern.compile(\"(\\\\d+:)?(\\\\d+)?:(\\\\d+)\");\n\n private final Linkify.TransformFilter timestampLink = new Linkify.TransformFilter() {\n @Override\n public String transformUrl(Matcher match, String url) {\n int timestamp = 0;\n String hours = match.group(1);\n String minutes = match.group(2);\n String seconds = match.group(3);\n if(hours != null) timestamp += (Integer.parseInt(hours.replace(\":\", \"\"))*3600);\n if(minutes != null) timestamp += (Integer.parseInt(minutes.replace(\":\", \"\"))*60);\n if(seconds != null) timestamp += (Integer.parseInt(seconds));\n return streamUrl + url.replace(match.group(0), \"#timestamp=\" + String.valueOf(timestamp));\n }\n };\n\n CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, int layoutId, ViewGroup parent) {\n super(infoItemBuilder, layoutId, parent);\n\n itemThumbnailView = itemView.findViewById(R.id.itemThumbnailView);\n itemLikesCountView = itemView.findViewById(R.id.detail_thumbs_up_count_view);\n itemDislikesCountView = itemView.findViewById(R.id.detail_thumbs_down_count_view);\n itemPublishedTime = itemView.findViewById(R.id.itemPublishedTime);\n itemContentView = itemView.findViewById(R.id.itemCommentContentView);\n }\n\n public CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, ViewGroup parent) {\n this(infoItemBuilder, R.layout.list_comments_mini_item, parent);\n }\n\n @Override\n public void updateFromItem(final InfoItem infoItem) {\n if (!(infoItem instanceof CommentsInfoItem)) return;\n final CommentsInfoItem item = (CommentsInfoItem) infoItem;\n\n itemBuilder.getImageLoader()\n .displayImage(item.getAuthorThumbnail(),\n itemThumbnailView,\n ImageDisplayConstants.DISPLAY_THUMBNAIL_OPTIONS);\n\n itemThumbnailView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n try {\n final AppCompatActivity activity = (AppCompatActivity) itemBuilder.getContext();\n NavigationHelper.openChannelFragment(\n activity.getSupportFragmentManager(),\n item.getServiceId(),\n item.getAuthorEndpoint(),\n item.getAuthorName());\n } catch (Exception e) {\n ErrorActivity.reportUiError((AppCompatActivity) itemBuilder.getContext(), e);\n }\n }\n });\n\n streamUrl = item.getUrl();\n\n itemContentView.setLines(commentDefaultLines);\n commentText = item.getCommentText();\n itemContentView.setText(commentText);\n itemContentView.setOnTouchListener(CommentTextOnTouchListener.INSTANCE);\n\n if (itemContentView.getLineCount() == 0) {\n itemContentView.post(() -> ellipsize());\n } else {\n ellipsize();\n }\n\n if (null != item.getLikeCount()) {\n itemLikesCountView.setText(String.valueOf(item.getLikeCount()));\n }\n itemPublishedTime.setText(item.getPublishedTime());\n\n itemView.setOnClickListener(view -> {\n toggleEllipsize();\n if (itemBuilder.getOnCommentsSelectedListener() != null) {\n itemBuilder.getOnCommentsSelectedListener().selected(item);\n }\n });\n }\n\n private void ellipsize() {\n if (itemContentView.getLineCount() > commentDefaultLines){\n int endOfLastLine = itemContentView.getLayout().getLineEnd(commentDefaultLines - 1);\n int end = itemContentView.getText().toString().lastIndexOf(' ', endOfLastLine -3);\n if(end == -1) end = Math.max(endOfLastLine -3, 0);\n String newVal = itemContentView.getText().subSequence(0, end) + \"...\";\n itemContentView.setText(newVal);\n }\n linkify();\n }\n\n private void toggleEllipsize() {\n if (itemContentView.getText().toString().equals(commentText)) {\n if (itemContentView.getLineCount() > commentDefaultLines) ellipsize();\n } else {\n expand();\n }\n }\n\n private void expand() {\n itemContentView.setMaxLines(commentExpandedLines);\n itemContentView.setText(commentText);\n linkify();\n }\n\n private void linkify(){\n Linkify.addLinks(itemContentView, Linkify.WEB_URLS);\n Linkify.addLinks(itemContentView, pattern, null, null, timestampLink);\n itemContentView.setMovementMethod(null);\n }\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.schabi.newpipe.info_list.holder;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.text.util.Linkify;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\n\nimport org.schabi.newpipe.R;\nimport org.schabi.newpipe.extractor.InfoItem;\nimport org.schabi.newpipe.extractor.comments.CommentsInfoItem;\nimport org.schabi.newpipe.info_list.InfoItemBuilder;\nimport org.schabi.newpipe.report.ErrorActivity;\nimport org.schabi.newpipe.util.CommentTextOnTouchListener;\nimport org.schabi.newpipe.util.ImageDisplayConstants;\nimport org.schabi.newpipe.util.NavigationHelper;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport de.hdodenhof.circleimageview.CircleImageView;\n\npublic class CommentsMiniInfoItemHolder extends InfoItemHolder {\n public final CircleImageView itemThumbnailView;\n private final TextView itemContentView;\n private final TextView itemLikesCountView;\n private final TextView itemDislikesCountView;\n private final TextView itemPublishedTime;\n\n private static final int commentDefaultLines = 2;\n private static final int commentExpandedLines = 1000;\n\n private String commentText;\n private String streamUrl;\n\n private static final Pattern pattern = Pattern.compile(\"(\\\\d+:)?(\\\\d+)?:(\\\\d+)\");\n\n private final Linkify.TransformFilter timestampLink = new Linkify.TransformFilter() {\n @Override\n public String transformUrl(Matcher match, String url) {\n int timestamp = 0;\n String hours = match.group(1);\n String minutes = match.group(2);\n String seconds = match.group(3);\n if(hours != null) timestamp += (Integer.parseInt(hours.replace(\":\", \"\"))*3600);\n if(minutes != null) timestamp += (Integer.parseInt(minutes.replace(\":\", \"\"))*60);\n if(seconds != null) timestamp += (Integer.parseInt(seconds));\n return streamUrl + url.replace(match.group(0), \"#timestamp=\" + String.valueOf(timestamp));\n }\n };\n\n CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, int layoutId, ViewGroup parent) {\n super(infoItemBuilder, layoutId, parent);\n\n itemThumbnailView = itemView.findViewById(R.id.itemThumbnailView);\n itemLikesCountView = itemView.findViewById(R.id.detail_thumbs_up_count_view);\n itemDislikesCountView = itemView.findViewById(R.id.detail_thumbs_down_count_view);\n itemPublishedTime = itemView.findViewById(R.id.itemPublishedTime);\n itemContentView = itemView.findViewById(R.id.itemCommentContentView);\n }\n\n public CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, ViewGroup parent) {\n this(infoItemBuilder, R.layout.list_comments_mini_item, parent);\n }\n\n @Override\n public void updateFromItem(final InfoItem infoItem) {\n if (!(infoItem instanceof CommentsInfoItem)) return;\n final CommentsInfoItem item = (CommentsInfoItem) infoItem;\n\n itemBuilder.getImageLoader()\n .displayImage(item.getAuthorThumbnail(),\n itemThumbnailView,\n ImageDisplayConstants.DISPLAY_THUMBNAIL_OPTIONS);\n\n itemThumbnailView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n try {\n final AppCompatActivity activity = (AppCompatActivity) itemBuilder.getContext();\n NavigationHelper.openChannelFragment(\n activity.getSupportFragmentManager(),\n item.getServiceId(),\n item.getAuthorEndpoint(),\n item.getAuthorName());\n } catch (Exception e) {\n ErrorActivity.reportUiError((AppCompatActivity) itemBuilder.getContext(), e);\n }\n }\n });\n\n streamUrl = item.getUrl();\n\n itemContentView.setMaxLines(commentDefaultLines);\n commentText = item.getCommentText();\n itemContentView.setText(commentText);\n linkify();\n itemContentView.setOnTouchListener(CommentTextOnTouchListener.INSTANCE);\n\n if(itemContentView.getLineCount() == 0){\n itemContentView.post(() -> ellipsize());\n }else{\n ellipsize();\n }\n\n if (null != item.getLikeCount()) {\n itemLikesCountView.setText(String.valueOf(item.getLikeCount()));\n }\n itemPublishedTime.setText(item.getPublishedTime());\n\n itemView.setOnClickListener(view -> {\n toggleEllipsize();\n if (itemBuilder.getOnCommentsSelectedListener() != null) {\n itemBuilder.getOnCommentsSelectedListener().selected(item);\n }\n });\n }\n\n private void ellipsize() {\n if (itemContentView.getLineCount() > commentDefaultLines){\n int endOfLastLine = itemContentView.getLayout().getLineEnd(commentDefaultLines - 1);\n String newVal = itemContentView.getText().subSequence(0, endOfLastLine - 3) + \"...\";\n itemContentView.setText(newVal);\n linkify();\n }\n }\n\n private void toggleEllipsize() {\n if (itemContentView.getText().toString().equals(commentText)) {\n ellipsize();\n } else {\n expand();\n }\n }\n\n private void expand() {\n itemContentView.setMaxLines(commentExpandedLines);\n itemContentView.setText(commentText);\n linkify();\n }\n\n private void linkify(){\n Linkify.addLinks(itemContentView, Linkify.WEB_URLS);\n Linkify.addLinks(itemContentView, pattern, null, null, timestampLink);\n itemContentView.setMovementMethod(null);\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.schabi.newpipe.info_list.holder;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.text.util.Linkify;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\n\nimport org.schabi.newpipe.R;\nimport org.schabi.newpipe.extractor.InfoItem;\nimport org.schabi.newpipe.extractor.comments.CommentsInfoItem;\nimport org.schabi.newpipe.info_list.InfoItemBuilder;\nimport org.schabi.newpipe.report.ErrorActivity;\nimport org.schabi.newpipe.util.CommentTextOnTouchListener;\nimport org.schabi.newpipe.util.ImageDisplayConstants;\nimport org.schabi.newpipe.util.NavigationHelper;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport de.hdodenhof.circleimageview.CircleImageView;\n\npublic class CommentsMiniInfoItemHolder extends InfoItemHolder {\n public final CircleImageView itemThumbnailView;\n private final TextView itemContentView;\n private final TextView itemLikesCountView;\n private final TextView itemDislikesCountView;\n private final TextView itemPublishedTime;\n\n private static final int commentDefaultLines = 2;\n private static final int commentExpandedLines = 1000;\n\n private String commentText;\n private String streamUrl;\n\n private static final Pattern pattern = Pattern.compile(\"(\\\\d+:)?(\\\\d+)?:(\\\\d+)\");\n\n private final Linkify.TransformFilter timestampLink = new Linkify.TransformFilter() {\n @Override\n public String transformUrl(Matcher match, String url) {\n int timestamp = 0;\n String hours = match.group(1);\n String minutes = match.group(2);\n String seconds = match.group(3);\n if(hours != null) timestamp += (Integer.parseInt(hours.replace(\":\", \"\"))*3600);\n if(minutes != null) timestamp += (Integer.parseInt(minutes.replace(\":\", \"\"))*60);\n if(seconds != null) timestamp += (Integer.parseInt(seconds));\n return streamUrl + url.replace(match.group(0), \"#timestamp=\" + String.valueOf(timestamp));\n }\n };\n\n CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, int layoutId, ViewGroup parent) {\n super(infoItemBuilder, layoutId, parent);\n\n itemThumbnailView = itemView.findViewById(R.id.itemThumbnailView);\n itemLikesCountView = itemView.findViewById(R.id.detail_thumbs_up_count_view);\n itemDislikesCountView = itemView.findViewById(R.id.detail_thumbs_down_count_view);\n itemPublishedTime = itemView.findViewById(R.id.itemPublishedTime);\n itemContentView = itemView.findViewById(R.id.itemCommentContentView);\n }\n\n public CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, ViewGroup parent) {\n this(infoItemBuilder, R.layout.list_comments_mini_item, parent);\n }\n\n @Override\n public void updateFromItem(final InfoItem infoItem) {\n if (!(infoItem instanceof CommentsInfoItem)) return;\n final CommentsInfoItem item = (CommentsInfoItem) infoItem;\n\n itemBuilder.getImageLoader()\n .displayImage(item.getAuthorThumbnail(),\n itemThumbnailView,\n ImageDisplayConstants.DISPLAY_THUMBNAIL_OPTIONS);\n\n itemThumbnailView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n try {\n final AppCompatActivity activity = (AppCompatActivity) itemBuilder.getContext();\n NavigationHelper.openChannelFragment(\n activity.getSupportFragmentManager(),\n item.getServiceId(),\n item.getAuthorEndpoint(),\n item.getAuthorName());\n } catch (Exception e) {\n ErrorActivity.reportUiError((AppCompatActivity) itemBuilder.getContext(), e);\n }\n }\n });\n\n streamUrl = item.getUrl();\n\n itemContentView.setMaxLines(commentDefaultLines);\n commentText = item.getCommentText();\n itemContentView.setText(commentText);\n linkify();\n itemContentView.setOnTouchListener(CommentTextOnTouchListener.INSTANCE);\n\n if(itemContentView.getLineCount() == 0){\n itemContentView.post(() -> ellipsize());\n }else{\n ellipsize();\n }\n\n if (null != item.getLikeCount()) {\n itemLikesCountView.setText(String.valueOf(item.getLikeCount()));\n }\n itemPublishedTime.setText(item.getPublishedTime());\n\n itemView.setOnClickListener(view -> {\n toggleEllipsize();\n if (itemBuilder.getOnCommentsSelectedListener() != null) {\n itemBuilder.getOnCommentsSelectedListener().selected(item);\n }\n });\n }\n\n private void ellipsize() {\n if (itemContentView.getLineCount() > commentDefaultLines){\n int endOfLastLine = itemContentView.getLayout().getLineEnd(commentDefaultLines - 1);\n String newVal = itemContentView.getText().subSequence(0, endOfLastLine - 3) + \"...\";\n itemContentView.setText(newVal);\n linkify();\n }\n }\n\n private void toggleEllipsize() {\n if (itemContentView.getText().toString().equals(commentText)) {\n ellipsize();\n } else {\n expand();\n }\n }\n\n private void expand() {\n itemContentView.setMaxLines(commentExpandedLines);\n itemContentView.setText(commentText);\n linkify();\n }\n\n private void linkify(){\n Linkify.addLinks(itemContentView, Linkify.WEB_URLS);\n Linkify.addLinks(itemContentView, pattern, null, null, timestampLink);\n itemContentView.setMovementMethod(null);\n }\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.schabi.newpipe.info_list.holder;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.text.util.Linkify;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\n\nimport org.schabi.newpipe.R;\nimport org.schabi.newpipe.extractor.InfoItem;\nimport org.schabi.newpipe.extractor.comments.CommentsInfoItem;\nimport org.schabi.newpipe.info_list.InfoItemBuilder;\nimport org.schabi.newpipe.report.ErrorActivity;\nimport org.schabi.newpipe.util.CommentTextOnTouchListener;\nimport org.schabi.newpipe.util.ImageDisplayConstants;\nimport org.schabi.newpipe.util.NavigationHelper;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport de.hdodenhof.circleimageview.CircleImageView;\n\npublic class CommentsMiniInfoItemHolder extends InfoItemHolder {\n public final CircleImageView itemThumbnailView;\n private final TextView itemContentView;\n private final TextView itemLikesCountView;\n private final TextView itemDislikesCountView;\n private final TextView itemPublishedTime;\n\n private static final int commentDefaultLines = 2;\n private static final int commentExpandedLines = 1000;\n\n private String commentText;\n private String streamUrl;\n\n private static final Pattern pattern = Pattern.compile(\"(\\\\d+:)?(\\\\d+)?:(\\\\d+)\");\n\n private final Linkify.TransformFilter timestampLink = new Linkify.TransformFilter() {\n @Override\n public String transformUrl(Matcher match, String url) {\n int timestamp = 0;\n String hours = match.group(1);\n String minutes = match.group(2);\n String seconds = match.group(3);\n if(hours != null) timestamp += (Integer.parseInt(hours.replace(\":\", \"\"))*3600);\n if(minutes != null) timestamp += (Integer.parseInt(minutes.replace(\":\", \"\"))*60);\n if(seconds != null) timestamp += (Integer.parseInt(seconds));\n return streamUrl + url.replace(match.group(0), \"#timestamp=\" + String.valueOf(timestamp));\n }\n };\n\n CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, int layoutId, ViewGroup parent) {\n super(infoItemBuilder, layoutId, parent);\n\n itemThumbnailView = itemView.findViewById(R.id.itemThumbnailView);\n itemLikesCountView = itemView.findViewById(R.id.detail_thumbs_up_count_view);\n itemDislikesCountView = itemView.findViewById(R.id.detail_thumbs_down_count_view);\n itemPublishedTime = itemView.findViewById(R.id.itemPublishedTime);\n itemContentView = itemView.findViewById(R.id.itemCommentContentView);\n }\n\n public CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, ViewGroup parent) {\n this(infoItemBuilder, R.layout.list_comments_mini_item, parent);\n }\n\n @Override\n public void updateFromItem(final InfoItem infoItem) {\n if (!(infoItem instanceof CommentsInfoItem)) return;\n final CommentsInfoItem item = (CommentsInfoItem) infoItem;\n\n itemBuilder.getImageLoader()\n .displayImage(item.getAuthorThumbnail(),\n itemThumbnailView,\n ImageDisplayConstants.DISPLAY_THUMBNAIL_OPTIONS);\n\n itemThumbnailView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n try {\n final AppCompatActivity activity = (AppCompatActivity) itemBuilder.getContext();\n NavigationHelper.openChannelFragment(\n activity.getSupportFragmentManager(),\n item.getServiceId(),\n item.getAuthorEndpoint(),\n item.getAuthorName());\n } catch (Exception e) {\n ErrorActivity.reportUiError((AppCompatActivity) itemBuilder.getContext(), e);\n }\n }\n });\n\n streamUrl = item.getUrl();\n\n itemContentView.setMaxLines(commentDefaultLines);\n commentText = item.getCommentText();\n itemContentView.setText(commentText);\n linkify();\n itemContentView.setOnTouchListener(CommentTextOnTouchListener.INSTANCE);\n\n if(itemContentView.getLineCount() == 0){\n itemContentView.post(() -> ellipsize());\n }else{\n ellipsize();\n }\n\n if (null != item.getLikeCount()) {\n itemLikesCountView.setText(String.valueOf(item.getLikeCount()));\n }\n itemPublishedTime.setText(item.getPublishedTime());\n\n itemView.setOnClickListener(view -> {\n toggleEllipsize();\n if (itemBuilder.getOnCommentsSelectedListener() != null) {\n itemBuilder.getOnCommentsSelectedListener().selected(item);\n }\n });\n }\n\n private void ellipsize() {\n if (itemContentView.getLineCount() > commentDefaultLines){\n int endOfLastLine = itemContentView.getLayout().getLineEnd(commentDefaultLines - 1);\n String newVal = itemContentView.getText().subSequence(0, endOfLastLine - 3) + \"...\";\n itemContentView.setText(newVal);\n linkify();\n }\n }\n\n private void toggleEllipsize() {\n if (itemContentView.getText().toString().equals(commentText)) {\n ellipsize();\n } else {\n expand();\n }\n }\n\n private void expand() {\n itemContentView.setMaxLines(commentExpandedLines);\n itemContentView.setText(commentText);\n linkify();\n }\n\n private void linkify(){\n Linkify.addLinks(itemContentView, Linkify.WEB_URLS);\n Linkify.addLinks(itemContentView, pattern, null, null, timestampLink);\n itemContentView.setMovementMethod(null);\n }\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the code to improve execution time. Write the entire code and no other text in the response.\n\n### Concepts:\n[in] onClick function\n[in] ellipsize function\n[in] toggleEllipsize function\n[-] setMaxLines\n[+] setLines\n[hint] optimize linkify() calls\n\n### Given program:\n```java\npackage org.schabi.newpipe.info_list.holder;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.text.util.Linkify;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\n\nimport org.schabi.newpipe.R;\nimport org.schabi.newpipe.extractor.InfoItem;\nimport org.schabi.newpipe.extractor.comments.CommentsInfoItem;\nimport org.schabi.newpipe.info_list.InfoItemBuilder;\nimport org.schabi.newpipe.report.ErrorActivity;\nimport org.schabi.newpipe.util.CommentTextOnTouchListener;\nimport org.schabi.newpipe.util.ImageDisplayConstants;\nimport org.schabi.newpipe.util.NavigationHelper;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport de.hdodenhof.circleimageview.CircleImageView;\n\npublic class CommentsMiniInfoItemHolder extends InfoItemHolder {\n public final CircleImageView itemThumbnailView;\n private final TextView itemContentView;\n private final TextView itemLikesCountView;\n private final TextView itemDislikesCountView;\n private final TextView itemPublishedTime;\n\n private static final int commentDefaultLines = 2;\n private static final int commentExpandedLines = 1000;\n\n private String commentText;\n private String streamUrl;\n\n private static final Pattern pattern = Pattern.compile(\"(\\\\d+:)?(\\\\d+)?:(\\\\d+)\");\n\n private final Linkify.TransformFilter timestampLink = new Linkify.TransformFilter() {\n @Override\n public String transformUrl(Matcher match, String url) {\n int timestamp = 0;\n String hours = match.group(1);\n String minutes = match.group(2);\n String seconds = match.group(3);\n if(hours != null) timestamp += (Integer.parseInt(hours.replace(\":\", \"\"))*3600);\n if(minutes != null) timestamp += (Integer.parseInt(minutes.replace(\":\", \"\"))*60);\n if(seconds != null) timestamp += (Integer.parseInt(seconds));\n return streamUrl + url.replace(match.group(0), \"#timestamp=\" + String.valueOf(timestamp));\n }\n };\n\n CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, int layoutId, ViewGroup parent) {\n super(infoItemBuilder, layoutId, parent);\n\n itemThumbnailView = itemView.findViewById(R.id.itemThumbnailView);\n itemLikesCountView = itemView.findViewById(R.id.detail_thumbs_up_count_view);\n itemDislikesCountView = itemView.findViewById(R.id.detail_thumbs_down_count_view);\n itemPublishedTime = itemView.findViewById(R.id.itemPublishedTime);\n itemContentView = itemView.findViewById(R.id.itemCommentContentView);\n }\n\n public CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, ViewGroup parent) {\n this(infoItemBuilder, R.layout.list_comments_mini_item, parent);\n }\n\n @Override\n public void updateFromItem(final InfoItem infoItem) {\n if (!(infoItem instanceof CommentsInfoItem)) return;\n final CommentsInfoItem item = (CommentsInfoItem) infoItem;\n\n itemBuilder.getImageLoader()\n .displayImage(item.getAuthorThumbnail(),\n itemThumbnailView,\n ImageDisplayConstants.DISPLAY_THUMBNAIL_OPTIONS);\n\n itemThumbnailView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n try {\n final AppCompatActivity activity = (AppCompatActivity) itemBuilder.getContext();\n NavigationHelper.openChannelFragment(\n activity.getSupportFragmentManager(),\n item.getServiceId(),\n item.getAuthorEndpoint(),\n item.getAuthorName());\n } catch (Exception e) {\n ErrorActivity.reportUiError((AppCompatActivity) itemBuilder.getContext(), e);\n }\n }\n });\n\n streamUrl = item.getUrl();\n\n itemContentView.setMaxLines(commentDefaultLines);\n commentText = item.getCommentText();\n itemContentView.setText(commentText);\n linkify();\n itemContentView.setOnTouchListener(CommentTextOnTouchListener.INSTANCE);\n\n if(itemContentView.getLineCount() == 0){\n itemContentView.post(() -> ellipsize());\n }else{\n ellipsize();\n }\n\n if (null != item.getLikeCount()) {\n itemLikesCountView.setText(String.valueOf(item.getLikeCount()));\n }\n itemPublishedTime.setText(item.getPublishedTime());\n\n itemView.setOnClickListener(view -> {\n toggleEllipsize();\n if (itemBuilder.getOnCommentsSelectedListener() != null) {\n itemBuilder.getOnCommentsSelectedListener().selected(item);\n }\n });\n }\n\n private void ellipsize() {\n if (itemContentView.getLineCount() > commentDefaultLines){\n int endOfLastLine = itemContentView.getLayout().getLineEnd(commentDefaultLines - 1);\n String newVal = itemContentView.getText().subSequence(0, endOfLastLine - 3) + \"...\";\n itemContentView.setText(newVal);\n linkify();\n }\n }\n\n private void toggleEllipsize() {\n if (itemContentView.getText().toString().equals(commentText)) {\n ellipsize();\n } else {\n expand();\n }\n }\n\n private void expand() {\n itemContentView.setMaxLines(commentExpandedLines);\n itemContentView.setText(commentText);\n linkify();\n }\n\n private void linkify(){\n Linkify.addLinks(itemContentView, Linkify.WEB_URLS);\n Linkify.addLinks(itemContentView, pattern, null, null, timestampLink);\n itemContentView.setMovementMethod(null);\n }\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.autocomplete\n\nimport android.content.Context\nimport android.util.Log\nimport kotlinx.coroutines.experimental.CommonPool\nimport kotlinx.coroutines.experimental.android.UI\nimport kotlinx.coroutines.experimental.async\nimport kotlinx.coroutines.experimental.launch\nimport org.mozilla.focus.locale.Locales\nimport org.mozilla.focus.utils.Settings\nimport org.mozilla.focus.widget.InlineAutocompleteEditText\nimport java.io.IOException\nimport java.util.*\nimport kotlin.collections.LinkedHashSet\n\nclass UrlAutoCompleteFilter : InlineAutocompleteEditText.OnFilterListener {\n companion object {\n private val LOG_TAG = \"UrlAutoCompleteFilter\"\n }\n\n private var settings : Settings? = null\n\n private var customDomains : List = emptyList()\n private var preInstalledDomains : List = emptyList()\n\n override fun onFilter(rawSearchText: String, view: InlineAutocompleteEditText?) {\n if (view == null) {\n return\n }\n\n \/\/ Search terms are all lowercase already, we just need to lowercase the search text\n val searchText = rawSearchText.toLowerCase(Locale.US)\n\n settings?.let {\n if (it.shouldAutocompleteFromCustomDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, customDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n\n if (it.shouldAutocompleteFromShippedDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, preInstalledDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n }\n }\n\n private fun tryToAutocomplete(searchText: String, domains: List): String? {\n domains.forEach {\n val wwwDomain = \"www.\" + it\n if (wwwDomain.startsWith(searchText)) {\n return wwwDomain\n }\n\n if (it.startsWith(searchText)) {\n return it\n }\n }\n\n return null\n }\n\n internal fun onDomainsLoaded(domains: List, customDomains: List) {\n this.preInstalledDomains = domains\n this.customDomains = customDomains\n }\n\n fun load(context: Context, loadDomainsFromDisk: Boolean = true) {\n settings = Settings.getInstance(context)\n\n if (loadDomainsFromDisk) {\n launch(UI) {\n val domains = async(CommonPool) { loadDomains(context) }\n val customDomains = async(CommonPool) { CustomAutocomplete.loadCustomAutoCompleteDomains(context) }\n\n onDomainsLoaded(domains.await(), customDomains.await())\n }\n }\n }\n\n private suspend fun loadDomains(context: Context): List {\n val domains = LinkedHashSet()\n val availableLists = getAvailableDomainLists(context)\n\n \/\/ First load the country specific lists following the default locale order\n Locales.getCountriesInDefaultLocaleList()\n .asSequence()\n .filter { availableLists.contains(it) }\n .forEach { loadDomainsForLanguage(context, domains, it) }\n\n \/\/ And then add domains from the global list\n loadDomainsForLanguage(context, domains, \"global\")\n\n return domains.toList()\n }\n\n private fun getAvailableDomainLists(context: Context): Set {\n val availableDomains = LinkedHashSet()\n\n val assetManager = context.assets\n\n try {\n availableDomains.addAll(assetManager.list(\"domains\"))\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not list domain list directory\")\n }\n\n return availableDomains\n }\n\n private fun loadDomainsForLanguage(context: Context, domains: MutableSet, country: String) {\n val assetManager = context.assets\n\n try {\n domains.addAll(\n assetManager.open(\"domains\/\" + country).bufferedReader().readLines())\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not load domain list: \" + country)\n }\n }\n\n \/**\n * Our autocomplete list is all lower case, however the search text might be mixed case.\n * Our autocomplete EditText code does more string comparison, which fails if the suggestion\n * doesn't exactly match searchText (ie. if casing differs). It's simplest to just build a suggestion\n * that exactly matches the search text - which is what this method is for:\n *\/\n private fun prepareAutocompleteResult(rawSearchText: String, lowerCaseResult: String) =\n rawSearchText + lowerCaseResult.substring(rawSearchText.length)\n}\n\n\nCode-B:\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.autocomplete\n\nimport android.content.Context\nimport android.util.Log\nimport kotlinx.coroutines.experimental.CommonPool\nimport kotlinx.coroutines.experimental.android.UI\nimport kotlinx.coroutines.experimental.async\nimport kotlinx.coroutines.experimental.launch\nimport org.mozilla.focus.locale.Locales\nimport org.mozilla.focus.utils.Settings\nimport org.mozilla.focus.widget.InlineAutocompleteEditText\nimport java.io.IOException\nimport java.util.*\nimport kotlin.collections.LinkedHashSet\n\nclass UrlAutoCompleteFilter : InlineAutocompleteEditText.OnFilterListener {\n companion object {\n private val LOG_TAG = \"UrlAutoCompleteFilter\"\n }\n\n private var settings : Settings? = null\n\n private var customDomains : List = emptyList()\n private var preInstalledDomains : List = emptyList()\n\n override fun onFilter(rawSearchText: String, view: InlineAutocompleteEditText?) {\n if (view == null) {\n return\n }\n\n \/\/ Search terms are all lowercase already, we just need to lowercase the search text\n val searchText = rawSearchText.toLowerCase(Locale.US)\n\n settings?.let {\n if (it.shouldAutocompleteFromCustomDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, customDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n\n if (it.shouldAutocompleteFromShippedDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, preInstalledDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n }\n }\n\n private fun tryToAutocomplete(searchText: String, domains: List): String? {\n domains.forEach {\n val wwwDomain = \"www.\" + it\n if (wwwDomain.startsWith(searchText)) {\n return wwwDomain\n }\n\n if (it.startsWith(searchText)) {\n return it\n }\n }\n\n return null\n }\n\n internal fun onDomainsLoaded(domains: List, customDomains: List) {\n this.preInstalledDomains = domains\n this.customDomains = customDomains\n }\n\n fun load(context: Context, loadDomainsFromDisk: Boolean = true) {\n settings = Settings.getInstance(context)\n\n if (loadDomainsFromDisk) {\n launch(UI) {\n val domains = async(CommonPool) { loadDomains(context) }\n val customDomains = async(CommonPool) { CustomAutocomplete.loadCustomAutoCompleteDomains(context) }\n\n onDomainsLoaded(domains.await(), customDomains.await())\n }\n }\n }\n\n private suspend fun loadDomains(context: Context): List {\n val domains = LinkedHashSet()\n val availableLists = getAvailableDomainLists(context)\n\n \/\/ First load the country specific lists following the default locale order\n Locales.getCountriesInDefaultLocaleList()\n .asSequence()\n .filter { availableLists.contains(it) }\n .forEach { loadDomainsForLanguage(context, domains, it) }\n\n \/\/ And then add domains from the global list\n loadDomainsForLanguage(context, domains, \"global\")\n\n return domains.toList()\n }\n\n private fun getAvailableDomainLists(context: Context): Set {\n val availableDomains = LinkedHashSet()\n\n val assetManager = context.assets\n\n try {\n Collections.addAll(availableDomains, *assetManager.list(\"domains\"))\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not list domain list directory\")\n }\n\n return availableDomains\n }\n\n private fun loadDomainsForLanguage(context: Context, domains: MutableSet, country: String) {\n val assetManager = context.assets\n\n try {\n domains.addAll(\n assetManager.open(\"domains\/\" + country).bufferedReader().readLines())\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not load domain list: \" + country)\n }\n }\n\n \/**\n * Our autocomplete list is all lower case, however the search text might be mixed case.\n * Our autocomplete EditText code does more string comparison, which fails if the suggestion\n * doesn't exactly match searchText (ie. if casing differs). It's simplest to just build a suggestion\n * that exactly matches the search text - which is what this method is for:\n *\/\n private fun prepareAutocompleteResult(rawSearchText: String, lowerCaseResult: String) =\n rawSearchText + lowerCaseResult.substring(rawSearchText.length)\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.autocomplete\n\nimport android.content.Context\nimport android.util.Log\nimport kotlinx.coroutines.experimental.CommonPool\nimport kotlinx.coroutines.experimental.android.UI\nimport kotlinx.coroutines.experimental.async\nimport kotlinx.coroutines.experimental.launch\nimport org.mozilla.focus.locale.Locales\nimport org.mozilla.focus.utils.Settings\nimport org.mozilla.focus.widget.InlineAutocompleteEditText\nimport java.io.IOException\nimport java.util.*\nimport kotlin.collections.LinkedHashSet\n\nclass UrlAutoCompleteFilter : InlineAutocompleteEditText.OnFilterListener {\n companion object {\n private val LOG_TAG = \"UrlAutoCompleteFilter\"\n }\n\n private var settings : Settings? = null\n\n private var customDomains : List = emptyList()\n private var preInstalledDomains : List = emptyList()\n\n override fun onFilter(rawSearchText: String, view: InlineAutocompleteEditText?) {\n if (view == null) {\n return\n }\n\n \/\/ Search terms are all lowercase already, we just need to lowercase the search text\n val searchText = rawSearchText.toLowerCase(Locale.US)\n\n settings?.let {\n if (it.shouldAutocompleteFromCustomDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, customDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n\n if (it.shouldAutocompleteFromShippedDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, preInstalledDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n }\n }\n\n private fun tryToAutocomplete(searchText: String, domains: List): String? {\n domains.forEach {\n val wwwDomain = \"www.\" + it\n if (wwwDomain.startsWith(searchText)) {\n return wwwDomain\n }\n\n if (it.startsWith(searchText)) {\n return it\n }\n }\n\n return null\n }\n\n internal fun onDomainsLoaded(domains: List, customDomains: List) {\n this.preInstalledDomains = domains\n this.customDomains = customDomains\n }\n\n fun load(context: Context, loadDomainsFromDisk: Boolean = true) {\n settings = Settings.getInstance(context)\n\n if (loadDomainsFromDisk) {\n launch(UI) {\n val domains = async(CommonPool) { loadDomains(context) }\n val customDomains = async(CommonPool) { CustomAutocomplete.loadCustomAutoCompleteDomains(context) }\n\n onDomainsLoaded(domains.await(), customDomains.await())\n }\n }\n }\n\n private suspend fun loadDomains(context: Context): List {\n val domains = LinkedHashSet()\n val availableLists = getAvailableDomainLists(context)\n\n \/\/ First load the country specific lists following the default locale order\n Locales.getCountriesInDefaultLocaleList()\n .asSequence()\n .filter { availableLists.contains(it) }\n .forEach { loadDomainsForLanguage(context, domains, it) }\n\n \/\/ And then add domains from the global list\n loadDomainsForLanguage(context, domains, \"global\")\n\n return domains.toList()\n }\n\n private fun getAvailableDomainLists(context: Context): Set {\n val availableDomains = LinkedHashSet()\n\n val assetManager = context.assets\n\n try {\n Collections.addAll(availableDomains, *assetManager.list(\"domains\"))\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not list domain list directory\")\n }\n\n return availableDomains\n }\n\n private fun loadDomainsForLanguage(context: Context, domains: MutableSet, country: String) {\n val assetManager = context.assets\n\n try {\n domains.addAll(\n assetManager.open(\"domains\/\" + country).bufferedReader().readLines())\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not load domain list: \" + country)\n }\n }\n\n \/**\n * Our autocomplete list is all lower case, however the search text might be mixed case.\n * Our autocomplete EditText code does more string comparison, which fails if the suggestion\n * doesn't exactly match searchText (ie. if casing differs). It's simplest to just build a suggestion\n * that exactly matches the search text - which is what this method is for:\n *\/\n private fun prepareAutocompleteResult(rawSearchText: String, lowerCaseResult: String) =\n rawSearchText + lowerCaseResult.substring(rawSearchText.length)\n}\n\n\nCode-B:\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus.autocomplete\n\nimport android.content.Context\nimport android.util.Log\nimport kotlinx.coroutines.experimental.CommonPool\nimport kotlinx.coroutines.experimental.android.UI\nimport kotlinx.coroutines.experimental.async\nimport kotlinx.coroutines.experimental.launch\nimport org.mozilla.focus.locale.Locales\nimport org.mozilla.focus.utils.Settings\nimport org.mozilla.focus.widget.InlineAutocompleteEditText\nimport java.io.IOException\nimport java.util.*\nimport kotlin.collections.LinkedHashSet\n\nclass UrlAutoCompleteFilter : InlineAutocompleteEditText.OnFilterListener {\n companion object {\n private val LOG_TAG = \"UrlAutoCompleteFilter\"\n }\n\n private var settings : Settings? = null\n\n private var customDomains : List = emptyList()\n private var preInstalledDomains : List = emptyList()\n\n override fun onFilter(rawSearchText: String, view: InlineAutocompleteEditText?) {\n if (view == null) {\n return\n }\n\n \/\/ Search terms are all lowercase already, we just need to lowercase the search text\n val searchText = rawSearchText.toLowerCase(Locale.US)\n\n settings?.let {\n if (it.shouldAutocompleteFromCustomDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, customDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n\n if (it.shouldAutocompleteFromShippedDomainList()) {\n val autocomplete = tryToAutocomplete(searchText, preInstalledDomains)\n if (autocomplete != null) {\n view.onAutocomplete(prepareAutocompleteResult(rawSearchText, autocomplete))\n return\n }\n }\n }\n }\n\n private fun tryToAutocomplete(searchText: String, domains: List): String? {\n domains.forEach {\n val wwwDomain = \"www.\" + it\n if (wwwDomain.startsWith(searchText)) {\n return wwwDomain\n }\n\n if (it.startsWith(searchText)) {\n return it\n }\n }\n\n return null\n }\n\n internal fun onDomainsLoaded(domains: List, customDomains: List) {\n this.preInstalledDomains = domains\n this.customDomains = customDomains\n }\n\n fun load(context: Context, loadDomainsFromDisk: Boolean = true) {\n settings = Settings.getInstance(context)\n\n if (loadDomainsFromDisk) {\n launch(UI) {\n val domains = async(CommonPool) { loadDomains(context) }\n val customDomains = async(CommonPool) { CustomAutocomplete.loadCustomAutoCompleteDomains(context) }\n\n onDomainsLoaded(domains.await(), customDomains.await())\n }\n }\n }\n\n private suspend fun loadDomains(context: Context): List {\n val domains = LinkedHashSet()\n val availableLists = getAvailableDomainLists(context)\n\n \/\/ First load the country specific lists following the default locale order\n Locales.getCountriesInDefaultLocaleList()\n .asSequence()\n .filter { availableLists.contains(it) }\n .forEach { loadDomainsForLanguage(context, domains, it) }\n\n \/\/ And then add domains from the global list\n loadDomainsForLanguage(context, domains, \"global\")\n\n return domains.toList()\n }\n\n private fun getAvailableDomainLists(context: Context): Set {\n val availableDomains = LinkedHashSet()\n\n val assetManager = context.assets\n\n try {\n availableDomains.addAll(assetManager.list(\"domains\"))\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not list domain list directory\")\n }\n\n return availableDomains\n }\n\n private fun loadDomainsForLanguage(context: Context, domains: MutableSet, country: String) {\n val assetManager = context.assets\n\n try {\n domains.addAll(\n assetManager.open(\"domains\/\" + country).bufferedReader().readLines())\n } catch (e: IOException) {\n Log.w(LOG_TAG, \"Could not load domain list: \" + country)\n }\n }\n\n \/**\n * Our autocomplete list is all lower case, however the search text might be mixed case.\n * Our autocomplete EditText code does more string comparison, which fails if the suggestion\n * doesn't exactly match searchText (ie. if casing differs). It's simplest to just build a suggestion\n * that exactly matches the search text - which is what this method is for:\n *\/\n private fun prepareAutocompleteResult(rawSearchText: String, lowerCaseResult: String) =\n rawSearchText + lowerCaseResult.substring(rawSearchText.length)\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/vaginessa\/TestBrowser-Lightning\/commit\/4c75b9ffb5fc0faf8d0d092e0a26ce0dedbae8c8","commit_message":"'\\\\\"Increased history query efficiency\\\\n\\\\\"'","source_code":"\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void delete(String url) {\n\t\tString n = getHistoryItem(url);\n\t\tif (n != null) {\n\t\t\tdeleteHistoryItem(n);\n\t\t}\n\t}\n\t\n\tpublic synchronized void visitHistoryItem(String url, String title){\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToPrevious());\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Deleting single item\n\tpublic synchronized void deleteHistoryItem(String id) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_ID + \" = ?\", new String[] { String.valueOf(id) });\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n","target_code":"\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void delete(String url) {\n\t\tString n = getHistoryItem(url);\n\t\tif (n != null) {\n\t\t\tdeleteHistoryItem(n);\n\t\t}\n\t}\n\n\tpublic synchronized void visitHistoryItem(String url, String title) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tint n = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t\tn++;\n\t\t\t} while (cursor.moveToPrevious() && n < 5);\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Deleting single item\n\tpublic synchronized void deleteHistoryItem(String id) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_ID + \" = ?\", new String[] { String.valueOf(id) });\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void delete(String url) {\n\t\tString n = getHistoryItem(url);\n\t\tif (n != null) {\n\t\t\tdeleteHistoryItem(n);\n\t\t}\n\t}\n\t\n\tpublic synchronized void visitHistoryItem(String url, String title){\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToPrevious());\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Deleting single item\n\tpublic synchronized void deleteHistoryItem(String id) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_ID + \" = ?\", new String[] { String.valueOf(id) });\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void delete(String url) {\n\t\tString n = getHistoryItem(url);\n\t\tif (n != null) {\n\t\t\tdeleteHistoryItem(n);\n\t\t}\n\t}\n\t\n\tpublic synchronized void visitHistoryItem(String url, String title){\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToPrevious());\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Deleting single item\n\tpublic synchronized void deleteHistoryItem(String id) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_ID + \" = ?\", new String[] { String.valueOf(id) });\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void delete(String url) {\n\t\tString n = getHistoryItem(url);\n\t\tif (n != null) {\n\t\t\tdeleteHistoryItem(n);\n\t\t}\n\t}\n\t\n\tpublic synchronized void visitHistoryItem(String url, String title){\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToPrevious());\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Deleting single item\n\tpublic synchronized void deleteHistoryItem(String id) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_ID + \" = ?\", new String[] { String.valueOf(id) });\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite findItemsContaining function to improve execution time by limiting the history size. Write the entire code and no other text in the response.\n\n### Concepts:\n[in] findItemsContaining function\n[hint] limit the history size to 5.\n\n### Given program:\n```java\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void delete(String url) {\n\t\tString n = getHistoryItem(url);\n\t\tif (n != null) {\n\t\t\tdeleteHistoryItem(n);\n\t\t}\n\t}\n\t\n\tpublic synchronized void visitHistoryItem(String url, String title){\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToPrevious());\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Deleting single item\n\tpublic synchronized void deleteHistoryItem(String id) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_ID + \" = ?\", new String[] { String.valueOf(id) });\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage us.shandian.giga.get;\n\nimport android.util.Log;\n\nimport java.io.RandomAccessFile;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\n\nimport static org.schabi.newpipe.BuildConfig.DEBUG;\n\n\/**\n * Runnable to download blocks of a file until the file is completely downloaded,\n * an error occurs or the process is stopped.\n *\/\npublic class DownloadRunnable implements Runnable {\n private static final String TAG = DownloadRunnable.class.getSimpleName();\n\n private final DownloadMission mMission;\n private final int mId;\n\n public DownloadRunnable(DownloadMission mission, int id) {\n if (mission == null) throw new NullPointerException(\"mission is null\");\n mMission = mission;\n mId = id;\n }\n\n @Override\n public void run() {\n boolean retry = mMission.recovered;\n long position = mMission.getPosition(mId);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":default pos \" + position);\n Log.d(TAG, mId + \":recovered: \" + mMission.recovered);\n }\n\n while (mMission.errCode == -1 && mMission.running && position < mMission.blocks) {\n\n if (Thread.currentThread().isInterrupted()) {\n mMission.pause();\n return;\n }\n\n if (DEBUG && retry) {\n Log.d(TAG, mId + \":retry is true. Resuming at \" + position);\n }\n\n \/\/ Wait for an unblocked position\n while (!retry && position < mMission.blocks && mMission.isBlockPreserved(position)) {\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" preserved, passing\");\n }\n\n position++;\n }\n\n retry = false;\n\n if (position >= mMission.blocks) {\n break;\n }\n\n if (DEBUG) {\n Log.d(TAG, mId + \":preserving position \" + position);\n }\n\n mMission.preserveBlock(position);\n mMission.setPosition(mId, position);\n\n long start = position * DownloadManager.BLOCK_SIZE;\n long end = start + DownloadManager.BLOCK_SIZE - 1;\n\n if (end >= mMission.length) {\n end = mMission.length - 1;\n }\n\n HttpURLConnection conn = null;\n\n int total = 0;\n\n try {\n URL url = new URL(mMission.url);\n conn = (HttpURLConnection) url.openConnection();\n conn.setRequestProperty(\"Range\", \"bytes=\" + start + \"-\" + end);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":\" + conn.getRequestProperty(\"Range\"));\n Log.d(TAG, mId + \":Content-Length=\" + conn.getContentLength() + \" Code:\" + conn.getResponseCode());\n }\n\n \/\/ A server may be ignoring the range request\n if (conn.getResponseCode() != 206) {\n mMission.errCode = DownloadMission.ERROR_SERVER_UNSUPPORTED;\n notifyError(DownloadMission.ERROR_SERVER_UNSUPPORTED);\n\n if (DEBUG) {\n Log.e(TAG, mId + \":Unsupported \" + conn.getResponseCode());\n }\n\n break;\n }\n\n RandomAccessFile f = new RandomAccessFile(mMission.location + \"\/\" + mMission.name, \"rw\");\n f.seek(start);\n java.io.InputStream ipt = conn.getInputStream();\n byte[] buf = new byte[64*1024];\n\n while (start < end && mMission.running) {\n int len = ipt.read(buf, 0, buf.length);\n\n if (len == -1) {\n break;\n } else {\n start += len;\n total += len;\n f.write(buf, 0, len);\n notifyProgress(len);\n }\n }\n\n if (DEBUG && mMission.running) {\n Log.d(TAG, mId + \":position \" + position + \" finished, total length \" + total);\n }\n\n f.close();\n ipt.close();\n\n \/\/ TODO We should save progress for each thread\n } catch (Exception e) {\n \/\/ TODO Retry count limit & notify error\n retry = true;\n\n notifyProgress(-total);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" retrying\", e);\n }\n }\n }\n\n if (DEBUG) {\n Log.d(TAG, \"thread \" + mId + \" exited main loop\");\n }\n\n if (mMission.errCode == -1 && mMission.running) {\n if (DEBUG) {\n Log.d(TAG, \"no error has happened, notifying\");\n }\n notifyFinished();\n }\n\n if (DEBUG && !mMission.running) {\n Log.d(TAG, \"The mission has been paused. Passing.\");\n }\n }\n\n private void notifyProgress(final long len) {\n synchronized (mMission) {\n mMission.notifyProgress(len);\n }\n }\n\n private void notifyError(final int err) {\n synchronized (mMission) {\n mMission.notifyError(err);\n mMission.pause();\n }\n }\n\n private void notifyFinished() {\n synchronized (mMission) {\n mMission.notifyFinished();\n }\n }\n}\n\n\nCode-B:\npackage us.shandian.giga.get;\n\nimport android.util.Log;\n\nimport java.io.BufferedInputStream;\nimport java.io.RandomAccessFile;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\n\nimport static org.schabi.newpipe.BuildConfig.DEBUG;\n\n\/**\n * Runnable to download blocks of a file until the file is completely downloaded,\n * an error occurs or the process is stopped.\n *\/\npublic class DownloadRunnable implements Runnable {\n private static final String TAG = DownloadRunnable.class.getSimpleName();\n\n private final DownloadMission mMission;\n private final int mId;\n\n public DownloadRunnable(DownloadMission mission, int id) {\n if (mission == null) throw new NullPointerException(\"mission is null\");\n mMission = mission;\n mId = id;\n }\n\n @Override\n public void run() {\n boolean retry = mMission.recovered;\n long position = mMission.getPosition(mId);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":default pos \" + position);\n Log.d(TAG, mId + \":recovered: \" + mMission.recovered);\n }\n\n while (mMission.errCode == -1 && mMission.running && position < mMission.blocks) {\n\n if (Thread.currentThread().isInterrupted()) {\n mMission.pause();\n return;\n }\n\n if (DEBUG && retry) {\n Log.d(TAG, mId + \":retry is true. Resuming at \" + position);\n }\n\n \/\/ Wait for an unblocked position\n while (!retry && position < mMission.blocks && mMission.isBlockPreserved(position)) {\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" preserved, passing\");\n }\n\n position++;\n }\n\n retry = false;\n\n if (position >= mMission.blocks) {\n break;\n }\n\n if (DEBUG) {\n Log.d(TAG, mId + \":preserving position \" + position);\n }\n\n mMission.preserveBlock(position);\n mMission.setPosition(mId, position);\n\n long start = position * DownloadManager.BLOCK_SIZE;\n long end = start + DownloadManager.BLOCK_SIZE - 1;\n\n if (end >= mMission.length) {\n end = mMission.length - 1;\n }\n\n HttpURLConnection conn = null;\n\n int total = 0;\n\n try {\n URL url = new URL(mMission.url);\n conn = (HttpURLConnection) url.openConnection();\n conn.setRequestProperty(\"Range\", \"bytes=\" + start + \"-\" + end);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":\" + conn.getRequestProperty(\"Range\"));\n Log.d(TAG, mId + \":Content-Length=\" + conn.getContentLength() + \" Code:\" + conn.getResponseCode());\n }\n\n \/\/ A server may be ignoring the range request\n if (conn.getResponseCode() != 206) {\n mMission.errCode = DownloadMission.ERROR_SERVER_UNSUPPORTED;\n notifyError(DownloadMission.ERROR_SERVER_UNSUPPORTED);\n\n if (DEBUG) {\n Log.e(TAG, mId + \":Unsupported \" + conn.getResponseCode());\n }\n\n break;\n }\n\n RandomAccessFile f = new RandomAccessFile(mMission.location + \"\/\" + mMission.name, \"rw\");\n f.seek(start);\n BufferedInputStream ipt = new BufferedInputStream(conn.getInputStream());\n byte[] buf = new byte[512];\n\n while (start < end && mMission.running) {\n int len = ipt.read(buf, 0, 512);\n\n if (len == -1) {\n break;\n } else {\n start += len;\n total += len;\n f.write(buf, 0, len);\n notifyProgress(len);\n }\n }\n\n if (DEBUG && mMission.running) {\n Log.d(TAG, mId + \":position \" + position + \" finished, total length \" + total);\n }\n\n f.close();\n ipt.close();\n\n \/\/ TODO We should save progress for each thread\n } catch (Exception e) {\n \/\/ TODO Retry count limit & notify error\n retry = true;\n\n notifyProgress(-total);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" retrying\", e);\n }\n }\n }\n\n if (DEBUG) {\n Log.d(TAG, \"thread \" + mId + \" exited main loop\");\n }\n\n if (mMission.errCode == -1 && mMission.running) {\n if (DEBUG) {\n Log.d(TAG, \"no error has happened, notifying\");\n }\n notifyFinished();\n }\n\n if (DEBUG && !mMission.running) {\n Log.d(TAG, \"The mission has been paused. Passing.\");\n }\n }\n\n private void notifyProgress(final long len) {\n synchronized (mMission) {\n mMission.notifyProgress(len);\n }\n }\n\n private void notifyError(final int err) {\n synchronized (mMission) {\n mMission.notifyError(err);\n mMission.pause();\n }\n }\n\n private void notifyFinished() {\n synchronized (mMission) {\n mMission.notifyFinished();\n }\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage us.shandian.giga.get;\n\nimport android.util.Log;\n\nimport java.io.BufferedInputStream;\nimport java.io.RandomAccessFile;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\n\nimport static org.schabi.newpipe.BuildConfig.DEBUG;\n\n\/**\n * Runnable to download blocks of a file until the file is completely downloaded,\n * an error occurs or the process is stopped.\n *\/\npublic class DownloadRunnable implements Runnable {\n private static final String TAG = DownloadRunnable.class.getSimpleName();\n\n private final DownloadMission mMission;\n private final int mId;\n\n public DownloadRunnable(DownloadMission mission, int id) {\n if (mission == null) throw new NullPointerException(\"mission is null\");\n mMission = mission;\n mId = id;\n }\n\n @Override\n public void run() {\n boolean retry = mMission.recovered;\n long position = mMission.getPosition(mId);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":default pos \" + position);\n Log.d(TAG, mId + \":recovered: \" + mMission.recovered);\n }\n\n while (mMission.errCode == -1 && mMission.running && position < mMission.blocks) {\n\n if (Thread.currentThread().isInterrupted()) {\n mMission.pause();\n return;\n }\n\n if (DEBUG && retry) {\n Log.d(TAG, mId + \":retry is true. Resuming at \" + position);\n }\n\n \/\/ Wait for an unblocked position\n while (!retry && position < mMission.blocks && mMission.isBlockPreserved(position)) {\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" preserved, passing\");\n }\n\n position++;\n }\n\n retry = false;\n\n if (position >= mMission.blocks) {\n break;\n }\n\n if (DEBUG) {\n Log.d(TAG, mId + \":preserving position \" + position);\n }\n\n mMission.preserveBlock(position);\n mMission.setPosition(mId, position);\n\n long start = position * DownloadManager.BLOCK_SIZE;\n long end = start + DownloadManager.BLOCK_SIZE - 1;\n\n if (end >= mMission.length) {\n end = mMission.length - 1;\n }\n\n HttpURLConnection conn = null;\n\n int total = 0;\n\n try {\n URL url = new URL(mMission.url);\n conn = (HttpURLConnection) url.openConnection();\n conn.setRequestProperty(\"Range\", \"bytes=\" + start + \"-\" + end);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":\" + conn.getRequestProperty(\"Range\"));\n Log.d(TAG, mId + \":Content-Length=\" + conn.getContentLength() + \" Code:\" + conn.getResponseCode());\n }\n\n \/\/ A server may be ignoring the range request\n if (conn.getResponseCode() != 206) {\n mMission.errCode = DownloadMission.ERROR_SERVER_UNSUPPORTED;\n notifyError(DownloadMission.ERROR_SERVER_UNSUPPORTED);\n\n if (DEBUG) {\n Log.e(TAG, mId + \":Unsupported \" + conn.getResponseCode());\n }\n\n break;\n }\n\n RandomAccessFile f = new RandomAccessFile(mMission.location + \"\/\" + mMission.name, \"rw\");\n f.seek(start);\n BufferedInputStream ipt = new BufferedInputStream(conn.getInputStream());\n byte[] buf = new byte[512];\n\n while (start < end && mMission.running) {\n int len = ipt.read(buf, 0, 512);\n\n if (len == -1) {\n break;\n } else {\n start += len;\n total += len;\n f.write(buf, 0, len);\n notifyProgress(len);\n }\n }\n\n if (DEBUG && mMission.running) {\n Log.d(TAG, mId + \":position \" + position + \" finished, total length \" + total);\n }\n\n f.close();\n ipt.close();\n\n \/\/ TODO We should save progress for each thread\n } catch (Exception e) {\n \/\/ TODO Retry count limit & notify error\n retry = true;\n\n notifyProgress(-total);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" retrying\", e);\n }\n }\n }\n\n if (DEBUG) {\n Log.d(TAG, \"thread \" + mId + \" exited main loop\");\n }\n\n if (mMission.errCode == -1 && mMission.running) {\n if (DEBUG) {\n Log.d(TAG, \"no error has happened, notifying\");\n }\n notifyFinished();\n }\n\n if (DEBUG && !mMission.running) {\n Log.d(TAG, \"The mission has been paused. Passing.\");\n }\n }\n\n private void notifyProgress(final long len) {\n synchronized (mMission) {\n mMission.notifyProgress(len);\n }\n }\n\n private void notifyError(final int err) {\n synchronized (mMission) {\n mMission.notifyError(err);\n mMission.pause();\n }\n }\n\n private void notifyFinished() {\n synchronized (mMission) {\n mMission.notifyFinished();\n }\n }\n}\n\n\nCode-B:\npackage us.shandian.giga.get;\n\nimport android.util.Log;\n\nimport java.io.RandomAccessFile;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\n\nimport static org.schabi.newpipe.BuildConfig.DEBUG;\n\n\/**\n * Runnable to download blocks of a file until the file is completely downloaded,\n * an error occurs or the process is stopped.\n *\/\npublic class DownloadRunnable implements Runnable {\n private static final String TAG = DownloadRunnable.class.getSimpleName();\n\n private final DownloadMission mMission;\n private final int mId;\n\n public DownloadRunnable(DownloadMission mission, int id) {\n if (mission == null) throw new NullPointerException(\"mission is null\");\n mMission = mission;\n mId = id;\n }\n\n @Override\n public void run() {\n boolean retry = mMission.recovered;\n long position = mMission.getPosition(mId);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":default pos \" + position);\n Log.d(TAG, mId + \":recovered: \" + mMission.recovered);\n }\n\n while (mMission.errCode == -1 && mMission.running && position < mMission.blocks) {\n\n if (Thread.currentThread().isInterrupted()) {\n mMission.pause();\n return;\n }\n\n if (DEBUG && retry) {\n Log.d(TAG, mId + \":retry is true. Resuming at \" + position);\n }\n\n \/\/ Wait for an unblocked position\n while (!retry && position < mMission.blocks && mMission.isBlockPreserved(position)) {\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" preserved, passing\");\n }\n\n position++;\n }\n\n retry = false;\n\n if (position >= mMission.blocks) {\n break;\n }\n\n if (DEBUG) {\n Log.d(TAG, mId + \":preserving position \" + position);\n }\n\n mMission.preserveBlock(position);\n mMission.setPosition(mId, position);\n\n long start = position * DownloadManager.BLOCK_SIZE;\n long end = start + DownloadManager.BLOCK_SIZE - 1;\n\n if (end >= mMission.length) {\n end = mMission.length - 1;\n }\n\n HttpURLConnection conn = null;\n\n int total = 0;\n\n try {\n URL url = new URL(mMission.url);\n conn = (HttpURLConnection) url.openConnection();\n conn.setRequestProperty(\"Range\", \"bytes=\" + start + \"-\" + end);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":\" + conn.getRequestProperty(\"Range\"));\n Log.d(TAG, mId + \":Content-Length=\" + conn.getContentLength() + \" Code:\" + conn.getResponseCode());\n }\n\n \/\/ A server may be ignoring the range request\n if (conn.getResponseCode() != 206) {\n mMission.errCode = DownloadMission.ERROR_SERVER_UNSUPPORTED;\n notifyError(DownloadMission.ERROR_SERVER_UNSUPPORTED);\n\n if (DEBUG) {\n Log.e(TAG, mId + \":Unsupported \" + conn.getResponseCode());\n }\n\n break;\n }\n\n RandomAccessFile f = new RandomAccessFile(mMission.location + \"\/\" + mMission.name, \"rw\");\n f.seek(start);\n java.io.InputStream ipt = conn.getInputStream();\n byte[] buf = new byte[64*1024];\n\n while (start < end && mMission.running) {\n int len = ipt.read(buf, 0, buf.length);\n\n if (len == -1) {\n break;\n } else {\n start += len;\n total += len;\n f.write(buf, 0, len);\n notifyProgress(len);\n }\n }\n\n if (DEBUG && mMission.running) {\n Log.d(TAG, mId + \":position \" + position + \" finished, total length \" + total);\n }\n\n f.close();\n ipt.close();\n\n \/\/ TODO We should save progress for each thread\n } catch (Exception e) {\n \/\/ TODO Retry count limit & notify error\n retry = true;\n\n notifyProgress(-total);\n\n if (DEBUG) {\n Log.d(TAG, mId + \":position \" + position + \" retrying\", e);\n }\n }\n }\n\n if (DEBUG) {\n Log.d(TAG, \"thread \" + mId + \" exited main loop\");\n }\n\n if (mMission.errCode == -1 && mMission.running) {\n if (DEBUG) {\n Log.d(TAG, \"no error has happened, notifying\");\n }\n notifyFinished();\n }\n\n if (DEBUG && !mMission.running) {\n Log.d(TAG, \"The mission has been paused. Passing.\");\n }\n }\n\n private void notifyProgress(final long len) {\n synchronized (mMission) {\n mMission.notifyProgress(len);\n }\n }\n\n private void notifyError(final int err) {\n synchronized (mMission) {\n mMission.notifyError(err);\n mMission.pause();\n }\n }\n\n private void notifyFinished() {\n synchronized (mMission) {\n mMission.notifyFinished();\n }\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/vaginessa\/TestBrowser-Lightning\/commit\/e92ad4303bcdcc9364496b0cbff0b7fd22e4eb41","commit_message":"'\\\\\"Make history deletion more efficient\\\\n\\\\\"'","source_code":"\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void delete(String url) {\n\t\tString n = getHistoryItem(url);\n\t\tif (n != null) {\n\t\t\tdeleteHistoryItem(n);\n\t\t}\n\t}\n\n\tpublic synchronized void visitHistoryItem(String url, String title) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tint n = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t\tn++;\n\t\t\t} while (cursor.moveToPrevious() && n < 5);\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Deleting single item\n\tpublic synchronized void deleteHistoryItem(String id) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_ID + \" = ?\", new String[] { String.valueOf(id) });\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n","target_code":"\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void deleteHistoryItem(String url) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t}\n\n\tpublic synchronized void visitHistoryItem(String url, String title) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tint n = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t\tn++;\n\t\t\t} while (cursor.moveToPrevious() && n < 5);\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void delete(String url) {\n\t\tString n = getHistoryItem(url);\n\t\tif (n != null) {\n\t\t\tdeleteHistoryItem(n);\n\t\t}\n\t}\n\n\tpublic synchronized void visitHistoryItem(String url, String title) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tint n = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t\tn++;\n\t\t\t} while (cursor.moveToPrevious() && n < 5);\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Deleting single item\n\tpublic synchronized void deleteHistoryItem(String id) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_ID + \" = ?\", new String[] { String.valueOf(id) });\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void delete(String url) {\n\t\tString n = getHistoryItem(url);\n\t\tif (n != null) {\n\t\t\tdeleteHistoryItem(n);\n\t\t}\n\t}\n\n\tpublic synchronized void visitHistoryItem(String url, String title) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tint n = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t\tn++;\n\t\t\t} while (cursor.moveToPrevious() && n < 5);\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Deleting single item\n\tpublic synchronized void deleteHistoryItem(String id) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_ID + \" = ?\", new String[] { String.valueOf(id) });\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void delete(String url) {\n\t\tString n = getHistoryItem(url);\n\t\tif (n != null) {\n\t\t\tdeleteHistoryItem(n);\n\t\t}\n\t}\n\n\tpublic synchronized void visitHistoryItem(String url, String title) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tint n = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t\tn++;\n\t\t\t} while (cursor.moveToPrevious() && n < 5);\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Deleting single item\n\tpublic synchronized void deleteHistoryItem(String id) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_ID + \" = ?\", new String[] { String.valueOf(id) });\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite history deletion code to improve execution time. Write the entire code and no other text in the response.\n\n### Concepts:\n[-] delete(String url) function\n[-] deleteHistoryItem(String id) function\n[implement] deleteHistoryItem(String url) function\n\n### Given program:\n```java\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void delete(String url) {\n\t\tString n = getHistoryItem(url);\n\t\tif (n != null) {\n\t\t\tdeleteHistoryItem(n);\n\t\t}\n\t}\n\n\tpublic synchronized void visitHistoryItem(String url, String title) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tint n = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t\tn++;\n\t\t\t} while (cursor.moveToPrevious() && n < 5);\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Deleting single item\n\tpublic synchronized void deleteHistoryItem(String id) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_ID + \" = ?\", new String[] { String.valueOf(id) });\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage org.schabi.newpipe.info_list.holder;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.text.util.Linkify;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\n\nimport org.schabi.newpipe.R;\nimport org.schabi.newpipe.extractor.InfoItem;\nimport org.schabi.newpipe.extractor.comments.CommentsInfoItem;\nimport org.schabi.newpipe.info_list.InfoItemBuilder;\nimport org.schabi.newpipe.report.ErrorActivity;\nimport org.schabi.newpipe.util.CommentTextOnTouchListener;\nimport org.schabi.newpipe.util.ImageDisplayConstants;\nimport org.schabi.newpipe.util.NavigationHelper;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport de.hdodenhof.circleimageview.CircleImageView;\n\npublic class CommentsMiniInfoItemHolder extends InfoItemHolder {\n public final CircleImageView itemThumbnailView;\n private final TextView itemContentView;\n private final TextView itemLikesCountView;\n private final TextView itemDislikesCountView;\n private final TextView itemPublishedTime;\n\n private static final int commentDefaultLines = 2;\n private static final int commentExpandedLines = 1000;\n\n private String commentText;\n private String streamUrl;\n\n private static final Pattern pattern = Pattern.compile(\"(\\\\d+:)?(\\\\d+)?:(\\\\d+)\");\n\n private final Linkify.TransformFilter timestampLink = new Linkify.TransformFilter() {\n @Override\n public String transformUrl(Matcher match, String url) {\n int timestamp = 0;\n String hours = match.group(1);\n String minutes = match.group(2);\n String seconds = match.group(3);\n if(hours != null) timestamp += (Integer.parseInt(hours.replace(\":\", \"\"))*3600);\n if(minutes != null) timestamp += (Integer.parseInt(minutes.replace(\":\", \"\"))*60);\n if(seconds != null) timestamp += (Integer.parseInt(seconds));\n return streamUrl + url.replace(match.group(0), \"#timestamp=\" + String.valueOf(timestamp));\n }\n };\n\n CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, int layoutId, ViewGroup parent) {\n super(infoItemBuilder, layoutId, parent);\n\n itemThumbnailView = itemView.findViewById(R.id.itemThumbnailView);\n itemLikesCountView = itemView.findViewById(R.id.detail_thumbs_up_count_view);\n itemDislikesCountView = itemView.findViewById(R.id.detail_thumbs_down_count_view);\n itemPublishedTime = itemView.findViewById(R.id.itemPublishedTime);\n itemContentView = itemView.findViewById(R.id.itemCommentContentView);\n }\n\n public CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, ViewGroup parent) {\n this(infoItemBuilder, R.layout.list_comments_mini_item, parent);\n }\n\n @Override\n public void updateFromItem(final InfoItem infoItem) {\n if (!(infoItem instanceof CommentsInfoItem)) return;\n final CommentsInfoItem item = (CommentsInfoItem) infoItem;\n\n itemBuilder.getImageLoader()\n .displayImage(item.getAuthorThumbnail(),\n itemThumbnailView,\n ImageDisplayConstants.DISPLAY_THUMBNAIL_OPTIONS);\n\n itemThumbnailView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n try {\n final AppCompatActivity activity = (AppCompatActivity) itemBuilder.getContext();\n NavigationHelper.openChannelFragment(\n activity.getSupportFragmentManager(),\n item.getServiceId(),\n item.getAuthorEndpoint(),\n item.getAuthorName());\n } catch (Exception e) {\n ErrorActivity.reportUiError((AppCompatActivity) itemBuilder.getContext(), e);\n }\n }\n });\n\n streamUrl = item.getUrl();\n\n itemContentView.setLines(commentDefaultLines);\n commentText = item.getCommentText();\n itemContentView.setText(commentText);\n itemContentView.setOnTouchListener(CommentTextOnTouchListener.INSTANCE);\n\n if (itemContentView.getLineCount() == 0) {\n itemContentView.post(() -> ellipsize());\n } else {\n ellipsize();\n }\n\n if (null != item.getLikeCount()) {\n itemLikesCountView.setText(String.valueOf(item.getLikeCount()));\n }\n itemPublishedTime.setText(item.getPublishedTime());\n\n itemView.setOnClickListener(view -> {\n toggleEllipsize();\n if (itemBuilder.getOnCommentsSelectedListener() != null) {\n itemBuilder.getOnCommentsSelectedListener().selected(item);\n }\n });\n }\n\n private void ellipsize() {\n if (itemContentView.getLineCount() > commentDefaultLines){\n int endOfLastLine = itemContentView.getLayout().getLineEnd(commentDefaultLines - 1);\n int end = itemContentView.getText().toString().lastIndexOf(' ', endOfLastLine -3);\n if(end == -1) end = Math.max(endOfLastLine -3, 0);\n String newVal = itemContentView.getText().subSequence(0, end) + \"...\";\n itemContentView.setText(newVal);\n }\n linkify();\n }\n\n private void toggleEllipsize() {\n if (itemContentView.getText().toString().equals(commentText)) {\n if (itemContentView.getLineCount() > commentDefaultLines) ellipsize();\n } else {\n expand();\n }\n }\n\n private void expand() {\n itemContentView.setMaxLines(commentExpandedLines);\n itemContentView.setText(commentText);\n linkify();\n }\n\n private void linkify(){\n Linkify.addLinks(itemContentView, Linkify.WEB_URLS);\n Linkify.addLinks(itemContentView, pattern, null, null, timestampLink);\n itemContentView.setMovementMethod(null);\n }\n}\n\n\nCode-B:\npackage org.schabi.newpipe.info_list.holder;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.text.util.Linkify;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\n\nimport org.schabi.newpipe.R;\nimport org.schabi.newpipe.extractor.InfoItem;\nimport org.schabi.newpipe.extractor.comments.CommentsInfoItem;\nimport org.schabi.newpipe.info_list.InfoItemBuilder;\nimport org.schabi.newpipe.report.ErrorActivity;\nimport org.schabi.newpipe.util.CommentTextOnTouchListener;\nimport org.schabi.newpipe.util.ImageDisplayConstants;\nimport org.schabi.newpipe.util.NavigationHelper;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport de.hdodenhof.circleimageview.CircleImageView;\n\npublic class CommentsMiniInfoItemHolder extends InfoItemHolder {\n public final CircleImageView itemThumbnailView;\n private final TextView itemContentView;\n private final TextView itemLikesCountView;\n private final TextView itemDislikesCountView;\n private final TextView itemPublishedTime;\n\n private static final int commentDefaultLines = 2;\n private static final int commentExpandedLines = 1000;\n\n private String commentText;\n private String streamUrl;\n\n private static final Pattern pattern = Pattern.compile(\"(\\\\d+:)?(\\\\d+)?:(\\\\d+)\");\n\n private final Linkify.TransformFilter timestampLink = new Linkify.TransformFilter() {\n @Override\n public String transformUrl(Matcher match, String url) {\n int timestamp = 0;\n String hours = match.group(1);\n String minutes = match.group(2);\n String seconds = match.group(3);\n if(hours != null) timestamp += (Integer.parseInt(hours.replace(\":\", \"\"))*3600);\n if(minutes != null) timestamp += (Integer.parseInt(minutes.replace(\":\", \"\"))*60);\n if(seconds != null) timestamp += (Integer.parseInt(seconds));\n return streamUrl + url.replace(match.group(0), \"#timestamp=\" + String.valueOf(timestamp));\n }\n };\n\n CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, int layoutId, ViewGroup parent) {\n super(infoItemBuilder, layoutId, parent);\n\n itemThumbnailView = itemView.findViewById(R.id.itemThumbnailView);\n itemLikesCountView = itemView.findViewById(R.id.detail_thumbs_up_count_view);\n itemDislikesCountView = itemView.findViewById(R.id.detail_thumbs_down_count_view);\n itemPublishedTime = itemView.findViewById(R.id.itemPublishedTime);\n itemContentView = itemView.findViewById(R.id.itemCommentContentView);\n }\n\n public CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, ViewGroup parent) {\n this(infoItemBuilder, R.layout.list_comments_mini_item, parent);\n }\n\n @Override\n public void updateFromItem(final InfoItem infoItem) {\n if (!(infoItem instanceof CommentsInfoItem)) return;\n final CommentsInfoItem item = (CommentsInfoItem) infoItem;\n\n itemBuilder.getImageLoader()\n .displayImage(item.getAuthorThumbnail(),\n itemThumbnailView,\n ImageDisplayConstants.DISPLAY_THUMBNAIL_OPTIONS);\n\n itemThumbnailView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n try {\n final AppCompatActivity activity = (AppCompatActivity) itemBuilder.getContext();\n NavigationHelper.openChannelFragment(\n activity.getSupportFragmentManager(),\n item.getServiceId(),\n item.getAuthorEndpoint(),\n item.getAuthorName());\n } catch (Exception e) {\n ErrorActivity.reportUiError((AppCompatActivity) itemBuilder.getContext(), e);\n }\n }\n });\n\n streamUrl = item.getUrl();\n\n itemContentView.setMaxLines(commentDefaultLines);\n commentText = item.getCommentText();\n itemContentView.setText(commentText);\n linkify();\n itemContentView.setOnTouchListener(CommentTextOnTouchListener.INSTANCE);\n\n if(itemContentView.getLineCount() == 0){\n itemContentView.post(() -> ellipsize());\n }else{\n ellipsize();\n }\n\n if (null != item.getLikeCount()) {\n itemLikesCountView.setText(String.valueOf(item.getLikeCount()));\n }\n itemPublishedTime.setText(item.getPublishedTime());\n\n itemView.setOnClickListener(view -> {\n toggleEllipsize();\n if (itemBuilder.getOnCommentsSelectedListener() != null) {\n itemBuilder.getOnCommentsSelectedListener().selected(item);\n }\n });\n }\n\n private void ellipsize() {\n if (itemContentView.getLineCount() > commentDefaultLines){\n int endOfLastLine = itemContentView.getLayout().getLineEnd(commentDefaultLines - 1);\n String newVal = itemContentView.getText().subSequence(0, endOfLastLine - 3) + \"...\";\n itemContentView.setText(newVal);\n linkify();\n }\n }\n\n private void toggleEllipsize() {\n if (itemContentView.getText().toString().equals(commentText)) {\n ellipsize();\n } else {\n expand();\n }\n }\n\n private void expand() {\n itemContentView.setMaxLines(commentExpandedLines);\n itemContentView.setText(commentText);\n linkify();\n }\n\n private void linkify(){\n Linkify.addLinks(itemContentView, Linkify.WEB_URLS);\n Linkify.addLinks(itemContentView, pattern, null, null, timestampLink);\n itemContentView.setMovementMethod(null);\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage org.schabi.newpipe.info_list.holder;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.text.util.Linkify;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\n\nimport org.schabi.newpipe.R;\nimport org.schabi.newpipe.extractor.InfoItem;\nimport org.schabi.newpipe.extractor.comments.CommentsInfoItem;\nimport org.schabi.newpipe.info_list.InfoItemBuilder;\nimport org.schabi.newpipe.report.ErrorActivity;\nimport org.schabi.newpipe.util.CommentTextOnTouchListener;\nimport org.schabi.newpipe.util.ImageDisplayConstants;\nimport org.schabi.newpipe.util.NavigationHelper;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport de.hdodenhof.circleimageview.CircleImageView;\n\npublic class CommentsMiniInfoItemHolder extends InfoItemHolder {\n public final CircleImageView itemThumbnailView;\n private final TextView itemContentView;\n private final TextView itemLikesCountView;\n private final TextView itemDislikesCountView;\n private final TextView itemPublishedTime;\n\n private static final int commentDefaultLines = 2;\n private static final int commentExpandedLines = 1000;\n\n private String commentText;\n private String streamUrl;\n\n private static final Pattern pattern = Pattern.compile(\"(\\\\d+:)?(\\\\d+)?:(\\\\d+)\");\n\n private final Linkify.TransformFilter timestampLink = new Linkify.TransformFilter() {\n @Override\n public String transformUrl(Matcher match, String url) {\n int timestamp = 0;\n String hours = match.group(1);\n String minutes = match.group(2);\n String seconds = match.group(3);\n if(hours != null) timestamp += (Integer.parseInt(hours.replace(\":\", \"\"))*3600);\n if(minutes != null) timestamp += (Integer.parseInt(minutes.replace(\":\", \"\"))*60);\n if(seconds != null) timestamp += (Integer.parseInt(seconds));\n return streamUrl + url.replace(match.group(0), \"#timestamp=\" + String.valueOf(timestamp));\n }\n };\n\n CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, int layoutId, ViewGroup parent) {\n super(infoItemBuilder, layoutId, parent);\n\n itemThumbnailView = itemView.findViewById(R.id.itemThumbnailView);\n itemLikesCountView = itemView.findViewById(R.id.detail_thumbs_up_count_view);\n itemDislikesCountView = itemView.findViewById(R.id.detail_thumbs_down_count_view);\n itemPublishedTime = itemView.findViewById(R.id.itemPublishedTime);\n itemContentView = itemView.findViewById(R.id.itemCommentContentView);\n }\n\n public CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, ViewGroup parent) {\n this(infoItemBuilder, R.layout.list_comments_mini_item, parent);\n }\n\n @Override\n public void updateFromItem(final InfoItem infoItem) {\n if (!(infoItem instanceof CommentsInfoItem)) return;\n final CommentsInfoItem item = (CommentsInfoItem) infoItem;\n\n itemBuilder.getImageLoader()\n .displayImage(item.getAuthorThumbnail(),\n itemThumbnailView,\n ImageDisplayConstants.DISPLAY_THUMBNAIL_OPTIONS);\n\n itemThumbnailView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n try {\n final AppCompatActivity activity = (AppCompatActivity) itemBuilder.getContext();\n NavigationHelper.openChannelFragment(\n activity.getSupportFragmentManager(),\n item.getServiceId(),\n item.getAuthorEndpoint(),\n item.getAuthorName());\n } catch (Exception e) {\n ErrorActivity.reportUiError((AppCompatActivity) itemBuilder.getContext(), e);\n }\n }\n });\n\n streamUrl = item.getUrl();\n\n itemContentView.setMaxLines(commentDefaultLines);\n commentText = item.getCommentText();\n itemContentView.setText(commentText);\n linkify();\n itemContentView.setOnTouchListener(CommentTextOnTouchListener.INSTANCE);\n\n if(itemContentView.getLineCount() == 0){\n itemContentView.post(() -> ellipsize());\n }else{\n ellipsize();\n }\n\n if (null != item.getLikeCount()) {\n itemLikesCountView.setText(String.valueOf(item.getLikeCount()));\n }\n itemPublishedTime.setText(item.getPublishedTime());\n\n itemView.setOnClickListener(view -> {\n toggleEllipsize();\n if (itemBuilder.getOnCommentsSelectedListener() != null) {\n itemBuilder.getOnCommentsSelectedListener().selected(item);\n }\n });\n }\n\n private void ellipsize() {\n if (itemContentView.getLineCount() > commentDefaultLines){\n int endOfLastLine = itemContentView.getLayout().getLineEnd(commentDefaultLines - 1);\n String newVal = itemContentView.getText().subSequence(0, endOfLastLine - 3) + \"...\";\n itemContentView.setText(newVal);\n linkify();\n }\n }\n\n private void toggleEllipsize() {\n if (itemContentView.getText().toString().equals(commentText)) {\n ellipsize();\n } else {\n expand();\n }\n }\n\n private void expand() {\n itemContentView.setMaxLines(commentExpandedLines);\n itemContentView.setText(commentText);\n linkify();\n }\n\n private void linkify(){\n Linkify.addLinks(itemContentView, Linkify.WEB_URLS);\n Linkify.addLinks(itemContentView, pattern, null, null, timestampLink);\n itemContentView.setMovementMethod(null);\n }\n}\n\n\nCode-B:\npackage org.schabi.newpipe.info_list.holder;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.text.util.Linkify;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\n\nimport org.schabi.newpipe.R;\nimport org.schabi.newpipe.extractor.InfoItem;\nimport org.schabi.newpipe.extractor.comments.CommentsInfoItem;\nimport org.schabi.newpipe.info_list.InfoItemBuilder;\nimport org.schabi.newpipe.report.ErrorActivity;\nimport org.schabi.newpipe.util.CommentTextOnTouchListener;\nimport org.schabi.newpipe.util.ImageDisplayConstants;\nimport org.schabi.newpipe.util.NavigationHelper;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport de.hdodenhof.circleimageview.CircleImageView;\n\npublic class CommentsMiniInfoItemHolder extends InfoItemHolder {\n public final CircleImageView itemThumbnailView;\n private final TextView itemContentView;\n private final TextView itemLikesCountView;\n private final TextView itemDislikesCountView;\n private final TextView itemPublishedTime;\n\n private static final int commentDefaultLines = 2;\n private static final int commentExpandedLines = 1000;\n\n private String commentText;\n private String streamUrl;\n\n private static final Pattern pattern = Pattern.compile(\"(\\\\d+:)?(\\\\d+)?:(\\\\d+)\");\n\n private final Linkify.TransformFilter timestampLink = new Linkify.TransformFilter() {\n @Override\n public String transformUrl(Matcher match, String url) {\n int timestamp = 0;\n String hours = match.group(1);\n String minutes = match.group(2);\n String seconds = match.group(3);\n if(hours != null) timestamp += (Integer.parseInt(hours.replace(\":\", \"\"))*3600);\n if(minutes != null) timestamp += (Integer.parseInt(minutes.replace(\":\", \"\"))*60);\n if(seconds != null) timestamp += (Integer.parseInt(seconds));\n return streamUrl + url.replace(match.group(0), \"#timestamp=\" + String.valueOf(timestamp));\n }\n };\n\n CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, int layoutId, ViewGroup parent) {\n super(infoItemBuilder, layoutId, parent);\n\n itemThumbnailView = itemView.findViewById(R.id.itemThumbnailView);\n itemLikesCountView = itemView.findViewById(R.id.detail_thumbs_up_count_view);\n itemDislikesCountView = itemView.findViewById(R.id.detail_thumbs_down_count_view);\n itemPublishedTime = itemView.findViewById(R.id.itemPublishedTime);\n itemContentView = itemView.findViewById(R.id.itemCommentContentView);\n }\n\n public CommentsMiniInfoItemHolder(InfoItemBuilder infoItemBuilder, ViewGroup parent) {\n this(infoItemBuilder, R.layout.list_comments_mini_item, parent);\n }\n\n @Override\n public void updateFromItem(final InfoItem infoItem) {\n if (!(infoItem instanceof CommentsInfoItem)) return;\n final CommentsInfoItem item = (CommentsInfoItem) infoItem;\n\n itemBuilder.getImageLoader()\n .displayImage(item.getAuthorThumbnail(),\n itemThumbnailView,\n ImageDisplayConstants.DISPLAY_THUMBNAIL_OPTIONS);\n\n itemThumbnailView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n try {\n final AppCompatActivity activity = (AppCompatActivity) itemBuilder.getContext();\n NavigationHelper.openChannelFragment(\n activity.getSupportFragmentManager(),\n item.getServiceId(),\n item.getAuthorEndpoint(),\n item.getAuthorName());\n } catch (Exception e) {\n ErrorActivity.reportUiError((AppCompatActivity) itemBuilder.getContext(), e);\n }\n }\n });\n\n streamUrl = item.getUrl();\n\n itemContentView.setLines(commentDefaultLines);\n commentText = item.getCommentText();\n itemContentView.setText(commentText);\n itemContentView.setOnTouchListener(CommentTextOnTouchListener.INSTANCE);\n\n if (itemContentView.getLineCount() == 0) {\n itemContentView.post(() -> ellipsize());\n } else {\n ellipsize();\n }\n\n if (null != item.getLikeCount()) {\n itemLikesCountView.setText(String.valueOf(item.getLikeCount()));\n }\n itemPublishedTime.setText(item.getPublishedTime());\n\n itemView.setOnClickListener(view -> {\n toggleEllipsize();\n if (itemBuilder.getOnCommentsSelectedListener() != null) {\n itemBuilder.getOnCommentsSelectedListener().selected(item);\n }\n });\n }\n\n private void ellipsize() {\n if (itemContentView.getLineCount() > commentDefaultLines){\n int endOfLastLine = itemContentView.getLayout().getLineEnd(commentDefaultLines - 1);\n int end = itemContentView.getText().toString().lastIndexOf(' ', endOfLastLine -3);\n if(end == -1) end = Math.max(endOfLastLine -3, 0);\n String newVal = itemContentView.getText().subSequence(0, end) + \"...\";\n itemContentView.setText(newVal);\n }\n linkify();\n }\n\n private void toggleEllipsize() {\n if (itemContentView.getText().toString().equals(commentText)) {\n if (itemContentView.getLineCount() > commentDefaultLines) ellipsize();\n } else {\n expand();\n }\n }\n\n private void expand() {\n itemContentView.setMaxLines(commentExpandedLines);\n itemContentView.setText(commentText);\n linkify();\n }\n\n private void linkify(){\n Linkify.addLinks(itemContentView, Linkify.WEB_URLS);\n Linkify.addLinks(itemContentView, pattern, null, null, timestampLink);\n itemContentView.setMovementMethod(null);\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/erikusaj\/fdroidTvClient\/commit\/19583c2b75224bf60ebfe65ff86c1d061b20f855","commit_message":"'\\\\\"Slightly optimise greyed out apk\/app views\\\\n\\\\\"'","source_code":"package org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.compat.LayoutCompat;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n\n boolean compact = Preferences.get().hasCompactLayout();\n DB.App app = items.get(position);\n\n if (convertView == null) {\n convertView = ((LayoutInflater) mContext.getSystemService(\n Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.applistitem, null);\n }\n\n TextView name = (TextView) convertView.findViewById(R.id.name);\n TextView summary = (TextView) convertView.findViewById(R.id.summary);\n TextView status = (TextView) convertView.findViewById(R.id.status);\n TextView license = (TextView) convertView.findViewById(R.id.license);\n ImageView icon = (ImageView) convertView.findViewById(R.id.icon);\n LinearLayout iconContainer = (LinearLayout)convertView.findViewById(R.id.status_icons);\n ImageView iconInstalled = (ImageView) convertView.findViewById(R.id.icon_status_installed);\n ImageView iconUpdates = (ImageView) convertView.findViewById(R.id.icon_status_has_updates);\n\n name.setText(app.name);\n summary.setText(app.summary);\n\n layoutSummary(summary);\n layoutIcon(icon, app);\n\n int visibleOnCompact = compact ? View.VISIBLE : View.GONE;\n int notVisibleOnCompact = compact ? View.GONE : View.VISIBLE;\n\n iconContainer.setVisibility(visibleOnCompact);\n status.setVisibility(notVisibleOnCompact);\n license.setVisibility(notVisibleOnCompact);\n\n if (!compact) {\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n } else {\n status.setText(\"\");\n license.setText(\"\");\n\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setVisibility(View.VISIBLE);\n } else {\n iconUpdates.setVisibility(View.GONE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setVisibility(View.VISIBLE);\n } else {\n iconInstalled.setVisibility(View.GONE);\n }\n }\n\n \/\/ Disable it all if it isn't compatible...\n View[] views = { convertView, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(app.compatible);\n }\n\n return convertView;\n }\n\n \/**\n * If an icon exists on disc, we'll use that, otherwise default to the\n * plain android app icon.\n *\/\n private void layoutIcon(ImageView iconView, DB.App app) {\n\n File icn = new File(DB.getIconsPath(mContext), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n iconView.setImageURI(Uri.parse(icn.getPath()));\n } else {\n iconView.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n }\n\n \/**\n * In compact view, the summary sites next to the icon, below the name.\n * In non-compact view, it sits under the icon, with some padding pushing\n * it away from the left margin.\n *\/\n private void layoutSummary(TextView summaryView) {\n\n if (Preferences.get().hasCompactLayout()) {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(LayoutCompat.RelativeLayout.END_OF, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n summaryView.setPadding(0,0,0,0);\n\n } else {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.MATCH_PARENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n float padding = mContext.getResources().getDimension(R.dimen.applist_summary_padding);\n summaryView.setPadding((int)padding, 0, 0, 0);\n\n }\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n","target_code":"package org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.compat.LayoutCompat;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n\n boolean compact = Preferences.get().hasCompactLayout();\n DB.App app = items.get(position);\n\n if (convertView == null) {\n convertView = ((LayoutInflater) mContext.getSystemService(\n Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.applistitem, null);\n }\n\n TextView name = (TextView) convertView.findViewById(R.id.name);\n TextView summary = (TextView) convertView.findViewById(R.id.summary);\n TextView status = (TextView) convertView.findViewById(R.id.status);\n TextView license = (TextView) convertView.findViewById(R.id.license);\n ImageView icon = (ImageView) convertView.findViewById(R.id.icon);\n LinearLayout iconContainer = (LinearLayout)convertView.findViewById(R.id.status_icons);\n ImageView iconInstalled = (ImageView) convertView.findViewById(R.id.icon_status_installed);\n ImageView iconUpdates = (ImageView) convertView.findViewById(R.id.icon_status_has_updates);\n\n name.setText(app.name);\n summary.setText(app.summary);\n\n layoutSummary(summary);\n layoutIcon(icon, app);\n\n int visibleOnCompact = compact ? View.VISIBLE : View.GONE;\n int notVisibleOnCompact = compact ? View.GONE : View.VISIBLE;\n\n iconContainer.setVisibility(visibleOnCompact);\n status.setVisibility(notVisibleOnCompact);\n license.setVisibility(notVisibleOnCompact);\n\n if (!compact) {\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n } else {\n status.setText(\"\");\n license.setText(\"\");\n\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setVisibility(View.VISIBLE);\n } else {\n iconUpdates.setVisibility(View.GONE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setVisibility(View.VISIBLE);\n } else {\n iconInstalled.setVisibility(View.GONE);\n }\n }\n\n \/\/ Disable it all if it isn't compatible...\n if (!app.compatible) {\n View[] views = { convertView, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(false);\n }\n }\n\n return convertView;\n }\n\n \/**\n * If an icon exists on disc, we'll use that, otherwise default to the\n * plain android app icon.\n *\/\n private void layoutIcon(ImageView iconView, DB.App app) {\n\n File icn = new File(DB.getIconsPath(mContext), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n iconView.setImageURI(Uri.parse(icn.getPath()));\n } else {\n iconView.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n }\n\n \/**\n * In compact view, the summary sites next to the icon, below the name.\n * In non-compact view, it sits under the icon, with some padding pushing\n * it away from the left margin.\n *\/\n private void layoutSummary(TextView summaryView) {\n\n if (Preferences.get().hasCompactLayout()) {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(LayoutCompat.RelativeLayout.END_OF, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n summaryView.setPadding(0,0,0,0);\n\n } else {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.MATCH_PARENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n float padding = mContext.getResources().getDimension(R.dimen.applist_summary_padding);\n summaryView.setPadding((int)padding, 0, 0, 0);\n\n }\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.compat.LayoutCompat;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n\n boolean compact = Preferences.get().hasCompactLayout();\n DB.App app = items.get(position);\n\n if (convertView == null) {\n convertView = ((LayoutInflater) mContext.getSystemService(\n Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.applistitem, null);\n }\n\n TextView name = (TextView) convertView.findViewById(R.id.name);\n TextView summary = (TextView) convertView.findViewById(R.id.summary);\n TextView status = (TextView) convertView.findViewById(R.id.status);\n TextView license = (TextView) convertView.findViewById(R.id.license);\n ImageView icon = (ImageView) convertView.findViewById(R.id.icon);\n LinearLayout iconContainer = (LinearLayout)convertView.findViewById(R.id.status_icons);\n ImageView iconInstalled = (ImageView) convertView.findViewById(R.id.icon_status_installed);\n ImageView iconUpdates = (ImageView) convertView.findViewById(R.id.icon_status_has_updates);\n\n name.setText(app.name);\n summary.setText(app.summary);\n\n layoutSummary(summary);\n layoutIcon(icon, app);\n\n int visibleOnCompact = compact ? View.VISIBLE : View.GONE;\n int notVisibleOnCompact = compact ? View.GONE : View.VISIBLE;\n\n iconContainer.setVisibility(visibleOnCompact);\n status.setVisibility(notVisibleOnCompact);\n license.setVisibility(notVisibleOnCompact);\n\n if (!compact) {\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n } else {\n status.setText(\"\");\n license.setText(\"\");\n\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setVisibility(View.VISIBLE);\n } else {\n iconUpdates.setVisibility(View.GONE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setVisibility(View.VISIBLE);\n } else {\n iconInstalled.setVisibility(View.GONE);\n }\n }\n\n \/\/ Disable it all if it isn't compatible...\n View[] views = { convertView, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(app.compatible);\n }\n\n return convertView;\n }\n\n \/**\n * If an icon exists on disc, we'll use that, otherwise default to the\n * plain android app icon.\n *\/\n private void layoutIcon(ImageView iconView, DB.App app) {\n\n File icn = new File(DB.getIconsPath(mContext), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n iconView.setImageURI(Uri.parse(icn.getPath()));\n } else {\n iconView.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n }\n\n \/**\n * In compact view, the summary sites next to the icon, below the name.\n * In non-compact view, it sits under the icon, with some padding pushing\n * it away from the left margin.\n *\/\n private void layoutSummary(TextView summaryView) {\n\n if (Preferences.get().hasCompactLayout()) {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(LayoutCompat.RelativeLayout.END_OF, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n summaryView.setPadding(0,0,0,0);\n\n } else {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.MATCH_PARENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n float padding = mContext.getResources().getDimension(R.dimen.applist_summary_padding);\n summaryView.setPadding((int)padding, 0, 0, 0);\n\n }\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.compat.LayoutCompat;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n\n boolean compact = Preferences.get().hasCompactLayout();\n DB.App app = items.get(position);\n\n if (convertView == null) {\n convertView = ((LayoutInflater) mContext.getSystemService(\n Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.applistitem, null);\n }\n\n TextView name = (TextView) convertView.findViewById(R.id.name);\n TextView summary = (TextView) convertView.findViewById(R.id.summary);\n TextView status = (TextView) convertView.findViewById(R.id.status);\n TextView license = (TextView) convertView.findViewById(R.id.license);\n ImageView icon = (ImageView) convertView.findViewById(R.id.icon);\n LinearLayout iconContainer = (LinearLayout)convertView.findViewById(R.id.status_icons);\n ImageView iconInstalled = (ImageView) convertView.findViewById(R.id.icon_status_installed);\n ImageView iconUpdates = (ImageView) convertView.findViewById(R.id.icon_status_has_updates);\n\n name.setText(app.name);\n summary.setText(app.summary);\n\n layoutSummary(summary);\n layoutIcon(icon, app);\n\n int visibleOnCompact = compact ? View.VISIBLE : View.GONE;\n int notVisibleOnCompact = compact ? View.GONE : View.VISIBLE;\n\n iconContainer.setVisibility(visibleOnCompact);\n status.setVisibility(notVisibleOnCompact);\n license.setVisibility(notVisibleOnCompact);\n\n if (!compact) {\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n } else {\n status.setText(\"\");\n license.setText(\"\");\n\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setVisibility(View.VISIBLE);\n } else {\n iconUpdates.setVisibility(View.GONE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setVisibility(View.VISIBLE);\n } else {\n iconInstalled.setVisibility(View.GONE);\n }\n }\n\n \/\/ Disable it all if it isn't compatible...\n View[] views = { convertView, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(app.compatible);\n }\n\n return convertView;\n }\n\n \/**\n * If an icon exists on disc, we'll use that, otherwise default to the\n * plain android app icon.\n *\/\n private void layoutIcon(ImageView iconView, DB.App app) {\n\n File icn = new File(DB.getIconsPath(mContext), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n iconView.setImageURI(Uri.parse(icn.getPath()));\n } else {\n iconView.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n }\n\n \/**\n * In compact view, the summary sites next to the icon, below the name.\n * In non-compact view, it sits under the icon, with some padding pushing\n * it away from the left margin.\n *\/\n private void layoutSummary(TextView summaryView) {\n\n if (Preferences.get().hasCompactLayout()) {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(LayoutCompat.RelativeLayout.END_OF, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n summaryView.setPadding(0,0,0,0);\n\n } else {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.MATCH_PARENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n float padding = mContext.getResources().getDimension(R.dimen.applist_summary_padding);\n summaryView.setPadding((int)padding, 0, 0, 0);\n\n }\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.compat.LayoutCompat;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n\n boolean compact = Preferences.get().hasCompactLayout();\n DB.App app = items.get(position);\n\n if (convertView == null) {\n convertView = ((LayoutInflater) mContext.getSystemService(\n Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.applistitem, null);\n }\n\n TextView name = (TextView) convertView.findViewById(R.id.name);\n TextView summary = (TextView) convertView.findViewById(R.id.summary);\n TextView status = (TextView) convertView.findViewById(R.id.status);\n TextView license = (TextView) convertView.findViewById(R.id.license);\n ImageView icon = (ImageView) convertView.findViewById(R.id.icon);\n LinearLayout iconContainer = (LinearLayout)convertView.findViewById(R.id.status_icons);\n ImageView iconInstalled = (ImageView) convertView.findViewById(R.id.icon_status_installed);\n ImageView iconUpdates = (ImageView) convertView.findViewById(R.id.icon_status_has_updates);\n\n name.setText(app.name);\n summary.setText(app.summary);\n\n layoutSummary(summary);\n layoutIcon(icon, app);\n\n int visibleOnCompact = compact ? View.VISIBLE : View.GONE;\n int notVisibleOnCompact = compact ? View.GONE : View.VISIBLE;\n\n iconContainer.setVisibility(visibleOnCompact);\n status.setVisibility(notVisibleOnCompact);\n license.setVisibility(notVisibleOnCompact);\n\n if (!compact) {\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n } else {\n status.setText(\"\");\n license.setText(\"\");\n\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setVisibility(View.VISIBLE);\n } else {\n iconUpdates.setVisibility(View.GONE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setVisibility(View.VISIBLE);\n } else {\n iconInstalled.setVisibility(View.GONE);\n }\n }\n\n \/\/ Disable it all if it isn't compatible...\n View[] views = { convertView, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(app.compatible);\n }\n\n return convertView;\n }\n\n \/**\n * If an icon exists on disc, we'll use that, otherwise default to the\n * plain android app icon.\n *\/\n private void layoutIcon(ImageView iconView, DB.App app) {\n\n File icn = new File(DB.getIconsPath(mContext), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n iconView.setImageURI(Uri.parse(icn.getPath()));\n } else {\n iconView.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n }\n\n \/**\n * In compact view, the summary sites next to the icon, below the name.\n * In non-compact view, it sits under the icon, with some padding pushing\n * it away from the left margin.\n *\/\n private void layoutSummary(TextView summaryView) {\n\n if (Preferences.get().hasCompactLayout()) {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(LayoutCompat.RelativeLayout.END_OF, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n summaryView.setPadding(0,0,0,0);\n\n } else {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.MATCH_PARENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n float padding = mContext.getResources().getDimension(R.dimen.applist_summary_padding);\n summaryView.setPadding((int)padding, 0, 0, 0);\n\n }\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite code to optimize grayed out apk\/app views for improving performance. Write the entire code and no other text in the response.\n\n### Concepts:\n[in] getView function\n\n### Given program:\n```java\npackage org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.compat.LayoutCompat;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n\n boolean compact = Preferences.get().hasCompactLayout();\n DB.App app = items.get(position);\n\n if (convertView == null) {\n convertView = ((LayoutInflater) mContext.getSystemService(\n Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.applistitem, null);\n }\n\n TextView name = (TextView) convertView.findViewById(R.id.name);\n TextView summary = (TextView) convertView.findViewById(R.id.summary);\n TextView status = (TextView) convertView.findViewById(R.id.status);\n TextView license = (TextView) convertView.findViewById(R.id.license);\n ImageView icon = (ImageView) convertView.findViewById(R.id.icon);\n LinearLayout iconContainer = (LinearLayout)convertView.findViewById(R.id.status_icons);\n ImageView iconInstalled = (ImageView) convertView.findViewById(R.id.icon_status_installed);\n ImageView iconUpdates = (ImageView) convertView.findViewById(R.id.icon_status_has_updates);\n\n name.setText(app.name);\n summary.setText(app.summary);\n\n layoutSummary(summary);\n layoutIcon(icon, app);\n\n int visibleOnCompact = compact ? View.VISIBLE : View.GONE;\n int notVisibleOnCompact = compact ? View.GONE : View.VISIBLE;\n\n iconContainer.setVisibility(visibleOnCompact);\n status.setVisibility(notVisibleOnCompact);\n license.setVisibility(notVisibleOnCompact);\n\n if (!compact) {\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n } else {\n status.setText(\"\");\n license.setText(\"\");\n\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setVisibility(View.VISIBLE);\n } else {\n iconUpdates.setVisibility(View.GONE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setVisibility(View.VISIBLE);\n } else {\n iconInstalled.setVisibility(View.GONE);\n }\n }\n\n \/\/ Disable it all if it isn't compatible...\n View[] views = { convertView, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(app.compatible);\n }\n\n return convertView;\n }\n\n \/**\n * If an icon exists on disc, we'll use that, otherwise default to the\n * plain android app icon.\n *\/\n private void layoutIcon(ImageView iconView, DB.App app) {\n\n File icn = new File(DB.getIconsPath(mContext), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n iconView.setImageURI(Uri.parse(icn.getPath()));\n } else {\n iconView.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n }\n\n \/**\n * In compact view, the summary sites next to the icon, below the name.\n * In non-compact view, it sits under the icon, with some padding pushing\n * it away from the left margin.\n *\/\n private void layoutSummary(TextView summaryView) {\n\n if (Preferences.get().hasCompactLayout()) {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(LayoutCompat.RelativeLayout.END_OF, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n summaryView.setPadding(0,0,0,0);\n\n } else {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.MATCH_PARENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n float padding = mContext.getResources().getDimension(R.dimen.applist_summary_padding);\n summaryView.setPadding((int)padding, 0, 0, 0);\n\n }\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void delete(String url) {\n\t\tString n = getHistoryItem(url);\n\t\tif (n != null) {\n\t\t\tdeleteHistoryItem(n);\n\t\t}\n\t}\n\n\tpublic synchronized void visitHistoryItem(String url, String title) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tint n = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t\tn++;\n\t\t\t} while (cursor.moveToPrevious() && n < 5);\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Deleting single item\n\tpublic synchronized void deleteHistoryItem(String id) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_ID + \" = ?\", new String[] { String.valueOf(id) });\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n\n\nCode-B:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void delete(String url) {\n\t\tString n = getHistoryItem(url);\n\t\tif (n != null) {\n\t\t\tdeleteHistoryItem(n);\n\t\t}\n\t}\n\t\n\tpublic synchronized void visitHistoryItem(String url, String title){\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToPrevious());\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Deleting single item\n\tpublic synchronized void deleteHistoryItem(String id) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_ID + \" = ?\", new String[] { String.valueOf(id) });\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void delete(String url) {\n\t\tString n = getHistoryItem(url);\n\t\tif (n != null) {\n\t\t\tdeleteHistoryItem(n);\n\t\t}\n\t}\n\t\n\tpublic synchronized void visitHistoryItem(String url, String title){\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToPrevious());\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Deleting single item\n\tpublic synchronized void deleteHistoryItem(String id) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_ID + \" = ?\", new String[] { String.valueOf(id) });\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n\n\nCode-B:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void delete(String url) {\n\t\tString n = getHistoryItem(url);\n\t\tif (n != null) {\n\t\t\tdeleteHistoryItem(n);\n\t\t}\n\t}\n\n\tpublic synchronized void visitHistoryItem(String url, String title) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tint n = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t\tn++;\n\t\t\t} while (cursor.moveToPrevious() && n < 5);\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Deleting single item\n\tpublic synchronized void deleteHistoryItem(String id) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_ID + \" = ?\", new String[] { String.valueOf(id) });\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/vaginessa\/TestBrowser-Lightning\/commit\/460da386ec10cb82b97bd2def2724fe41f709a88","commit_message":"'\\\\\"Keeping connectivity manager around rather than getting it every time\\\\n\\\\\"'","source_code":"package acr.browser.lightning.search;\n\nimport android.app.Application;\nimport android.content.Context;\nimport android.net.ConnectivityManager;\nimport android.net.NetworkInfo;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.InputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.net.URLEncoder;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.concurrent.TimeUnit;\nimport java.util.zip.GZIPInputStream;\n\nimport acr.browser.lightning.database.HistoryItem;\nimport acr.browser.lightning.utils.Utils;\nimport okhttp3.CacheControl;\nimport okhttp3.OkHttpClient;\nimport okhttp3.Request;\nimport okhttp3.Response;\n\nabstract class BaseSuggestionsTask {\n\n private static final String TAG = BaseSuggestionsTask.class.getSimpleName();\n\n static final int MAX_RESULTS = 5;\n private static final long INTERVAL_DAY = TimeUnit.DAYS.toMillis(1);\n private static final String DEFAULT_LANGUAGE = \"en\";\n @Nullable private static String sLanguage;\n @NonNull private final SuggestionsResult mResultCallback;\n @NonNull private final Application mApplication;\n @NonNull private final OkHttpClient mHttpClient = new OkHttpClient();\n @NonNull private final CacheControl mCacheControl;\n @NonNull private String mQuery;\n\n @NonNull\n protected abstract String getQueryUrl(@NonNull String query, @NonNull String language);\n\n protected abstract void parseResults(@NonNull FileInputStream inputStream, @NonNull List results) throws Exception;\n\n @NonNull\n protected abstract String getEncoding();\n\n BaseSuggestionsTask(@NonNull String query,\n @NonNull Application application,\n @NonNull SuggestionsResult callback) {\n mQuery = query;\n mResultCallback = callback;\n mApplication = application;\n mCacheControl = new CacheControl.Builder().maxStale(1, TimeUnit.DAYS).build();\n }\n\n @NonNull\n private static synchronized String getLanguage() {\n if (sLanguage == null) {\n sLanguage = Locale.getDefault().getLanguage();\n }\n if (TextUtils.isEmpty(sLanguage)) {\n sLanguage = DEFAULT_LANGUAGE;\n }\n return sLanguage;\n }\n\n void run() {\n List filter = new ArrayList<>(5);\n try {\n mQuery = URLEncoder.encode(mQuery, getEncoding());\n } catch (UnsupportedEncodingException e) {\n Log.e(TAG, \"Unable to encode the URL\", e);\n }\n File cache = downloadSuggestionsForQuery(mQuery, getLanguage(), mApplication);\n if (!cache.exists()) {\n post(filter);\n return;\n }\n FileInputStream fileInput = null;\n try {\n fileInput = new FileInputStream(cache);\n parseResults(fileInput, filter);\n } catch (Exception e) {\n post(filter);\n Log.e(TAG, \"Unable to parse results\", e);\n return;\n } finally {\n Utils.close(fileInput);\n }\n post(filter);\n }\n\n private void post(@NonNull List result) {\n mResultCallback.resultReceived(result);\n }\n\n \/**\n * This method downloads the search suggestions for the specific query.\n * NOTE: This is a blocking operation, do not run on the UI thread.\n *\n * @param query the query to get suggestions for\n * @return the cache file containing the suggestions\n *\/\n @NonNull\n private File downloadSuggestionsForQuery(@NonNull String query, String language, @NonNull Application app) {\n String queryUrl = getQueryUrl(query, language);\n File cacheFile = new File(app.getCacheDir(), queryUrl.hashCode() + SuggestionsAdapter.CACHE_FILE_TYPE);\n if (System.currentTimeMillis() - INTERVAL_DAY < cacheFile.lastModified()) {\n return cacheFile;\n }\n if (!isNetworkConnected(app)) {\n return cacheFile;\n }\n InputStream in = null;\n FileOutputStream fos = null;\n try {\n URL url = new URL(queryUrl);\n Request suggestionsRequest = new Request.Builder().url(url)\n .addHeader(\"Accept-Encoding\", \"gzip\")\n .addHeader(\"Accept-Charset\", getEncoding())\n .cacheControl(mCacheControl)\n .build();\n\n Response suggestionsResponse = mHttpClient.newCall(suggestionsRequest).execute();\n\n if (suggestionsResponse.code() >= HttpURLConnection.HTTP_MULT_CHOICE ||\n suggestionsResponse.code() < HttpURLConnection.HTTP_OK) {\n Log.e(TAG, \"Search API Responded with code: \" + suggestionsResponse.code());\n suggestionsResponse.body().close();\n return cacheFile;\n }\n\n in = suggestionsResponse.body().byteStream();\n\n if (in != null) {\n in = new GZIPInputStream(in);\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n fos = new FileOutputStream(cacheFile);\n int buffer;\n while ((buffer = in.read()) != -1) {\n fos.write(buffer);\n }\n fos.flush();\n }\n suggestionsResponse.body().close();\n cacheFile.setLastModified(System.currentTimeMillis());\n } catch (Exception e) {\n Log.w(TAG, \"Problem getting search suggestions\", e);\n } finally {\n Utils.close(in);\n Utils.close(fos);\n }\n return cacheFile;\n }\n\n private static boolean isNetworkConnected(@NonNull Context context) {\n NetworkInfo networkInfo = getActiveNetworkInfo(context);\n return networkInfo != null && networkInfo.isConnected();\n }\n\n @Nullable\n private static NetworkInfo getActiveNetworkInfo(@NonNull Context context) {\n ConnectivityManager connectivity = (ConnectivityManager) context\n .getApplicationContext()\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n if (connectivity == null) {\n return null;\n }\n return connectivity.getActiveNetworkInfo();\n }\n\n}\n","target_code":"package acr.browser.lightning.search;\n\nimport android.app.Application;\nimport android.content.Context;\nimport android.net.ConnectivityManager;\nimport android.net.NetworkInfo;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.InputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.net.URLEncoder;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.concurrent.TimeUnit;\nimport java.util.zip.GZIPInputStream;\n\nimport acr.browser.lightning.database.HistoryItem;\nimport acr.browser.lightning.utils.Utils;\nimport okhttp3.CacheControl;\nimport okhttp3.OkHttpClient;\nimport okhttp3.Request;\nimport okhttp3.Response;\n\nabstract class BaseSuggestionsTask {\n\n private static final String TAG = BaseSuggestionsTask.class.getSimpleName();\n\n static final int MAX_RESULTS = 5;\n private static final long INTERVAL_DAY = TimeUnit.DAYS.toMillis(1);\n private static final String DEFAULT_LANGUAGE = \"en\";\n @Nullable private static String sLanguage;\n @NonNull private final SuggestionsResult mResultCallback;\n @NonNull private final Application mApplication;\n @NonNull private final OkHttpClient mHttpClient = new OkHttpClient();\n @NonNull private final CacheControl mCacheControl;\n @NonNull private final ConnectivityManager mConnectivityManager;\n @NonNull private String mQuery;\n\n @NonNull\n protected abstract String getQueryUrl(@NonNull String query, @NonNull String language);\n\n protected abstract void parseResults(@NonNull FileInputStream inputStream, @NonNull List results) throws Exception;\n\n @NonNull\n protected abstract String getEncoding();\n\n BaseSuggestionsTask(@NonNull String query,\n @NonNull Application application,\n @NonNull SuggestionsResult callback) {\n mQuery = query;\n mResultCallback = callback;\n mApplication = application;\n mCacheControl = new CacheControl.Builder().maxStale(1, TimeUnit.DAYS).build();\n mConnectivityManager = getConnectivityManager(mApplication);\n }\n\n @NonNull\n private static synchronized String getLanguage() {\n if (sLanguage == null) {\n sLanguage = Locale.getDefault().getLanguage();\n }\n if (TextUtils.isEmpty(sLanguage)) {\n sLanguage = DEFAULT_LANGUAGE;\n }\n return sLanguage;\n }\n\n void run() {\n List filter = new ArrayList<>(5);\n try {\n mQuery = URLEncoder.encode(mQuery, getEncoding());\n } catch (UnsupportedEncodingException e) {\n Log.e(TAG, \"Unable to encode the URL\", e);\n }\n File cache = downloadSuggestionsForQuery(mQuery, getLanguage(), mApplication);\n if (!cache.exists()) {\n post(filter);\n return;\n }\n FileInputStream fileInput = null;\n try {\n fileInput = new FileInputStream(cache);\n parseResults(fileInput, filter);\n } catch (Exception e) {\n post(filter);\n Log.e(TAG, \"Unable to parse results\", e);\n return;\n } finally {\n Utils.close(fileInput);\n }\n post(filter);\n }\n\n private void post(@NonNull List result) {\n mResultCallback.resultReceived(result);\n }\n\n \/**\n * This method downloads the search suggestions for the specific query.\n * NOTE: This is a blocking operation, do not run on the UI thread.\n *\n * @param query the query to get suggestions for\n * @return the cache file containing the suggestions\n *\/\n @NonNull\n private File downloadSuggestionsForQuery(@NonNull String query, String language, @NonNull Application app) {\n String queryUrl = getQueryUrl(query, language);\n File cacheFile = new File(app.getCacheDir(), queryUrl.hashCode() + SuggestionsAdapter.CACHE_FILE_TYPE);\n if (System.currentTimeMillis() - INTERVAL_DAY < cacheFile.lastModified()) {\n return cacheFile;\n }\n if (!isNetworkConnected()) {\n return cacheFile;\n }\n InputStream in = null;\n FileOutputStream fos = null;\n try {\n URL url = new URL(queryUrl);\n Request suggestionsRequest = new Request.Builder().url(url)\n .addHeader(\"Accept-Encoding\", \"gzip\")\n .addHeader(\"Accept-Charset\", getEncoding())\n .cacheControl(mCacheControl)\n .build();\n\n Response suggestionsResponse = mHttpClient.newCall(suggestionsRequest).execute();\n\n if (suggestionsResponse.code() >= HttpURLConnection.HTTP_MULT_CHOICE ||\n suggestionsResponse.code() < HttpURLConnection.HTTP_OK) {\n Log.e(TAG, \"Search API Responded with code: \" + suggestionsResponse.code());\n suggestionsResponse.body().close();\n return cacheFile;\n }\n\n in = suggestionsResponse.body().byteStream();\n\n if (in != null) {\n in = new GZIPInputStream(in);\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n fos = new FileOutputStream(cacheFile);\n int buffer;\n while ((buffer = in.read()) != -1) {\n fos.write(buffer);\n }\n fos.flush();\n }\n suggestionsResponse.body().close();\n cacheFile.setLastModified(System.currentTimeMillis());\n } catch (Exception e) {\n Log.w(TAG, \"Problem getting search suggestions\", e);\n } finally {\n Utils.close(in);\n Utils.close(fos);\n }\n return cacheFile;\n }\n\n private boolean isNetworkConnected() {\n NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();\n return networkInfo != null && networkInfo.isConnected();\n }\n\n @NonNull\n private static ConnectivityManager getConnectivityManager(@NonNull Context context) {\n return (ConnectivityManager) context\n .getApplicationContext()\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n }\n\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage acr.browser.lightning.search;\n\nimport android.app.Application;\nimport android.content.Context;\nimport android.net.ConnectivityManager;\nimport android.net.NetworkInfo;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.InputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.net.URLEncoder;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.concurrent.TimeUnit;\nimport java.util.zip.GZIPInputStream;\n\nimport acr.browser.lightning.database.HistoryItem;\nimport acr.browser.lightning.utils.Utils;\nimport okhttp3.CacheControl;\nimport okhttp3.OkHttpClient;\nimport okhttp3.Request;\nimport okhttp3.Response;\n\nabstract class BaseSuggestionsTask {\n\n private static final String TAG = BaseSuggestionsTask.class.getSimpleName();\n\n static final int MAX_RESULTS = 5;\n private static final long INTERVAL_DAY = TimeUnit.DAYS.toMillis(1);\n private static final String DEFAULT_LANGUAGE = \"en\";\n @Nullable private static String sLanguage;\n @NonNull private final SuggestionsResult mResultCallback;\n @NonNull private final Application mApplication;\n @NonNull private final OkHttpClient mHttpClient = new OkHttpClient();\n @NonNull private final CacheControl mCacheControl;\n @NonNull private String mQuery;\n\n @NonNull\n protected abstract String getQueryUrl(@NonNull String query, @NonNull String language);\n\n protected abstract void parseResults(@NonNull FileInputStream inputStream, @NonNull List results) throws Exception;\n\n @NonNull\n protected abstract String getEncoding();\n\n BaseSuggestionsTask(@NonNull String query,\n @NonNull Application application,\n @NonNull SuggestionsResult callback) {\n mQuery = query;\n mResultCallback = callback;\n mApplication = application;\n mCacheControl = new CacheControl.Builder().maxStale(1, TimeUnit.DAYS).build();\n }\n\n @NonNull\n private static synchronized String getLanguage() {\n if (sLanguage == null) {\n sLanguage = Locale.getDefault().getLanguage();\n }\n if (TextUtils.isEmpty(sLanguage)) {\n sLanguage = DEFAULT_LANGUAGE;\n }\n return sLanguage;\n }\n\n void run() {\n List filter = new ArrayList<>(5);\n try {\n mQuery = URLEncoder.encode(mQuery, getEncoding());\n } catch (UnsupportedEncodingException e) {\n Log.e(TAG, \"Unable to encode the URL\", e);\n }\n File cache = downloadSuggestionsForQuery(mQuery, getLanguage(), mApplication);\n if (!cache.exists()) {\n post(filter);\n return;\n }\n FileInputStream fileInput = null;\n try {\n fileInput = new FileInputStream(cache);\n parseResults(fileInput, filter);\n } catch (Exception e) {\n post(filter);\n Log.e(TAG, \"Unable to parse results\", e);\n return;\n } finally {\n Utils.close(fileInput);\n }\n post(filter);\n }\n\n private void post(@NonNull List result) {\n mResultCallback.resultReceived(result);\n }\n\n \/**\n * This method downloads the search suggestions for the specific query.\n * NOTE: This is a blocking operation, do not run on the UI thread.\n *\n * @param query the query to get suggestions for\n * @return the cache file containing the suggestions\n *\/\n @NonNull\n private File downloadSuggestionsForQuery(@NonNull String query, String language, @NonNull Application app) {\n String queryUrl = getQueryUrl(query, language);\n File cacheFile = new File(app.getCacheDir(), queryUrl.hashCode() + SuggestionsAdapter.CACHE_FILE_TYPE);\n if (System.currentTimeMillis() - INTERVAL_DAY < cacheFile.lastModified()) {\n return cacheFile;\n }\n if (!isNetworkConnected(app)) {\n return cacheFile;\n }\n InputStream in = null;\n FileOutputStream fos = null;\n try {\n URL url = new URL(queryUrl);\n Request suggestionsRequest = new Request.Builder().url(url)\n .addHeader(\"Accept-Encoding\", \"gzip\")\n .addHeader(\"Accept-Charset\", getEncoding())\n .cacheControl(mCacheControl)\n .build();\n\n Response suggestionsResponse = mHttpClient.newCall(suggestionsRequest).execute();\n\n if (suggestionsResponse.code() >= HttpURLConnection.HTTP_MULT_CHOICE ||\n suggestionsResponse.code() < HttpURLConnection.HTTP_OK) {\n Log.e(TAG, \"Search API Responded with code: \" + suggestionsResponse.code());\n suggestionsResponse.body().close();\n return cacheFile;\n }\n\n in = suggestionsResponse.body().byteStream();\n\n if (in != null) {\n in = new GZIPInputStream(in);\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n fos = new FileOutputStream(cacheFile);\n int buffer;\n while ((buffer = in.read()) != -1) {\n fos.write(buffer);\n }\n fos.flush();\n }\n suggestionsResponse.body().close();\n cacheFile.setLastModified(System.currentTimeMillis());\n } catch (Exception e) {\n Log.w(TAG, \"Problem getting search suggestions\", e);\n } finally {\n Utils.close(in);\n Utils.close(fos);\n }\n return cacheFile;\n }\n\n private static boolean isNetworkConnected(@NonNull Context context) {\n NetworkInfo networkInfo = getActiveNetworkInfo(context);\n return networkInfo != null && networkInfo.isConnected();\n }\n\n @Nullable\n private static NetworkInfo getActiveNetworkInfo(@NonNull Context context) {\n ConnectivityManager connectivity = (ConnectivityManager) context\n .getApplicationContext()\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n if (connectivity == null) {\n return null;\n }\n return connectivity.getActiveNetworkInfo();\n }\n\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage acr.browser.lightning.search;\n\nimport android.app.Application;\nimport android.content.Context;\nimport android.net.ConnectivityManager;\nimport android.net.NetworkInfo;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.InputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.net.URLEncoder;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.concurrent.TimeUnit;\nimport java.util.zip.GZIPInputStream;\n\nimport acr.browser.lightning.database.HistoryItem;\nimport acr.browser.lightning.utils.Utils;\nimport okhttp3.CacheControl;\nimport okhttp3.OkHttpClient;\nimport okhttp3.Request;\nimport okhttp3.Response;\n\nabstract class BaseSuggestionsTask {\n\n private static final String TAG = BaseSuggestionsTask.class.getSimpleName();\n\n static final int MAX_RESULTS = 5;\n private static final long INTERVAL_DAY = TimeUnit.DAYS.toMillis(1);\n private static final String DEFAULT_LANGUAGE = \"en\";\n @Nullable private static String sLanguage;\n @NonNull private final SuggestionsResult mResultCallback;\n @NonNull private final Application mApplication;\n @NonNull private final OkHttpClient mHttpClient = new OkHttpClient();\n @NonNull private final CacheControl mCacheControl;\n @NonNull private String mQuery;\n\n @NonNull\n protected abstract String getQueryUrl(@NonNull String query, @NonNull String language);\n\n protected abstract void parseResults(@NonNull FileInputStream inputStream, @NonNull List results) throws Exception;\n\n @NonNull\n protected abstract String getEncoding();\n\n BaseSuggestionsTask(@NonNull String query,\n @NonNull Application application,\n @NonNull SuggestionsResult callback) {\n mQuery = query;\n mResultCallback = callback;\n mApplication = application;\n mCacheControl = new CacheControl.Builder().maxStale(1, TimeUnit.DAYS).build();\n }\n\n @NonNull\n private static synchronized String getLanguage() {\n if (sLanguage == null) {\n sLanguage = Locale.getDefault().getLanguage();\n }\n if (TextUtils.isEmpty(sLanguage)) {\n sLanguage = DEFAULT_LANGUAGE;\n }\n return sLanguage;\n }\n\n void run() {\n List filter = new ArrayList<>(5);\n try {\n mQuery = URLEncoder.encode(mQuery, getEncoding());\n } catch (UnsupportedEncodingException e) {\n Log.e(TAG, \"Unable to encode the URL\", e);\n }\n File cache = downloadSuggestionsForQuery(mQuery, getLanguage(), mApplication);\n if (!cache.exists()) {\n post(filter);\n return;\n }\n FileInputStream fileInput = null;\n try {\n fileInput = new FileInputStream(cache);\n parseResults(fileInput, filter);\n } catch (Exception e) {\n post(filter);\n Log.e(TAG, \"Unable to parse results\", e);\n return;\n } finally {\n Utils.close(fileInput);\n }\n post(filter);\n }\n\n private void post(@NonNull List result) {\n mResultCallback.resultReceived(result);\n }\n\n \/**\n * This method downloads the search suggestions for the specific query.\n * NOTE: This is a blocking operation, do not run on the UI thread.\n *\n * @param query the query to get suggestions for\n * @return the cache file containing the suggestions\n *\/\n @NonNull\n private File downloadSuggestionsForQuery(@NonNull String query, String language, @NonNull Application app) {\n String queryUrl = getQueryUrl(query, language);\n File cacheFile = new File(app.getCacheDir(), queryUrl.hashCode() + SuggestionsAdapter.CACHE_FILE_TYPE);\n if (System.currentTimeMillis() - INTERVAL_DAY < cacheFile.lastModified()) {\n return cacheFile;\n }\n if (!isNetworkConnected(app)) {\n return cacheFile;\n }\n InputStream in = null;\n FileOutputStream fos = null;\n try {\n URL url = new URL(queryUrl);\n Request suggestionsRequest = new Request.Builder().url(url)\n .addHeader(\"Accept-Encoding\", \"gzip\")\n .addHeader(\"Accept-Charset\", getEncoding())\n .cacheControl(mCacheControl)\n .build();\n\n Response suggestionsResponse = mHttpClient.newCall(suggestionsRequest).execute();\n\n if (suggestionsResponse.code() >= HttpURLConnection.HTTP_MULT_CHOICE ||\n suggestionsResponse.code() < HttpURLConnection.HTTP_OK) {\n Log.e(TAG, \"Search API Responded with code: \" + suggestionsResponse.code());\n suggestionsResponse.body().close();\n return cacheFile;\n }\n\n in = suggestionsResponse.body().byteStream();\n\n if (in != null) {\n in = new GZIPInputStream(in);\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n fos = new FileOutputStream(cacheFile);\n int buffer;\n while ((buffer = in.read()) != -1) {\n fos.write(buffer);\n }\n fos.flush();\n }\n suggestionsResponse.body().close();\n cacheFile.setLastModified(System.currentTimeMillis());\n } catch (Exception e) {\n Log.w(TAG, \"Problem getting search suggestions\", e);\n } finally {\n Utils.close(in);\n Utils.close(fos);\n }\n return cacheFile;\n }\n\n private static boolean isNetworkConnected(@NonNull Context context) {\n NetworkInfo networkInfo = getActiveNetworkInfo(context);\n return networkInfo != null && networkInfo.isConnected();\n }\n\n @Nullable\n private static NetworkInfo getActiveNetworkInfo(@NonNull Context context) {\n ConnectivityManager connectivity = (ConnectivityManager) context\n .getApplicationContext()\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n if (connectivity == null) {\n return null;\n }\n return connectivity.getActiveNetworkInfo();\n }\n\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage acr.browser.lightning.search;\n\nimport android.app.Application;\nimport android.content.Context;\nimport android.net.ConnectivityManager;\nimport android.net.NetworkInfo;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.InputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.net.URLEncoder;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.concurrent.TimeUnit;\nimport java.util.zip.GZIPInputStream;\n\nimport acr.browser.lightning.database.HistoryItem;\nimport acr.browser.lightning.utils.Utils;\nimport okhttp3.CacheControl;\nimport okhttp3.OkHttpClient;\nimport okhttp3.Request;\nimport okhttp3.Response;\n\nabstract class BaseSuggestionsTask {\n\n private static final String TAG = BaseSuggestionsTask.class.getSimpleName();\n\n static final int MAX_RESULTS = 5;\n private static final long INTERVAL_DAY = TimeUnit.DAYS.toMillis(1);\n private static final String DEFAULT_LANGUAGE = \"en\";\n @Nullable private static String sLanguage;\n @NonNull private final SuggestionsResult mResultCallback;\n @NonNull private final Application mApplication;\n @NonNull private final OkHttpClient mHttpClient = new OkHttpClient();\n @NonNull private final CacheControl mCacheControl;\n @NonNull private String mQuery;\n\n @NonNull\n protected abstract String getQueryUrl(@NonNull String query, @NonNull String language);\n\n protected abstract void parseResults(@NonNull FileInputStream inputStream, @NonNull List results) throws Exception;\n\n @NonNull\n protected abstract String getEncoding();\n\n BaseSuggestionsTask(@NonNull String query,\n @NonNull Application application,\n @NonNull SuggestionsResult callback) {\n mQuery = query;\n mResultCallback = callback;\n mApplication = application;\n mCacheControl = new CacheControl.Builder().maxStale(1, TimeUnit.DAYS).build();\n }\n\n @NonNull\n private static synchronized String getLanguage() {\n if (sLanguage == null) {\n sLanguage = Locale.getDefault().getLanguage();\n }\n if (TextUtils.isEmpty(sLanguage)) {\n sLanguage = DEFAULT_LANGUAGE;\n }\n return sLanguage;\n }\n\n void run() {\n List filter = new ArrayList<>(5);\n try {\n mQuery = URLEncoder.encode(mQuery, getEncoding());\n } catch (UnsupportedEncodingException e) {\n Log.e(TAG, \"Unable to encode the URL\", e);\n }\n File cache = downloadSuggestionsForQuery(mQuery, getLanguage(), mApplication);\n if (!cache.exists()) {\n post(filter);\n return;\n }\n FileInputStream fileInput = null;\n try {\n fileInput = new FileInputStream(cache);\n parseResults(fileInput, filter);\n } catch (Exception e) {\n post(filter);\n Log.e(TAG, \"Unable to parse results\", e);\n return;\n } finally {\n Utils.close(fileInput);\n }\n post(filter);\n }\n\n private void post(@NonNull List result) {\n mResultCallback.resultReceived(result);\n }\n\n \/**\n * This method downloads the search suggestions for the specific query.\n * NOTE: This is a blocking operation, do not run on the UI thread.\n *\n * @param query the query to get suggestions for\n * @return the cache file containing the suggestions\n *\/\n @NonNull\n private File downloadSuggestionsForQuery(@NonNull String query, String language, @NonNull Application app) {\n String queryUrl = getQueryUrl(query, language);\n File cacheFile = new File(app.getCacheDir(), queryUrl.hashCode() + SuggestionsAdapter.CACHE_FILE_TYPE);\n if (System.currentTimeMillis() - INTERVAL_DAY < cacheFile.lastModified()) {\n return cacheFile;\n }\n if (!isNetworkConnected(app)) {\n return cacheFile;\n }\n InputStream in = null;\n FileOutputStream fos = null;\n try {\n URL url = new URL(queryUrl);\n Request suggestionsRequest = new Request.Builder().url(url)\n .addHeader(\"Accept-Encoding\", \"gzip\")\n .addHeader(\"Accept-Charset\", getEncoding())\n .cacheControl(mCacheControl)\n .build();\n\n Response suggestionsResponse = mHttpClient.newCall(suggestionsRequest).execute();\n\n if (suggestionsResponse.code() >= HttpURLConnection.HTTP_MULT_CHOICE ||\n suggestionsResponse.code() < HttpURLConnection.HTTP_OK) {\n Log.e(TAG, \"Search API Responded with code: \" + suggestionsResponse.code());\n suggestionsResponse.body().close();\n return cacheFile;\n }\n\n in = suggestionsResponse.body().byteStream();\n\n if (in != null) {\n in = new GZIPInputStream(in);\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n fos = new FileOutputStream(cacheFile);\n int buffer;\n while ((buffer = in.read()) != -1) {\n fos.write(buffer);\n }\n fos.flush();\n }\n suggestionsResponse.body().close();\n cacheFile.setLastModified(System.currentTimeMillis());\n } catch (Exception e) {\n Log.w(TAG, \"Problem getting search suggestions\", e);\n } finally {\n Utils.close(in);\n Utils.close(fos);\n }\n return cacheFile;\n }\n\n private static boolean isNetworkConnected(@NonNull Context context) {\n NetworkInfo networkInfo = getActiveNetworkInfo(context);\n return networkInfo != null && networkInfo.isConnected();\n }\n\n @Nullable\n private static NetworkInfo getActiveNetworkInfo(@NonNull Context context) {\n ConnectivityManager connectivity = (ConnectivityManager) context\n .getApplicationContext()\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n if (connectivity == null) {\n return null;\n }\n return connectivity.getActiveNetworkInfo();\n }\n\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite code to keep connectivity manager around, rather than getting it every time, for improving execution time. Write the entire code and no other text in the response.\n\n### Concepts:\n[+] ConnectivityManager mConnectivityManager\n[-] isNetworkConnected(@NonNull Context context)\n[implement] boolean isNetworkConnected()\n[-] getActiveNetworkInfo(@NonNull Context context)\n[implement] ConnectivityManager getConnectivityManager(@NonNull Context context)\n[in] BaseSuggestionsTask constructor\n[in] downloadSuggestionsForQuery function\n\n### Given program:\n```java\npackage acr.browser.lightning.search;\n\nimport android.app.Application;\nimport android.content.Context;\nimport android.net.ConnectivityManager;\nimport android.net.NetworkInfo;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.InputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.net.URLEncoder;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.concurrent.TimeUnit;\nimport java.util.zip.GZIPInputStream;\n\nimport acr.browser.lightning.database.HistoryItem;\nimport acr.browser.lightning.utils.Utils;\nimport okhttp3.CacheControl;\nimport okhttp3.OkHttpClient;\nimport okhttp3.Request;\nimport okhttp3.Response;\n\nabstract class BaseSuggestionsTask {\n\n private static final String TAG = BaseSuggestionsTask.class.getSimpleName();\n\n static final int MAX_RESULTS = 5;\n private static final long INTERVAL_DAY = TimeUnit.DAYS.toMillis(1);\n private static final String DEFAULT_LANGUAGE = \"en\";\n @Nullable private static String sLanguage;\n @NonNull private final SuggestionsResult mResultCallback;\n @NonNull private final Application mApplication;\n @NonNull private final OkHttpClient mHttpClient = new OkHttpClient();\n @NonNull private final CacheControl mCacheControl;\n @NonNull private String mQuery;\n\n @NonNull\n protected abstract String getQueryUrl(@NonNull String query, @NonNull String language);\n\n protected abstract void parseResults(@NonNull FileInputStream inputStream, @NonNull List results) throws Exception;\n\n @NonNull\n protected abstract String getEncoding();\n\n BaseSuggestionsTask(@NonNull String query,\n @NonNull Application application,\n @NonNull SuggestionsResult callback) {\n mQuery = query;\n mResultCallback = callback;\n mApplication = application;\n mCacheControl = new CacheControl.Builder().maxStale(1, TimeUnit.DAYS).build();\n }\n\n @NonNull\n private static synchronized String getLanguage() {\n if (sLanguage == null) {\n sLanguage = Locale.getDefault().getLanguage();\n }\n if (TextUtils.isEmpty(sLanguage)) {\n sLanguage = DEFAULT_LANGUAGE;\n }\n return sLanguage;\n }\n\n void run() {\n List filter = new ArrayList<>(5);\n try {\n mQuery = URLEncoder.encode(mQuery, getEncoding());\n } catch (UnsupportedEncodingException e) {\n Log.e(TAG, \"Unable to encode the URL\", e);\n }\n File cache = downloadSuggestionsForQuery(mQuery, getLanguage(), mApplication);\n if (!cache.exists()) {\n post(filter);\n return;\n }\n FileInputStream fileInput = null;\n try {\n fileInput = new FileInputStream(cache);\n parseResults(fileInput, filter);\n } catch (Exception e) {\n post(filter);\n Log.e(TAG, \"Unable to parse results\", e);\n return;\n } finally {\n Utils.close(fileInput);\n }\n post(filter);\n }\n\n private void post(@NonNull List result) {\n mResultCallback.resultReceived(result);\n }\n\n \/**\n * This method downloads the search suggestions for the specific query.\n * NOTE: This is a blocking operation, do not run on the UI thread.\n *\n * @param query the query to get suggestions for\n * @return the cache file containing the suggestions\n *\/\n @NonNull\n private File downloadSuggestionsForQuery(@NonNull String query, String language, @NonNull Application app) {\n String queryUrl = getQueryUrl(query, language);\n File cacheFile = new File(app.getCacheDir(), queryUrl.hashCode() + SuggestionsAdapter.CACHE_FILE_TYPE);\n if (System.currentTimeMillis() - INTERVAL_DAY < cacheFile.lastModified()) {\n return cacheFile;\n }\n if (!isNetworkConnected(app)) {\n return cacheFile;\n }\n InputStream in = null;\n FileOutputStream fos = null;\n try {\n URL url = new URL(queryUrl);\n Request suggestionsRequest = new Request.Builder().url(url)\n .addHeader(\"Accept-Encoding\", \"gzip\")\n .addHeader(\"Accept-Charset\", getEncoding())\n .cacheControl(mCacheControl)\n .build();\n\n Response suggestionsResponse = mHttpClient.newCall(suggestionsRequest).execute();\n\n if (suggestionsResponse.code() >= HttpURLConnection.HTTP_MULT_CHOICE ||\n suggestionsResponse.code() < HttpURLConnection.HTTP_OK) {\n Log.e(TAG, \"Search API Responded with code: \" + suggestionsResponse.code());\n suggestionsResponse.body().close();\n return cacheFile;\n }\n\n in = suggestionsResponse.body().byteStream();\n\n if (in != null) {\n in = new GZIPInputStream(in);\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n fos = new FileOutputStream(cacheFile);\n int buffer;\n while ((buffer = in.read()) != -1) {\n fos.write(buffer);\n }\n fos.flush();\n }\n suggestionsResponse.body().close();\n cacheFile.setLastModified(System.currentTimeMillis());\n } catch (Exception e) {\n Log.w(TAG, \"Problem getting search suggestions\", e);\n } finally {\n Utils.close(in);\n Utils.close(fos);\n }\n return cacheFile;\n }\n\n private static boolean isNetworkConnected(@NonNull Context context) {\n NetworkInfo networkInfo = getActiveNetworkInfo(context);\n return networkInfo != null && networkInfo.isConnected();\n }\n\n @Nullable\n private static NetworkInfo getActiveNetworkInfo(@NonNull Context context) {\n ConnectivityManager connectivity = (ConnectivityManager) context\n .getApplicationContext()\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n if (connectivity == null) {\n return null;\n }\n return connectivity.getActiveNetworkInfo();\n }\n\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void deleteHistoryItem(String url) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t}\n\n\tpublic synchronized void visitHistoryItem(String url, String title) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tint n = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t\tn++;\n\t\t\t} while (cursor.moveToPrevious() && n < 5);\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n\n\nCode-B:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void delete(String url) {\n\t\tString n = getHistoryItem(url);\n\t\tif (n != null) {\n\t\t\tdeleteHistoryItem(n);\n\t\t}\n\t}\n\n\tpublic synchronized void visitHistoryItem(String url, String title) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tint n = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t\tn++;\n\t\t\t} while (cursor.moveToPrevious() && n < 5);\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Deleting single item\n\tpublic synchronized void deleteHistoryItem(String id) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_ID + \" = ?\", new String[] { String.valueOf(id) });\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void delete(String url) {\n\t\tString n = getHistoryItem(url);\n\t\tif (n != null) {\n\t\t\tdeleteHistoryItem(n);\n\t\t}\n\t}\n\n\tpublic synchronized void visitHistoryItem(String url, String title) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tint n = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t\tn++;\n\t\t\t} while (cursor.moveToPrevious() && n < 5);\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Deleting single item\n\tpublic synchronized void deleteHistoryItem(String id) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_ID + \" = ?\", new String[] { String.valueOf(id) });\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n\n\nCode-B:\n\/*\n * Copyright 2014 A.C.R. Development\n *\/\npackage acr.browser.lightning;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class HistoryDatabaseHandler extends SQLiteOpenHelper {\n\n\t\/\/ All Static variables\n\t\/\/ Database Version\n\tprivate static final int DATABASE_VERSION = 1;\n\n\t\/\/ Database Name\n\tpublic static final String DATABASE_NAME = \"historyManager\";\n\n\t\/\/ HistoryItems table name\n\tpublic static final String TABLE_HISTORY = \"history\";\n\n\t\/\/ HistoryItems Table Columns names\n\tpublic static final String KEY_ID = \"id\";\n\n\tpublic static final String KEY_URL = \"url\";\n\n\tpublic static final String KEY_TITLE = \"title\";\n\n\tpublic static SQLiteDatabase mDatabase;\n\n\tpublic HistoryDatabaseHandler(Context context) {\n\t\tsuper(context.getApplicationContext(), DATABASE_NAME, null, DATABASE_VERSION);\n\t\tmDatabase = this.getWritableDatabase();\n\t}\n\n\t\/\/ Creating Tables\n\t@Override\n\tpublic void onCreate(SQLiteDatabase db) {\n\t\tString CREATE_HISTORY_TABLE = \"CREATE TABLE \" + TABLE_HISTORY + \"(\" + KEY_ID\n\t\t\t\t+ \" INTEGER PRIMARY KEY,\" + KEY_URL + \" TEXT,\" + KEY_TITLE + \" TEXT\" + \")\";\n\t\tdb.execSQL(CREATE_HISTORY_TABLE);\n\t}\n\n\t\/\/ Upgrading database\n\t@Override\n\tpublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\t\t\/\/ Drop older table if existed\n\t\tdb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_HISTORY);\n\n\t\t\/\/ Create tables again\n\t\tonCreate(db);\n\t}\n\n\tpublic boolean isOpen() {\n\t\tif (mDatabase != null) {\n\t\t\treturn mDatabase.isOpen();\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic synchronized void close() {\n\t\tif (mDatabase != null) {\n\t\t\tmDatabase.close();\n\t\t}\n\t\tsuper.close();\n\t}\n\n\t\/**\n\t * All CRUD(Create, Read, Update, Delete) Operations\n\t *\/\n\n\tpublic synchronized void deleteHistoryItem(String url) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t}\n\n\tpublic synchronized void visitHistoryItem(String url, String title) {\n\t\tmDatabase.delete(TABLE_HISTORY, KEY_URL + \" = ?\", new String[] { url });\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, url);\n\t\tvalues.put(KEY_TITLE, title);\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Adding new item\n\tpublic synchronized void addHistoryItem(HistoryItem item) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tmDatabase.insert(TABLE_HISTORY, null, values);\n\t}\n\n\t\/\/ Getting single item\n\tString getHistoryItem(String url) {\n\t\tCursor cursor = mDatabase.query(TABLE_HISTORY, new String[] { KEY_ID, KEY_URL, KEY_TITLE },\n\t\t\t\tKEY_URL + \"=?\", new String[] { url }, null, null, null, null);\n\t\tString m = null;\n\t\tif (cursor != null) {\n\t\t\tcursor.moveToFirst();\n\t\t\tm = cursor.getString(0);\n\n\t\t\tcursor.close();\n\t\t}\n\t\t\/\/ return item\n\t\treturn m;\n\t}\n\n\tpublic List findItemsContaining(String search) {\n\t\tList itemList = new ArrayList();\n\t\t\/\/ select query\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY + \" WHERE \" + KEY_TITLE + \" LIKE '%\"\n\t\t\t\t+ search + \"%' OR \" + KEY_URL + \" LIKE '%\" + search + \"%'\";\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\t\/\/ looping through all rows and adding to list\n\t\tint n = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\t\/\/ Adding item to list\n\t\t\t\titemList.add(item);\n\t\t\t\tn++;\n\t\t\t} while (cursor.moveToPrevious() && n < 5);\n\t\t}\n\t\tcursor.close();\n\t\t\/\/ return item list\n\t\treturn itemList;\n\t}\n\n\tpublic List getLastHundredItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\t\tint counter = 0;\n\t\tif (cursor.moveToLast()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t\tcounter++;\n\t\t\t} while (cursor.moveToPrevious() && counter < 100);\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\tpublic List getAllHistoryItems() {\n\t\tList itemList = new ArrayList();\n\t\tString selectQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\n\t\tCursor cursor = mDatabase.rawQuery(selectQuery, null);\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tdo {\n\t\t\t\tHistoryItem item = new HistoryItem();\n\t\t\t\titem.setID(Integer.parseInt(cursor.getString(0)));\n\t\t\t\titem.setUrl(cursor.getString(1));\n\t\t\t\titem.setTitle(cursor.getString(2));\n\t\t\t\titem.setImageId(R.drawable.ic_history);\n\t\t\t\titemList.add(item);\n\t\t\t} while (cursor.moveToNext());\n\t\t}\n\t\tcursor.close();\n\t\treturn itemList;\n\t}\n\n\t\/\/ Updating single item\n\tpublic synchronized int updateHistoryItem(HistoryItem item) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_URL, item.getUrl());\n\t\tvalues.put(KEY_TITLE, item.getTitle());\n\t\tint n = mDatabase.update(TABLE_HISTORY, values, KEY_ID + \" = ?\",\n\t\t\t\tnew String[] { String.valueOf(item.getId()) });\n\t\t\/\/ updating row\n\t\treturn n;\n\t}\n\n\t\/\/ Getting items Count\n\tpublic int getHistoryItemsCount() {\n\t\tString countQuery = \"SELECT * FROM \" + TABLE_HISTORY;\n\t\tCursor cursor = mDatabase.rawQuery(countQuery, null);\n\t\tcursor.close();\n\n\t\t\/\/ return count\n\t\treturn cursor.getCount();\n\t}\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/erikusaj\/fdroidTvClient\/commit\/2fc8060a5dc76f6705476b26798e914814d6da1c","commit_message":"'\\\\\"Check file size first before checking hash to save cycles.\\\\n\\\\\"'","source_code":"package org.fdroid.fdroid;\n\nimport android.app.IntentService;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.net.Uri;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport org.fdroid.fdroid.data.Apk;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.InstalledAppProviderService;\nimport org.fdroid.fdroid.installer.ApkCache;\nimport org.fdroid.fdroid.installer.InstallManagerService;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\n\/**\n * Scans the list of downloaded .apk files in the cache for each app which can be updated.\n * If a valid .apk file is found then it will tell the {@link AppUpdateStatusManager} that it is\n * {@link AppUpdateStatusManager.Status#ReadyToInstall}. This is an {@link IntentService} so as to\n * run on a background thread, as it hits the disk a bit to figure out the hash of each downloaded\n * file.\n *\/\n@SuppressWarnings(\"LineLength\")\npublic class AppUpdateStatusService extends IntentService {\n\n private static final String TAG = \"AppUpdateStatusService\";\n\n \/**\n * Queue up a background scan of all downloaded apk files to see if we should notify the user\n * that they are ready to install.\n *\/\n public static void scanDownloadedApks(Context context) {\n context.startService(new Intent(context, AppUpdateStatusService.class));\n }\n\n public AppUpdateStatusService() {\n super(\"AppUpdateStatusService\");\n }\n\n @Override\n protected void onHandleIntent(@Nullable Intent intent) {\n Utils.debugLog(TAG, \"Scanning apk cache to see if we need to prompt the user to install any apks.\");\n File cacheDir = ApkCache.getApkCacheDir(this);\n if (cacheDir == null) {\n return;\n }\n String[] cacheDirList = cacheDir.list();\n if (cacheDirList == null) {\n return;\n }\n List apksReadyToInstall = new ArrayList<>();\n for (String repoDirName : cacheDirList) {\n File repoDir = new File(cacheDir, repoDirName);\n String[] apks = repoDir.list();\n if (apks == null) {\n continue;\n }\n for (String apkFileName : apks) {\n Apk apk = processDownloadedApk(new File(repoDir, apkFileName));\n if (apk != null) {\n Log.i(TAG, \"Found downloaded apk \" + apk.packageName + \". Notifying user that it should be installed.\");\n apksReadyToInstall.add(apk);\n }\n }\n }\n\n if (apksReadyToInstall.size() > 0) {\n AppUpdateStatusManager.getInstance(this).addApks(apksReadyToInstall, AppUpdateStatusManager.Status.ReadyToInstall);\n InstallManagerService.managePreviouslyDownloadedApks(this);\n }\n }\n\n \/**\n * Verifies that {@param apkPath} is a valid apk which the user intends to install.\n * If it is corrupted to the point where {@link PackageManager} can't read it, doesn't match the hash of any apk\n * we know about in our database, is not pending install, or is already installed, then it will return null.\n *\/\n @Nullable\n private Apk processDownloadedApk(File apkPath) {\n Utils.debugLog(TAG, \"Checking \" + apkPath);\n PackageInfo downloadedInfo = getPackageManager().getPackageArchiveInfo(apkPath.getAbsolutePath(), PackageManager.GET_GIDS);\n if (downloadedInfo == null) {\n Log.i(TAG, \"Skipping \" + apkPath + \" because PackageManager was unable to read it.\");\n return null;\n }\n\n Utils.debugLog(TAG, \"Found package for \" + downloadedInfo.packageName + \", checking its hash to see if it downloaded correctly.\");\n Apk downloadedApk = findApkMatchingHash(apkPath);\n if (downloadedApk == null) {\n Log.i(TAG, \"Either the apk wasn't downloaded fully, or the repo it came from has been disabled. Either way, not notifying the user about it.\");\n return null;\n }\n\n if (!AppUpdateStatusManager.getInstance(this).isPendingInstall(downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is NOT pending install, probably just left over from a previous install.\");\n return null;\n }\n\n try {\n PackageInfo info = getPackageManager().getPackageInfo(downloadedApk.packageName, 0);\n File pathToInstalled = InstalledAppProviderService.getPathToInstalledApk(info);\n if (pathToInstalled != null && pathToInstalled.canRead() &&\n TextUtils.equals(Utils.getBinaryHash(pathToInstalled, \"sha256\"), downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is pending install, but we already have the correct version installed.\");\n AppUpdateStatusManager.getInstance(this).markAsNoLongerPendingInstall(downloadedApk.getUrl());\n return null;\n }\n } catch (PackageManager.NameNotFoundException ignored) { }\n\n Utils.debugLog(TAG, downloadedApk.packageName + \" is pending install, so we need to notify the user about installing it.\");\n return downloadedApk;\n }\n\n \/**\n * There could be multiple apks with the same hash, provided by different repositories.\n * This method looks for all matching records in the database. It then asks each of these\n * {@link Apk} instances where they expect to be downloaded. If they expect to be downloaded\n * to {@param apkPath} then that instance is returned.\n *\n * If no files have a matching hash, or only those which don't belong to the correct repo, then\n * this will return null.\n *\/\n @Nullable\n private Apk findApkMatchingHash(File apkPath) {\n\n \/\/ NOTE: This presumes SHA256 is the only supported hash. It seems like that is an assumption\n \/\/ in more than one place in the F-Droid client. If this becomes a problem in the future, we\n \/\/ can query the Apk table for `SELECT DISTINCT hashType FROM fdroid_apk` and then we can just\n \/\/ try each of the hash types that have been specified in the metadata. Seems a bit overkill\n \/\/ at the time of writing though.\n String hash = Utils.getBinaryHash(apkPath, \"sha256\");\n\n List apksMatchingHash = ApkProvider.Helper.findApksByHash(this, hash);\n Utils.debugLog(TAG, \"Found \" + apksMatchingHash.size() + \" apk(s) matching the hash \" + hash);\n\n for (Apk apk : apksMatchingHash) {\n if (apkPath.equals(ApkCache.getApkDownloadPath(this, Uri.parse(apk.getUrl())))) {\n return apk;\n }\n }\n\n return null;\n }\n}","target_code":"package org.fdroid.fdroid;\n\nimport android.app.IntentService;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.net.Uri;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport org.fdroid.fdroid.data.Apk;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.InstalledAppProviderService;\nimport org.fdroid.fdroid.installer.ApkCache;\nimport org.fdroid.fdroid.installer.InstallManagerService;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\n\/**\n * Scans the list of downloaded .apk files in the cache for each app which can be updated.\n * If a valid .apk file is found then it will tell the {@link AppUpdateStatusManager} that it is\n * {@link AppUpdateStatusManager.Status#ReadyToInstall}. This is an {@link IntentService} so as to\n * run on a background thread, as it hits the disk a bit to figure out the hash of each downloaded\n * file.\n *\/\n@SuppressWarnings(\"LineLength\")\npublic class AppUpdateStatusService extends IntentService {\n\n private static final String TAG = \"AppUpdateStatusService\";\n\n \/**\n * Queue up a background scan of all downloaded apk files to see if we should notify the user\n * that they are ready to install.\n *\/\n public static void scanDownloadedApks(Context context) {\n context.startService(new Intent(context, AppUpdateStatusService.class));\n }\n\n public AppUpdateStatusService() {\n super(\"AppUpdateStatusService\");\n }\n\n @Override\n protected void onHandleIntent(@Nullable Intent intent) {\n Utils.debugLog(TAG, \"Scanning apk cache to see if we need to prompt the user to install any apks.\");\n File cacheDir = ApkCache.getApkCacheDir(this);\n if (cacheDir == null) {\n return;\n }\n String[] cacheDirList = cacheDir.list();\n if (cacheDirList == null) {\n return;\n }\n List apksReadyToInstall = new ArrayList<>();\n for (String repoDirName : cacheDirList) {\n File repoDir = new File(cacheDir, repoDirName);\n String[] apks = repoDir.list();\n if (apks == null) {\n continue;\n }\n for (String apkFileName : apks) {\n Apk apk = processDownloadedApk(new File(repoDir, apkFileName));\n if (apk != null) {\n Log.i(TAG, \"Found downloaded apk \" + apk.packageName + \". Notifying user that it should be installed.\");\n apksReadyToInstall.add(apk);\n }\n }\n }\n\n if (apksReadyToInstall.size() > 0) {\n AppUpdateStatusManager.getInstance(this).addApks(apksReadyToInstall, AppUpdateStatusManager.Status.ReadyToInstall);\n InstallManagerService.managePreviouslyDownloadedApks(this);\n }\n }\n\n \/**\n * Verifies that {@param apkPath} is a valid apk which the user intends to install.\n * If it is corrupted to the point where {@link PackageManager} can't read it, doesn't match the hash of any apk\n * we know about in our database, is not pending install, or is already installed, then it will return null.\n *\/\n @Nullable\n private Apk processDownloadedApk(File apkPath) {\n Utils.debugLog(TAG, \"Checking \" + apkPath);\n PackageInfo downloadedInfo = getPackageManager().getPackageArchiveInfo(apkPath.getAbsolutePath(), PackageManager.GET_GIDS);\n if (downloadedInfo == null) {\n Log.i(TAG, \"Skipping \" + apkPath + \" because PackageManager was unable to read it.\");\n return null;\n }\n\n Utils.debugLog(TAG, \"Found package for \" + downloadedInfo.packageName + \", checking its hash to see if it downloaded correctly.\");\n Apk downloadedApk = findApkMatchingHash(apkPath);\n if (downloadedApk == null) {\n Log.i(TAG, \"Either the apk wasn't downloaded fully, or the repo it came from has been disabled. Either way, not notifying the user about it.\");\n return null;\n }\n\n if (!AppUpdateStatusManager.getInstance(this).isPendingInstall(downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is NOT pending install, probably just left over from a previous install.\");\n return null;\n }\n\n try {\n PackageInfo info = getPackageManager().getPackageInfo(downloadedApk.packageName, 0);\n File pathToInstalled = InstalledAppProviderService.getPathToInstalledApk(info);\n if (pathToInstalled != null && pathToInstalled.canRead() &&\n pathToInstalled.length() == downloadedApk.size && \/\/ Check size before hash for performance.\n TextUtils.equals(Utils.getBinaryHash(pathToInstalled, \"sha256\"), downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is pending install, but we already have the correct version installed.\");\n AppUpdateStatusManager.getInstance(this).markAsNoLongerPendingInstall(downloadedApk.getUrl());\n return null;\n }\n } catch (PackageManager.NameNotFoundException ignored) { }\n\n Utils.debugLog(TAG, downloadedApk.packageName + \" is pending install, so we need to notify the user about installing it.\");\n return downloadedApk;\n }\n\n \/**\n * There could be multiple apks with the same hash, provided by different repositories.\n * This method looks for all matching records in the database. It then asks each of these\n * {@link Apk} instances where they expect to be downloaded. If they expect to be downloaded\n * to {@param apkPath} then that instance is returned.\n *\n * If no files have a matching hash, or only those which don't belong to the correct repo, then\n * this will return null.\n *\/\n @Nullable\n private Apk findApkMatchingHash(File apkPath) {\n\n \/\/ NOTE: This presumes SHA256 is the only supported hash. It seems like that is an assumption\n \/\/ in more than one place in the F-Droid client. If this becomes a problem in the future, we\n \/\/ can query the Apk table for `SELECT DISTINCT hashType FROM fdroid_apk` and then we can just\n \/\/ try each of the hash types that have been specified in the metadata. Seems a bit overkill\n \/\/ at the time of writing though.\n String hash = Utils.getBinaryHash(apkPath, \"sha256\");\n\n List apksMatchingHash = ApkProvider.Helper.findApksByHash(this, hash);\n Utils.debugLog(TAG, \"Found \" + apksMatchingHash.size() + \" apk(s) matching the hash \" + hash);\n\n for (Apk apk : apksMatchingHash) {\n if (apkPath.equals(ApkCache.getApkDownloadPath(this, Uri.parse(apk.getUrl())))) {\n return apk;\n }\n }\n\n return null;\n }\n}","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid;\n\nimport android.app.IntentService;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.net.Uri;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport org.fdroid.fdroid.data.Apk;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.InstalledAppProviderService;\nimport org.fdroid.fdroid.installer.ApkCache;\nimport org.fdroid.fdroid.installer.InstallManagerService;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\n\/**\n * Scans the list of downloaded .apk files in the cache for each app which can be updated.\n * If a valid .apk file is found then it will tell the {@link AppUpdateStatusManager} that it is\n * {@link AppUpdateStatusManager.Status#ReadyToInstall}. This is an {@link IntentService} so as to\n * run on a background thread, as it hits the disk a bit to figure out the hash of each downloaded\n * file.\n *\/\n@SuppressWarnings(\"LineLength\")\npublic class AppUpdateStatusService extends IntentService {\n\n private static final String TAG = \"AppUpdateStatusService\";\n\n \/**\n * Queue up a background scan of all downloaded apk files to see if we should notify the user\n * that they are ready to install.\n *\/\n public static void scanDownloadedApks(Context context) {\n context.startService(new Intent(context, AppUpdateStatusService.class));\n }\n\n public AppUpdateStatusService() {\n super(\"AppUpdateStatusService\");\n }\n\n @Override\n protected void onHandleIntent(@Nullable Intent intent) {\n Utils.debugLog(TAG, \"Scanning apk cache to see if we need to prompt the user to install any apks.\");\n File cacheDir = ApkCache.getApkCacheDir(this);\n if (cacheDir == null) {\n return;\n }\n String[] cacheDirList = cacheDir.list();\n if (cacheDirList == null) {\n return;\n }\n List apksReadyToInstall = new ArrayList<>();\n for (String repoDirName : cacheDirList) {\n File repoDir = new File(cacheDir, repoDirName);\n String[] apks = repoDir.list();\n if (apks == null) {\n continue;\n }\n for (String apkFileName : apks) {\n Apk apk = processDownloadedApk(new File(repoDir, apkFileName));\n if (apk != null) {\n Log.i(TAG, \"Found downloaded apk \" + apk.packageName + \". Notifying user that it should be installed.\");\n apksReadyToInstall.add(apk);\n }\n }\n }\n\n if (apksReadyToInstall.size() > 0) {\n AppUpdateStatusManager.getInstance(this).addApks(apksReadyToInstall, AppUpdateStatusManager.Status.ReadyToInstall);\n InstallManagerService.managePreviouslyDownloadedApks(this);\n }\n }\n\n \/**\n * Verifies that {@param apkPath} is a valid apk which the user intends to install.\n * If it is corrupted to the point where {@link PackageManager} can't read it, doesn't match the hash of any apk\n * we know about in our database, is not pending install, or is already installed, then it will return null.\n *\/\n @Nullable\n private Apk processDownloadedApk(File apkPath) {\n Utils.debugLog(TAG, \"Checking \" + apkPath);\n PackageInfo downloadedInfo = getPackageManager().getPackageArchiveInfo(apkPath.getAbsolutePath(), PackageManager.GET_GIDS);\n if (downloadedInfo == null) {\n Log.i(TAG, \"Skipping \" + apkPath + \" because PackageManager was unable to read it.\");\n return null;\n }\n\n Utils.debugLog(TAG, \"Found package for \" + downloadedInfo.packageName + \", checking its hash to see if it downloaded correctly.\");\n Apk downloadedApk = findApkMatchingHash(apkPath);\n if (downloadedApk == null) {\n Log.i(TAG, \"Either the apk wasn't downloaded fully, or the repo it came from has been disabled. Either way, not notifying the user about it.\");\n return null;\n }\n\n if (!AppUpdateStatusManager.getInstance(this).isPendingInstall(downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is NOT pending install, probably just left over from a previous install.\");\n return null;\n }\n\n try {\n PackageInfo info = getPackageManager().getPackageInfo(downloadedApk.packageName, 0);\n File pathToInstalled = InstalledAppProviderService.getPathToInstalledApk(info);\n if (pathToInstalled != null && pathToInstalled.canRead() &&\n TextUtils.equals(Utils.getBinaryHash(pathToInstalled, \"sha256\"), downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is pending install, but we already have the correct version installed.\");\n AppUpdateStatusManager.getInstance(this).markAsNoLongerPendingInstall(downloadedApk.getUrl());\n return null;\n }\n } catch (PackageManager.NameNotFoundException ignored) { }\n\n Utils.debugLog(TAG, downloadedApk.packageName + \" is pending install, so we need to notify the user about installing it.\");\n return downloadedApk;\n }\n\n \/**\n * There could be multiple apks with the same hash, provided by different repositories.\n * This method looks for all matching records in the database. It then asks each of these\n * {@link Apk} instances where they expect to be downloaded. If they expect to be downloaded\n * to {@param apkPath} then that instance is returned.\n *\n * If no files have a matching hash, or only those which don't belong to the correct repo, then\n * this will return null.\n *\/\n @Nullable\n private Apk findApkMatchingHash(File apkPath) {\n\n \/\/ NOTE: This presumes SHA256 is the only supported hash. It seems like that is an assumption\n \/\/ in more than one place in the F-Droid client. If this becomes a problem in the future, we\n \/\/ can query the Apk table for `SELECT DISTINCT hashType FROM fdroid_apk` and then we can just\n \/\/ try each of the hash types that have been specified in the metadata. Seems a bit overkill\n \/\/ at the time of writing though.\n String hash = Utils.getBinaryHash(apkPath, \"sha256\");\n\n List apksMatchingHash = ApkProvider.Helper.findApksByHash(this, hash);\n Utils.debugLog(TAG, \"Found \" + apksMatchingHash.size() + \" apk(s) matching the hash \" + hash);\n\n for (Apk apk : apksMatchingHash) {\n if (apkPath.equals(ApkCache.getApkDownloadPath(this, Uri.parse(apk.getUrl())))) {\n return apk;\n }\n }\n\n return null;\n }\n}\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid;\n\nimport android.app.IntentService;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.net.Uri;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport org.fdroid.fdroid.data.Apk;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.InstalledAppProviderService;\nimport org.fdroid.fdroid.installer.ApkCache;\nimport org.fdroid.fdroid.installer.InstallManagerService;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\n\/**\n * Scans the list of downloaded .apk files in the cache for each app which can be updated.\n * If a valid .apk file is found then it will tell the {@link AppUpdateStatusManager} that it is\n * {@link AppUpdateStatusManager.Status#ReadyToInstall}. This is an {@link IntentService} so as to\n * run on a background thread, as it hits the disk a bit to figure out the hash of each downloaded\n * file.\n *\/\n@SuppressWarnings(\"LineLength\")\npublic class AppUpdateStatusService extends IntentService {\n\n private static final String TAG = \"AppUpdateStatusService\";\n\n \/**\n * Queue up a background scan of all downloaded apk files to see if we should notify the user\n * that they are ready to install.\n *\/\n public static void scanDownloadedApks(Context context) {\n context.startService(new Intent(context, AppUpdateStatusService.class));\n }\n\n public AppUpdateStatusService() {\n super(\"AppUpdateStatusService\");\n }\n\n @Override\n protected void onHandleIntent(@Nullable Intent intent) {\n Utils.debugLog(TAG, \"Scanning apk cache to see if we need to prompt the user to install any apks.\");\n File cacheDir = ApkCache.getApkCacheDir(this);\n if (cacheDir == null) {\n return;\n }\n String[] cacheDirList = cacheDir.list();\n if (cacheDirList == null) {\n return;\n }\n List apksReadyToInstall = new ArrayList<>();\n for (String repoDirName : cacheDirList) {\n File repoDir = new File(cacheDir, repoDirName);\n String[] apks = repoDir.list();\n if (apks == null) {\n continue;\n }\n for (String apkFileName : apks) {\n Apk apk = processDownloadedApk(new File(repoDir, apkFileName));\n if (apk != null) {\n Log.i(TAG, \"Found downloaded apk \" + apk.packageName + \". Notifying user that it should be installed.\");\n apksReadyToInstall.add(apk);\n }\n }\n }\n\n if (apksReadyToInstall.size() > 0) {\n AppUpdateStatusManager.getInstance(this).addApks(apksReadyToInstall, AppUpdateStatusManager.Status.ReadyToInstall);\n InstallManagerService.managePreviouslyDownloadedApks(this);\n }\n }\n\n \/**\n * Verifies that {@param apkPath} is a valid apk which the user intends to install.\n * If it is corrupted to the point where {@link PackageManager} can't read it, doesn't match the hash of any apk\n * we know about in our database, is not pending install, or is already installed, then it will return null.\n *\/\n @Nullable\n private Apk processDownloadedApk(File apkPath) {\n Utils.debugLog(TAG, \"Checking \" + apkPath);\n PackageInfo downloadedInfo = getPackageManager().getPackageArchiveInfo(apkPath.getAbsolutePath(), PackageManager.GET_GIDS);\n if (downloadedInfo == null) {\n Log.i(TAG, \"Skipping \" + apkPath + \" because PackageManager was unable to read it.\");\n return null;\n }\n\n Utils.debugLog(TAG, \"Found package for \" + downloadedInfo.packageName + \", checking its hash to see if it downloaded correctly.\");\n Apk downloadedApk = findApkMatchingHash(apkPath);\n if (downloadedApk == null) {\n Log.i(TAG, \"Either the apk wasn't downloaded fully, or the repo it came from has been disabled. Either way, not notifying the user about it.\");\n return null;\n }\n\n if (!AppUpdateStatusManager.getInstance(this).isPendingInstall(downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is NOT pending install, probably just left over from a previous install.\");\n return null;\n }\n\n try {\n PackageInfo info = getPackageManager().getPackageInfo(downloadedApk.packageName, 0);\n File pathToInstalled = InstalledAppProviderService.getPathToInstalledApk(info);\n if (pathToInstalled != null && pathToInstalled.canRead() &&\n TextUtils.equals(Utils.getBinaryHash(pathToInstalled, \"sha256\"), downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is pending install, but we already have the correct version installed.\");\n AppUpdateStatusManager.getInstance(this).markAsNoLongerPendingInstall(downloadedApk.getUrl());\n return null;\n }\n } catch (PackageManager.NameNotFoundException ignored) { }\n\n Utils.debugLog(TAG, downloadedApk.packageName + \" is pending install, so we need to notify the user about installing it.\");\n return downloadedApk;\n }\n\n \/**\n * There could be multiple apks with the same hash, provided by different repositories.\n * This method looks for all matching records in the database. It then asks each of these\n * {@link Apk} instances where they expect to be downloaded. If they expect to be downloaded\n * to {@param apkPath} then that instance is returned.\n *\n * If no files have a matching hash, or only those which don't belong to the correct repo, then\n * this will return null.\n *\/\n @Nullable\n private Apk findApkMatchingHash(File apkPath) {\n\n \/\/ NOTE: This presumes SHA256 is the only supported hash. It seems like that is an assumption\n \/\/ in more than one place in the F-Droid client. If this becomes a problem in the future, we\n \/\/ can query the Apk table for `SELECT DISTINCT hashType FROM fdroid_apk` and then we can just\n \/\/ try each of the hash types that have been specified in the metadata. Seems a bit overkill\n \/\/ at the time of writing though.\n String hash = Utils.getBinaryHash(apkPath, \"sha256\");\n\n List apksMatchingHash = ApkProvider.Helper.findApksByHash(this, hash);\n Utils.debugLog(TAG, \"Found \" + apksMatchingHash.size() + \" apk(s) matching the hash \" + hash);\n\n for (Apk apk : apksMatchingHash) {\n if (apkPath.equals(ApkCache.getApkDownloadPath(this, Uri.parse(apk.getUrl())))) {\n return apk;\n }\n }\n\n return null;\n }\n}\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid;\n\nimport android.app.IntentService;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.net.Uri;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport org.fdroid.fdroid.data.Apk;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.InstalledAppProviderService;\nimport org.fdroid.fdroid.installer.ApkCache;\nimport org.fdroid.fdroid.installer.InstallManagerService;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\n\/**\n * Scans the list of downloaded .apk files in the cache for each app which can be updated.\n * If a valid .apk file is found then it will tell the {@link AppUpdateStatusManager} that it is\n * {@link AppUpdateStatusManager.Status#ReadyToInstall}. This is an {@link IntentService} so as to\n * run on a background thread, as it hits the disk a bit to figure out the hash of each downloaded\n * file.\n *\/\n@SuppressWarnings(\"LineLength\")\npublic class AppUpdateStatusService extends IntentService {\n\n private static final String TAG = \"AppUpdateStatusService\";\n\n \/**\n * Queue up a background scan of all downloaded apk files to see if we should notify the user\n * that they are ready to install.\n *\/\n public static void scanDownloadedApks(Context context) {\n context.startService(new Intent(context, AppUpdateStatusService.class));\n }\n\n public AppUpdateStatusService() {\n super(\"AppUpdateStatusService\");\n }\n\n @Override\n protected void onHandleIntent(@Nullable Intent intent) {\n Utils.debugLog(TAG, \"Scanning apk cache to see if we need to prompt the user to install any apks.\");\n File cacheDir = ApkCache.getApkCacheDir(this);\n if (cacheDir == null) {\n return;\n }\n String[] cacheDirList = cacheDir.list();\n if (cacheDirList == null) {\n return;\n }\n List apksReadyToInstall = new ArrayList<>();\n for (String repoDirName : cacheDirList) {\n File repoDir = new File(cacheDir, repoDirName);\n String[] apks = repoDir.list();\n if (apks == null) {\n continue;\n }\n for (String apkFileName : apks) {\n Apk apk = processDownloadedApk(new File(repoDir, apkFileName));\n if (apk != null) {\n Log.i(TAG, \"Found downloaded apk \" + apk.packageName + \". Notifying user that it should be installed.\");\n apksReadyToInstall.add(apk);\n }\n }\n }\n\n if (apksReadyToInstall.size() > 0) {\n AppUpdateStatusManager.getInstance(this).addApks(apksReadyToInstall, AppUpdateStatusManager.Status.ReadyToInstall);\n InstallManagerService.managePreviouslyDownloadedApks(this);\n }\n }\n\n \/**\n * Verifies that {@param apkPath} is a valid apk which the user intends to install.\n * If it is corrupted to the point where {@link PackageManager} can't read it, doesn't match the hash of any apk\n * we know about in our database, is not pending install, or is already installed, then it will return null.\n *\/\n @Nullable\n private Apk processDownloadedApk(File apkPath) {\n Utils.debugLog(TAG, \"Checking \" + apkPath);\n PackageInfo downloadedInfo = getPackageManager().getPackageArchiveInfo(apkPath.getAbsolutePath(), PackageManager.GET_GIDS);\n if (downloadedInfo == null) {\n Log.i(TAG, \"Skipping \" + apkPath + \" because PackageManager was unable to read it.\");\n return null;\n }\n\n Utils.debugLog(TAG, \"Found package for \" + downloadedInfo.packageName + \", checking its hash to see if it downloaded correctly.\");\n Apk downloadedApk = findApkMatchingHash(apkPath);\n if (downloadedApk == null) {\n Log.i(TAG, \"Either the apk wasn't downloaded fully, or the repo it came from has been disabled. Either way, not notifying the user about it.\");\n return null;\n }\n\n if (!AppUpdateStatusManager.getInstance(this).isPendingInstall(downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is NOT pending install, probably just left over from a previous install.\");\n return null;\n }\n\n try {\n PackageInfo info = getPackageManager().getPackageInfo(downloadedApk.packageName, 0);\n File pathToInstalled = InstalledAppProviderService.getPathToInstalledApk(info);\n if (pathToInstalled != null && pathToInstalled.canRead() &&\n TextUtils.equals(Utils.getBinaryHash(pathToInstalled, \"sha256\"), downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is pending install, but we already have the correct version installed.\");\n AppUpdateStatusManager.getInstance(this).markAsNoLongerPendingInstall(downloadedApk.getUrl());\n return null;\n }\n } catch (PackageManager.NameNotFoundException ignored) { }\n\n Utils.debugLog(TAG, downloadedApk.packageName + \" is pending install, so we need to notify the user about installing it.\");\n return downloadedApk;\n }\n\n \/**\n * There could be multiple apks with the same hash, provided by different repositories.\n * This method looks for all matching records in the database. It then asks each of these\n * {@link Apk} instances where they expect to be downloaded. If they expect to be downloaded\n * to {@param apkPath} then that instance is returned.\n *\n * If no files have a matching hash, or only those which don't belong to the correct repo, then\n * this will return null.\n *\/\n @Nullable\n private Apk findApkMatchingHash(File apkPath) {\n\n \/\/ NOTE: This presumes SHA256 is the only supported hash. It seems like that is an assumption\n \/\/ in more than one place in the F-Droid client. If this becomes a problem in the future, we\n \/\/ can query the Apk table for `SELECT DISTINCT hashType FROM fdroid_apk` and then we can just\n \/\/ try each of the hash types that have been specified in the metadata. Seems a bit overkill\n \/\/ at the time of writing though.\n String hash = Utils.getBinaryHash(apkPath, \"sha256\");\n\n List apksMatchingHash = ApkProvider.Helper.findApksByHash(this, hash);\n Utils.debugLog(TAG, \"Found \" + apksMatchingHash.size() + \" apk(s) matching the hash \" + hash);\n\n for (Apk apk : apksMatchingHash) {\n if (apkPath.equals(ApkCache.getApkDownloadPath(this, Uri.parse(apk.getUrl())))) {\n return apk;\n }\n }\n\n return null;\n }\n}\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite processDownloadedApk function to improve execution time. Write the entire code and no other text in the response.\n\n### Concepts:\n[in] processDownloadedApk function\n[hint] Check file size first before checking hash to save cycles.\n\n### Given program:\n```java\npackage org.fdroid.fdroid;\n\nimport android.app.IntentService;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.net.Uri;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport org.fdroid.fdroid.data.Apk;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.InstalledAppProviderService;\nimport org.fdroid.fdroid.installer.ApkCache;\nimport org.fdroid.fdroid.installer.InstallManagerService;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\n\/**\n * Scans the list of downloaded .apk files in the cache for each app which can be updated.\n * If a valid .apk file is found then it will tell the {@link AppUpdateStatusManager} that it is\n * {@link AppUpdateStatusManager.Status#ReadyToInstall}. This is an {@link IntentService} so as to\n * run on a background thread, as it hits the disk a bit to figure out the hash of each downloaded\n * file.\n *\/\n@SuppressWarnings(\"LineLength\")\npublic class AppUpdateStatusService extends IntentService {\n\n private static final String TAG = \"AppUpdateStatusService\";\n\n \/**\n * Queue up a background scan of all downloaded apk files to see if we should notify the user\n * that they are ready to install.\n *\/\n public static void scanDownloadedApks(Context context) {\n context.startService(new Intent(context, AppUpdateStatusService.class));\n }\n\n public AppUpdateStatusService() {\n super(\"AppUpdateStatusService\");\n }\n\n @Override\n protected void onHandleIntent(@Nullable Intent intent) {\n Utils.debugLog(TAG, \"Scanning apk cache to see if we need to prompt the user to install any apks.\");\n File cacheDir = ApkCache.getApkCacheDir(this);\n if (cacheDir == null) {\n return;\n }\n String[] cacheDirList = cacheDir.list();\n if (cacheDirList == null) {\n return;\n }\n List apksReadyToInstall = new ArrayList<>();\n for (String repoDirName : cacheDirList) {\n File repoDir = new File(cacheDir, repoDirName);\n String[] apks = repoDir.list();\n if (apks == null) {\n continue;\n }\n for (String apkFileName : apks) {\n Apk apk = processDownloadedApk(new File(repoDir, apkFileName));\n if (apk != null) {\n Log.i(TAG, \"Found downloaded apk \" + apk.packageName + \". Notifying user that it should be installed.\");\n apksReadyToInstall.add(apk);\n }\n }\n }\n\n if (apksReadyToInstall.size() > 0) {\n AppUpdateStatusManager.getInstance(this).addApks(apksReadyToInstall, AppUpdateStatusManager.Status.ReadyToInstall);\n InstallManagerService.managePreviouslyDownloadedApks(this);\n }\n }\n\n \/**\n * Verifies that {@param apkPath} is a valid apk which the user intends to install.\n * If it is corrupted to the point where {@link PackageManager} can't read it, doesn't match the hash of any apk\n * we know about in our database, is not pending install, or is already installed, then it will return null.\n *\/\n @Nullable\n private Apk processDownloadedApk(File apkPath) {\n Utils.debugLog(TAG, \"Checking \" + apkPath);\n PackageInfo downloadedInfo = getPackageManager().getPackageArchiveInfo(apkPath.getAbsolutePath(), PackageManager.GET_GIDS);\n if (downloadedInfo == null) {\n Log.i(TAG, \"Skipping \" + apkPath + \" because PackageManager was unable to read it.\");\n return null;\n }\n\n Utils.debugLog(TAG, \"Found package for \" + downloadedInfo.packageName + \", checking its hash to see if it downloaded correctly.\");\n Apk downloadedApk = findApkMatchingHash(apkPath);\n if (downloadedApk == null) {\n Log.i(TAG, \"Either the apk wasn't downloaded fully, or the repo it came from has been disabled. Either way, not notifying the user about it.\");\n return null;\n }\n\n if (!AppUpdateStatusManager.getInstance(this).isPendingInstall(downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is NOT pending install, probably just left over from a previous install.\");\n return null;\n }\n\n try {\n PackageInfo info = getPackageManager().getPackageInfo(downloadedApk.packageName, 0);\n File pathToInstalled = InstalledAppProviderService.getPathToInstalledApk(info);\n if (pathToInstalled != null && pathToInstalled.canRead() &&\n TextUtils.equals(Utils.getBinaryHash(pathToInstalled, \"sha256\"), downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is pending install, but we already have the correct version installed.\");\n AppUpdateStatusManager.getInstance(this).markAsNoLongerPendingInstall(downloadedApk.getUrl());\n return null;\n }\n } catch (PackageManager.NameNotFoundException ignored) { }\n\n Utils.debugLog(TAG, downloadedApk.packageName + \" is pending install, so we need to notify the user about installing it.\");\n return downloadedApk;\n }\n\n \/**\n * There could be multiple apks with the same hash, provided by different repositories.\n * This method looks for all matching records in the database. It then asks each of these\n * {@link Apk} instances where they expect to be downloaded. If they expect to be downloaded\n * to {@param apkPath} then that instance is returned.\n *\n * If no files have a matching hash, or only those which don't belong to the correct repo, then\n * this will return null.\n *\/\n @Nullable\n private Apk findApkMatchingHash(File apkPath) {\n\n \/\/ NOTE: This presumes SHA256 is the only supported hash. It seems like that is an assumption\n \/\/ in more than one place in the F-Droid client. If this becomes a problem in the future, we\n \/\/ can query the Apk table for `SELECT DISTINCT hashType FROM fdroid_apk` and then we can just\n \/\/ try each of the hash types that have been specified in the metadata. Seems a bit overkill\n \/\/ at the time of writing though.\n String hash = Utils.getBinaryHash(apkPath, \"sha256\");\n\n List apksMatchingHash = ApkProvider.Helper.findApksByHash(this, hash);\n Utils.debugLog(TAG, \"Found \" + apksMatchingHash.size() + \" apk(s) matching the hash \" + hash);\n\n for (Apk apk : apksMatchingHash) {\n if (apkPath.equals(ApkCache.getApkDownloadPath(this, Uri.parse(apk.getUrl())))) {\n return apk;\n }\n }\n\n return null;\n }\n}\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.compat.LayoutCompat;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n\n boolean compact = Preferences.get().hasCompactLayout();\n DB.App app = items.get(position);\n\n if (convertView == null) {\n convertView = ((LayoutInflater) mContext.getSystemService(\n Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.applistitem, null);\n }\n\n TextView name = (TextView) convertView.findViewById(R.id.name);\n TextView summary = (TextView) convertView.findViewById(R.id.summary);\n TextView status = (TextView) convertView.findViewById(R.id.status);\n TextView license = (TextView) convertView.findViewById(R.id.license);\n ImageView icon = (ImageView) convertView.findViewById(R.id.icon);\n LinearLayout iconContainer = (LinearLayout)convertView.findViewById(R.id.status_icons);\n ImageView iconInstalled = (ImageView) convertView.findViewById(R.id.icon_status_installed);\n ImageView iconUpdates = (ImageView) convertView.findViewById(R.id.icon_status_has_updates);\n\n name.setText(app.name);\n summary.setText(app.summary);\n\n layoutSummary(summary);\n layoutIcon(icon, app);\n\n int visibleOnCompact = compact ? View.VISIBLE : View.GONE;\n int notVisibleOnCompact = compact ? View.GONE : View.VISIBLE;\n\n iconContainer.setVisibility(visibleOnCompact);\n status.setVisibility(notVisibleOnCompact);\n license.setVisibility(notVisibleOnCompact);\n\n if (!compact) {\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n } else {\n status.setText(\"\");\n license.setText(\"\");\n\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setVisibility(View.VISIBLE);\n } else {\n iconUpdates.setVisibility(View.GONE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setVisibility(View.VISIBLE);\n } else {\n iconInstalled.setVisibility(View.GONE);\n }\n }\n\n \/\/ Disable it all if it isn't compatible...\n if (!app.compatible) {\n View[] views = { convertView, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(false);\n }\n }\n\n return convertView;\n }\n\n \/**\n * If an icon exists on disc, we'll use that, otherwise default to the\n * plain android app icon.\n *\/\n private void layoutIcon(ImageView iconView, DB.App app) {\n\n File icn = new File(DB.getIconsPath(mContext), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n iconView.setImageURI(Uri.parse(icn.getPath()));\n } else {\n iconView.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n }\n\n \/**\n * In compact view, the summary sites next to the icon, below the name.\n * In non-compact view, it sits under the icon, with some padding pushing\n * it away from the left margin.\n *\/\n private void layoutSummary(TextView summaryView) {\n\n if (Preferences.get().hasCompactLayout()) {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(LayoutCompat.RelativeLayout.END_OF, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n summaryView.setPadding(0,0,0,0);\n\n } else {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.MATCH_PARENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n float padding = mContext.getResources().getDimension(R.dimen.applist_summary_padding);\n summaryView.setPadding((int)padding, 0, 0, 0);\n\n }\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n\n\nCode-B:\npackage org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.compat.LayoutCompat;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n\n boolean compact = Preferences.get().hasCompactLayout();\n DB.App app = items.get(position);\n\n if (convertView == null) {\n convertView = ((LayoutInflater) mContext.getSystemService(\n Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.applistitem, null);\n }\n\n TextView name = (TextView) convertView.findViewById(R.id.name);\n TextView summary = (TextView) convertView.findViewById(R.id.summary);\n TextView status = (TextView) convertView.findViewById(R.id.status);\n TextView license = (TextView) convertView.findViewById(R.id.license);\n ImageView icon = (ImageView) convertView.findViewById(R.id.icon);\n LinearLayout iconContainer = (LinearLayout)convertView.findViewById(R.id.status_icons);\n ImageView iconInstalled = (ImageView) convertView.findViewById(R.id.icon_status_installed);\n ImageView iconUpdates = (ImageView) convertView.findViewById(R.id.icon_status_has_updates);\n\n name.setText(app.name);\n summary.setText(app.summary);\n\n layoutSummary(summary);\n layoutIcon(icon, app);\n\n int visibleOnCompact = compact ? View.VISIBLE : View.GONE;\n int notVisibleOnCompact = compact ? View.GONE : View.VISIBLE;\n\n iconContainer.setVisibility(visibleOnCompact);\n status.setVisibility(notVisibleOnCompact);\n license.setVisibility(notVisibleOnCompact);\n\n if (!compact) {\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n } else {\n status.setText(\"\");\n license.setText(\"\");\n\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setVisibility(View.VISIBLE);\n } else {\n iconUpdates.setVisibility(View.GONE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setVisibility(View.VISIBLE);\n } else {\n iconInstalled.setVisibility(View.GONE);\n }\n }\n\n \/\/ Disable it all if it isn't compatible...\n View[] views = { convertView, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(app.compatible);\n }\n\n return convertView;\n }\n\n \/**\n * If an icon exists on disc, we'll use that, otherwise default to the\n * plain android app icon.\n *\/\n private void layoutIcon(ImageView iconView, DB.App app) {\n\n File icn = new File(DB.getIconsPath(mContext), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n iconView.setImageURI(Uri.parse(icn.getPath()));\n } else {\n iconView.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n }\n\n \/**\n * In compact view, the summary sites next to the icon, below the name.\n * In non-compact view, it sits under the icon, with some padding pushing\n * it away from the left margin.\n *\/\n private void layoutSummary(TextView summaryView) {\n\n if (Preferences.get().hasCompactLayout()) {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(LayoutCompat.RelativeLayout.END_OF, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n summaryView.setPadding(0,0,0,0);\n\n } else {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.MATCH_PARENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n float padding = mContext.getResources().getDimension(R.dimen.applist_summary_padding);\n summaryView.setPadding((int)padding, 0, 0, 0);\n\n }\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.compat.LayoutCompat;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n\n boolean compact = Preferences.get().hasCompactLayout();\n DB.App app = items.get(position);\n\n if (convertView == null) {\n convertView = ((LayoutInflater) mContext.getSystemService(\n Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.applistitem, null);\n }\n\n TextView name = (TextView) convertView.findViewById(R.id.name);\n TextView summary = (TextView) convertView.findViewById(R.id.summary);\n TextView status = (TextView) convertView.findViewById(R.id.status);\n TextView license = (TextView) convertView.findViewById(R.id.license);\n ImageView icon = (ImageView) convertView.findViewById(R.id.icon);\n LinearLayout iconContainer = (LinearLayout)convertView.findViewById(R.id.status_icons);\n ImageView iconInstalled = (ImageView) convertView.findViewById(R.id.icon_status_installed);\n ImageView iconUpdates = (ImageView) convertView.findViewById(R.id.icon_status_has_updates);\n\n name.setText(app.name);\n summary.setText(app.summary);\n\n layoutSummary(summary);\n layoutIcon(icon, app);\n\n int visibleOnCompact = compact ? View.VISIBLE : View.GONE;\n int notVisibleOnCompact = compact ? View.GONE : View.VISIBLE;\n\n iconContainer.setVisibility(visibleOnCompact);\n status.setVisibility(notVisibleOnCompact);\n license.setVisibility(notVisibleOnCompact);\n\n if (!compact) {\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n } else {\n status.setText(\"\");\n license.setText(\"\");\n\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setVisibility(View.VISIBLE);\n } else {\n iconUpdates.setVisibility(View.GONE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setVisibility(View.VISIBLE);\n } else {\n iconInstalled.setVisibility(View.GONE);\n }\n }\n\n \/\/ Disable it all if it isn't compatible...\n View[] views = { convertView, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(app.compatible);\n }\n\n return convertView;\n }\n\n \/**\n * If an icon exists on disc, we'll use that, otherwise default to the\n * plain android app icon.\n *\/\n private void layoutIcon(ImageView iconView, DB.App app) {\n\n File icn = new File(DB.getIconsPath(mContext), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n iconView.setImageURI(Uri.parse(icn.getPath()));\n } else {\n iconView.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n }\n\n \/**\n * In compact view, the summary sites next to the icon, below the name.\n * In non-compact view, it sits under the icon, with some padding pushing\n * it away from the left margin.\n *\/\n private void layoutSummary(TextView summaryView) {\n\n if (Preferences.get().hasCompactLayout()) {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(LayoutCompat.RelativeLayout.END_OF, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n summaryView.setPadding(0,0,0,0);\n\n } else {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.MATCH_PARENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n float padding = mContext.getResources().getDimension(R.dimen.applist_summary_padding);\n summaryView.setPadding((int)padding, 0, 0, 0);\n\n }\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n\n\nCode-B:\npackage org.fdroid.fdroid.views;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.content.Context;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.content.SharedPreferences;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.*;\nimport org.fdroid.fdroid.DB;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.compat.LayoutCompat;\n\nabstract public class AppListAdapter extends BaseAdapter {\n\n private List items = new ArrayList();\n private Context mContext;\n\n public AppListAdapter(Context context) {\n mContext = context;\n }\n\n abstract protected boolean showStatusUpdate();\n\n abstract protected boolean showStatusInstalled();\n\n public void addItem(DB.App app) {\n items.add(app);\n }\n\n public void clear() {\n items.clear();\n }\n\n @Override\n public int getCount() {\n return items.size();\n }\n\n @Override\n public Object getItem(int position) {\n return items.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n\n boolean compact = Preferences.get().hasCompactLayout();\n DB.App app = items.get(position);\n\n if (convertView == null) {\n convertView = ((LayoutInflater) mContext.getSystemService(\n Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.applistitem, null);\n }\n\n TextView name = (TextView) convertView.findViewById(R.id.name);\n TextView summary = (TextView) convertView.findViewById(R.id.summary);\n TextView status = (TextView) convertView.findViewById(R.id.status);\n TextView license = (TextView) convertView.findViewById(R.id.license);\n ImageView icon = (ImageView) convertView.findViewById(R.id.icon);\n LinearLayout iconContainer = (LinearLayout)convertView.findViewById(R.id.status_icons);\n ImageView iconInstalled = (ImageView) convertView.findViewById(R.id.icon_status_installed);\n ImageView iconUpdates = (ImageView) convertView.findViewById(R.id.icon_status_has_updates);\n\n name.setText(app.name);\n summary.setText(app.summary);\n\n layoutSummary(summary);\n layoutIcon(icon, app);\n\n int visibleOnCompact = compact ? View.VISIBLE : View.GONE;\n int notVisibleOnCompact = compact ? View.GONE : View.VISIBLE;\n\n iconContainer.setVisibility(visibleOnCompact);\n status.setVisibility(notVisibleOnCompact);\n license.setVisibility(notVisibleOnCompact);\n\n if (!compact) {\n status.setText(getVersionInfo(app));\n license.setText(app.license);\n } else {\n status.setText(\"\");\n license.setText(\"\");\n\n iconInstalled.setImageResource(R.drawable.ic_cab_done_holo_dark);\n iconUpdates.setImageResource(R.drawable.ic_menu_refresh);\n\n if (app.hasUpdates && showStatusUpdate()) {\n iconUpdates.setVisibility(View.VISIBLE);\n } else {\n iconUpdates.setVisibility(View.GONE);\n }\n\n if (app.installedVerCode > 0 && showStatusInstalled()) {\n iconInstalled.setVisibility(View.VISIBLE);\n } else {\n iconInstalled.setVisibility(View.GONE);\n }\n }\n\n \/\/ Disable it all if it isn't compatible...\n if (!app.compatible) {\n View[] views = { convertView, status, summary, license, name };\n for (View view : views) {\n view.setEnabled(false);\n }\n }\n\n return convertView;\n }\n\n \/**\n * If an icon exists on disc, we'll use that, otherwise default to the\n * plain android app icon.\n *\/\n private void layoutIcon(ImageView iconView, DB.App app) {\n\n File icn = new File(DB.getIconsPath(mContext), app.icon);\n if (icn.exists() && icn.length() > 0) {\n new Uri.Builder().build();\n iconView.setImageURI(Uri.parse(icn.getPath()));\n } else {\n iconView.setImageResource(android.R.drawable.sym_def_app_icon);\n }\n\n }\n\n \/**\n * In compact view, the summary sites next to the icon, below the name.\n * In non-compact view, it sits under the icon, with some padding pushing\n * it away from the left margin.\n *\/\n private void layoutSummary(TextView summaryView) {\n\n if (Preferences.get().hasCompactLayout()) {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.WRAP_CONTENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.name);\n summaryLayout.addRule(LayoutCompat.RelativeLayout.END_OF, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n summaryView.setPadding(0,0,0,0);\n\n } else {\n\n RelativeLayout.LayoutParams summaryLayout =\n new RelativeLayout.LayoutParams(\n RelativeLayout.LayoutParams.MATCH_PARENT,\n RelativeLayout.LayoutParams.WRAP_CONTENT);\n summaryLayout.addRule(RelativeLayout.BELOW, R.id.icon);\n summaryView.setLayoutParams(summaryLayout);\n float padding = mContext.getResources().getDimension(R.dimen.applist_summary_padding);\n summaryView.setPadding((int)padding, 0, 0, 0);\n\n }\n }\n\n private String getVersionInfo(DB.App app) {\n StringBuilder version = new StringBuilder();\n if (app.installedVersion != null) {\n version.append(app.installedVersion);\n if (app.hasUpdates) {\n version.append(\" -> \");\n version.append(app.updateVersion);\n }\n } else {\n int numav = app.apks.size();\n String numVersions;\n if (numav == 1)\n numVersions = mContext.getString(R.string.n_version_available);\n else\n numVersions = mContext.getString(R.string.n_versions_available);\n version.append(String.format(numVersions, numav));\n }\n return version.toString();\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/PaperAirplane-Dev-Team\/GigaGet\/commit\/29f86e6847d48c7521caba7e2019e4a744e1faa2","commit_message":"'\\\\\"BrowserActivity: Optimize input method\\\\\"'","source_code":"package us.shandian.giga.ui.web;\n\nimport android.app.AlertDialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.ContextThemeWrapper;\nimport android.view.KeyEvent;\nimport android.view.LayoutInflater;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.webkit.DownloadListener;\nimport android.webkit.JavascriptInterface;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.EditText;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\n\nimport android.support.v7.app.ActionBar;\n\nimport java.util.ArrayList;\nimport java.util.regex.Pattern;\nimport java.util.regex.Matcher;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.ui.common.ToolbarActivity;\nimport us.shandian.giga.ui.main.MainActivity;\nimport us.shandian.giga.util.Utility;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class BrowserActivity extends ToolbarActivity\n{\n\tprivate WebView mWeb;\n\tprivate ProgressBar mProgress;\n\tprivate EditText mUrl;\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\t\n\t\t\/\/ Toolbar\n\t\tgetSupportActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowHomeEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\n\t\t\/\/ Custom view\n\t\tif (Build.VERSION.SDK_INT < 21) {\n\t\t\tContextThemeWrapper wrap = new ContextThemeWrapper(this, R.style.Theme_AppCompat);\n\t\t\tLayoutInflater inflater = (LayoutInflater) wrap.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n\t\t\tView custom = inflater.inflate(R.layout.browser_url, null);\n\t\t\tgetSupportActionBar().setCustomView(custom);\n\t\t} else {\n\t\t\tgetSupportActionBar().setCustomView(R.layout.browser_url);\n\t\t}\n\t\t\n\t\t\/\/ Initialize WebView\n\t\tmProgress = Utility.findViewById(this, R.id.progress);\n\t\tmUrl = Utility.findViewById(getSupportActionBar().getCustomView(), R.id.browser_url);\n\t\tmWeb = Utility.findViewById(this, R.id.web);\n\t\tmWeb.setWebViewClient(new WebViewClient() {\n\t\t\t@Override\n\t\t\tpublic boolean shouldOverrideUrlLoading(WebView view, String url) {\n\t\t\t\tview.loadUrl(url);\n\t\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onPageFinished(WebView view, String url) {\n\t\t\t\tmProgress.setProgress(0);\n\t\t\t}\n\t\t});\n\t\tmWeb.setWebChromeClient(new WebChromeClient() {\n\t\t\t@Override\n\t\t\tpublic void onProgressChanged(WebView v, int progress) {\n\t\t\t\tmProgress.setProgress(progress);\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onReceivedTitle(WebView v, String title) {\n\t\t\t\tgetSupportActionBar().setTitle(title);\n\t\t\t}\n\t\t});\n\t\tmWeb.getSettings().setJavaScriptEnabled(true);\n\t\tmWeb.setDownloadListener(new DownloadListener() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {\n\t\t\t\t\t\/\/ Start MainActivity for downloading\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(url), mimeType);\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t\n\t\t});\n\t\tmUrl.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n\t\t\t@Override\n\t\t\tpublic boolean onEditorAction(TextView v, int actionId, KeyEvent ev) {\n\t\t\t\t\tif (actionId == EditorInfo.IME_ACTION_GO) {\n\t\t\t\t\t\tString url = mUrl.getText().toString();\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!url.startsWith(\"http\")) {\n\t\t\t\t\t\t\turl = \"http:\/\/\" + url;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tmWeb.loadUrl(url);\n\t\t\t\t\t\tswitchCustom();\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t});\n\t\tmWeb.addJavascriptInterface(new MyJavascriptInterface(), \"HTMLOUT\");\n\t\t\n\t\tmWeb.loadUrl(\"about:blank\");\n\t\t\n\t\tswitchCustom();\n\t\t\n\t\tmToolbar.setOnClickListener(new View.OnClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tswitchCustom();\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tprotected int getLayoutResource() {\n\t\treturn R.layout.browser;\n\t}\n\n\t@Override\n\tpublic boolean onCreateOptionsMenu(Menu menu) {\n\t\tgetMenuInflater().inflate(R.menu.browser, menu);\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tswitch (item.getItemId()) {\n\t\t\tcase android.R.id.home:\n\t\t\t\tfinish();\n\t\t\t\treturn true;\n\t\t\tcase R.id.detector:\n\t\t\t\tmWeb.loadUrl(\"javascript:window.HTMLOUT.processHTML(''+document.getElementsByTagName('html')[0].innerHTML+'<\/head>');\");\n\t\t\t\treturn true;\n\t\t\tdefault:\n\t\t\t\treturn super.onOptionsItemSelected(item);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onBackPressed() {\n\t\tif (mWeb.canGoBack()) {\n\t\t\tmWeb.goBack();\n\t\t} else {\n\t\t\tfinish();\n\t\t}\n\t}\n\t\n\tprivate void switchCustom() {\n\t\tint opt = getSupportActionBar().getDisplayOptions();\n\t\t\n\t\tif ((opt & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t} else {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(true);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\tmUrl.setText(mWeb.getUrl());\n\t\t\tmUrl.setSelection(0, mUrl.getText().length());\n\t\t}\n\t}\n\t\n\tprivate void showVideoChoices(final String[] vids) {\n\t\tnew AlertDialog.Builder(this)\n\t\t\t.setItems(vids, new DialogInterface.OnClickListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(vids[id]), \"application\/octet-stream\");\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t})\n\t\t\t.show();\n\t}\n\t\n\tclass MyJavascriptInterface {\n\t\tprivate static final String TAG = MyJavascriptInterface.class.getSimpleName();\n\t\t\n\t\tprivate static final String PATTERN = \"[http|https]+[:\/\/]+[0-9A-Za-z:\/[-]_#[?][=][.][&]]*\";\n\t\tprivate static final String[] VIDEO_SUFFIXES = new String[]{\n\t\t\t\".mp4\",\n\t\t\t\".flv\",\n\t\t\t\".rm\",\n\t\t\t\".rmvb\",\n\t\t\t\".wmv\",\n\t\t\t\".avi\",\n\t\t\t\".mkv\",\n\t\t\t\".webm\"\n\t\t};\n\t\t\n\t\t@JavascriptInterface\n\t\tpublic void processHTML(String html) {\n\t\t\tPattern pattern = Pattern.compile(PATTERN);\n\t\t\tMatcher matcher = pattern.matcher(html);\n\t\t\t\n\t\t\tArrayList vid = new ArrayList();\n\t\t\t\n\t\t\twhile (matcher.find()) {\n\t\t\t\tString url = matcher.group();\n\t\t\t\t\n\t\t\t\tboolean isVid = false;\n\t\t\t\t\n\t\t\t\tfor (String suffix : VIDEO_SUFFIXES) {\n\t\t\t\t\tif (url.contains(suffix)) {\n\t\t\t\t\t\tisVid = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (isVid) {\n\t\t\t\t\t\n\t\t\t\t\tvid.add(url);\n\t\t\t\t\t\n\t\t\t\t\tif (DEBUG) {\n\t\t\t\t\t\tLog.d(TAG, \"found url:\" + url);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (vid.size() == 0) return;\n\t\t\t\n\t\t\tString[] arr = new String[vid.size()];\n\t\t\tshowVideoChoices(vid.toArray(arr));\n\t\t}\n\t}\n}\n","target_code":"package us.shandian.giga.ui.web;\n\nimport android.app.AlertDialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.ContextThemeWrapper;\nimport android.view.KeyEvent;\nimport android.view.LayoutInflater;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.view.inputmethod.InputMethodManager;\nimport android.webkit.DownloadListener;\nimport android.webkit.JavascriptInterface;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.EditText;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\n\nimport android.support.v7.app.ActionBar;\n\nimport java.util.ArrayList;\nimport java.util.regex.Pattern;\nimport java.util.regex.Matcher;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.ui.common.ToolbarActivity;\nimport us.shandian.giga.ui.main.MainActivity;\nimport us.shandian.giga.util.Utility;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class BrowserActivity extends ToolbarActivity\n{\n\tprivate WebView mWeb;\n\tprivate ProgressBar mProgress;\n\tprivate EditText mUrl;\n\tprivate InputMethodManager mInput;\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\t\n\t\tmInput = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);\n\t\t\n\t\t\/\/ Toolbar\n\t\tgetSupportActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowHomeEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\n\t\t\/\/ Custom view\n\t\tif (Build.VERSION.SDK_INT < 21) {\n\t\t\tContextThemeWrapper wrap = new ContextThemeWrapper(this, R.style.Theme_AppCompat);\n\t\t\tLayoutInflater inflater = (LayoutInflater) wrap.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n\t\t\tView custom = inflater.inflate(R.layout.browser_url, null);\n\t\t\tgetSupportActionBar().setCustomView(custom);\n\t\t} else {\n\t\t\tgetSupportActionBar().setCustomView(R.layout.browser_url);\n\t\t}\n\t\t\n\t\t\/\/ Initialize WebView\n\t\tmProgress = Utility.findViewById(this, R.id.progress);\n\t\tmUrl = Utility.findViewById(getSupportActionBar().getCustomView(), R.id.browser_url);\n\t\tmWeb = Utility.findViewById(this, R.id.web);\n\t\tmWeb.setWebViewClient(new WebViewClient() {\n\t\t\t@Override\n\t\t\tpublic boolean shouldOverrideUrlLoading(WebView view, String url) {\n\t\t\t\tview.loadUrl(url);\n\t\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t\t\tmInput.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onPageFinished(WebView view, String url) {\n\t\t\t\tmProgress.setProgress(0);\n\t\t\t}\n\t\t});\n\t\tmWeb.setWebChromeClient(new WebChromeClient() {\n\t\t\t@Override\n\t\t\tpublic void onProgressChanged(WebView v, int progress) {\n\t\t\t\tmProgress.setProgress(progress);\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onReceivedTitle(WebView v, String title) {\n\t\t\t\tgetSupportActionBar().setTitle(title);\n\t\t\t}\n\t\t});\n\t\tmWeb.getSettings().setJavaScriptEnabled(true);\n\t\tmWeb.setDownloadListener(new DownloadListener() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {\n\t\t\t\t\t\/\/ Start MainActivity for downloading\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(url), mimeType);\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t\n\t\t});\n\t\tmUrl.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n\t\t\t@Override\n\t\t\tpublic boolean onEditorAction(TextView v, int actionId, KeyEvent ev) {\n\t\t\t\t\tif (actionId == EditorInfo.IME_ACTION_GO) {\n\t\t\t\t\t\tString url = mUrl.getText().toString();\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!url.startsWith(\"http\")) {\n\t\t\t\t\t\t\turl = \"http:\/\/\" + url;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tmWeb.loadUrl(url);\n\t\t\t\t\t\tswitchCustom();\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t});\n\t\tmWeb.addJavascriptInterface(new MyJavascriptInterface(), \"HTMLOUT\");\n\t\t\n\t\tmWeb.loadUrl(\"about:blank\");\n\t\t\n\t\tswitchCustom();\n\t\t\n\t\tmToolbar.setOnClickListener(new View.OnClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tswitchCustom();\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tprotected int getLayoutResource() {\n\t\treturn R.layout.browser;\n\t}\n\n\t@Override\n\tpublic boolean onCreateOptionsMenu(Menu menu) {\n\t\tgetMenuInflater().inflate(R.menu.browser, menu);\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tswitch (item.getItemId()) {\n\t\t\tcase android.R.id.home:\n\t\t\t\tfinish();\n\t\t\t\treturn true;\n\t\t\tcase R.id.detector:\n\t\t\t\tmWeb.loadUrl(\"javascript:window.HTMLOUT.processHTML(''+document.getElementsByTagName('html')[0].innerHTML+'<\/head>');\");\n\t\t\t\treturn true;\n\t\t\tdefault:\n\t\t\t\treturn super.onOptionsItemSelected(item);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onBackPressed() {\n\t\tif (mWeb.canGoBack()) {\n\t\t\tmWeb.goBack();\n\t\t} else {\n\t\t\tfinish();\n\t\t}\n\t}\n\t\n\tprivate void switchCustom() {\n\t\tint opt = getSupportActionBar().getDisplayOptions();\n\t\t\n\t\tif ((opt & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t\tmInput.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);\n\t\t} else {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(true);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\tmInput.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);\n\t\t\tmUrl.requestFocus();\n\t\t\tmUrl.setText(mWeb.getUrl());\n\t\t\tmUrl.setSelection(0, mUrl.getText().length());\n\t\t}\n\t}\n\t\n\tprivate void showVideoChoices(final String[] vids) {\n\t\tnew AlertDialog.Builder(this)\n\t\t\t.setItems(vids, new DialogInterface.OnClickListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(vids[id]), \"application\/octet-stream\");\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t})\n\t\t\t.show();\n\t}\n\t\n\tclass MyJavascriptInterface {\n\t\tprivate static final String TAG = MyJavascriptInterface.class.getSimpleName();\n\t\t\n\t\tprivate static final String PATTERN = \"[http|https]+[:\/\/]+[0-9A-Za-z:\/[-]_#[?][=][.][&]]*\";\n\t\tprivate static final String[] VIDEO_SUFFIXES = new String[]{\n\t\t\t\".mp4\",\n\t\t\t\".flv\",\n\t\t\t\".rm\",\n\t\t\t\".rmvb\",\n\t\t\t\".wmv\",\n\t\t\t\".avi\",\n\t\t\t\".mkv\",\n\t\t\t\".webm\"\n\t\t};\n\t\t\n\t\t@JavascriptInterface\n\t\tpublic void processHTML(String html) {\n\t\t\tPattern pattern = Pattern.compile(PATTERN);\n\t\t\tMatcher matcher = pattern.matcher(html);\n\t\t\t\n\t\t\tArrayList vid = new ArrayList();\n\t\t\t\n\t\t\twhile (matcher.find()) {\n\t\t\t\tString url = matcher.group();\n\t\t\t\t\n\t\t\t\tboolean isVid = false;\n\t\t\t\t\n\t\t\t\tfor (String suffix : VIDEO_SUFFIXES) {\n\t\t\t\t\tif (url.contains(suffix)) {\n\t\t\t\t\t\tisVid = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (isVid) {\n\t\t\t\t\t\n\t\t\t\t\tvid.add(url);\n\t\t\t\t\t\n\t\t\t\t\tif (DEBUG) {\n\t\t\t\t\t\tLog.d(TAG, \"found url:\" + url);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (vid.size() == 0) return;\n\t\t\t\n\t\t\tString[] arr = new String[vid.size()];\n\t\t\tshowVideoChoices(vid.toArray(arr));\n\t\t}\n\t}\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage us.shandian.giga.ui.web;\n\nimport android.app.AlertDialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.ContextThemeWrapper;\nimport android.view.KeyEvent;\nimport android.view.LayoutInflater;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.webkit.DownloadListener;\nimport android.webkit.JavascriptInterface;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.EditText;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\n\nimport android.support.v7.app.ActionBar;\n\nimport java.util.ArrayList;\nimport java.util.regex.Pattern;\nimport java.util.regex.Matcher;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.ui.common.ToolbarActivity;\nimport us.shandian.giga.ui.main.MainActivity;\nimport us.shandian.giga.util.Utility;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class BrowserActivity extends ToolbarActivity\n{\n\tprivate WebView mWeb;\n\tprivate ProgressBar mProgress;\n\tprivate EditText mUrl;\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\t\n\t\t\/\/ Toolbar\n\t\tgetSupportActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowHomeEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\n\t\t\/\/ Custom view\n\t\tif (Build.VERSION.SDK_INT < 21) {\n\t\t\tContextThemeWrapper wrap = new ContextThemeWrapper(this, R.style.Theme_AppCompat);\n\t\t\tLayoutInflater inflater = (LayoutInflater) wrap.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n\t\t\tView custom = inflater.inflate(R.layout.browser_url, null);\n\t\t\tgetSupportActionBar().setCustomView(custom);\n\t\t} else {\n\t\t\tgetSupportActionBar().setCustomView(R.layout.browser_url);\n\t\t}\n\t\t\n\t\t\/\/ Initialize WebView\n\t\tmProgress = Utility.findViewById(this, R.id.progress);\n\t\tmUrl = Utility.findViewById(getSupportActionBar().getCustomView(), R.id.browser_url);\n\t\tmWeb = Utility.findViewById(this, R.id.web);\n\t\tmWeb.setWebViewClient(new WebViewClient() {\n\t\t\t@Override\n\t\t\tpublic boolean shouldOverrideUrlLoading(WebView view, String url) {\n\t\t\t\tview.loadUrl(url);\n\t\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onPageFinished(WebView view, String url) {\n\t\t\t\tmProgress.setProgress(0);\n\t\t\t}\n\t\t});\n\t\tmWeb.setWebChromeClient(new WebChromeClient() {\n\t\t\t@Override\n\t\t\tpublic void onProgressChanged(WebView v, int progress) {\n\t\t\t\tmProgress.setProgress(progress);\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onReceivedTitle(WebView v, String title) {\n\t\t\t\tgetSupportActionBar().setTitle(title);\n\t\t\t}\n\t\t});\n\t\tmWeb.getSettings().setJavaScriptEnabled(true);\n\t\tmWeb.setDownloadListener(new DownloadListener() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {\n\t\t\t\t\t\/\/ Start MainActivity for downloading\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(url), mimeType);\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t\n\t\t});\n\t\tmUrl.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n\t\t\t@Override\n\t\t\tpublic boolean onEditorAction(TextView v, int actionId, KeyEvent ev) {\n\t\t\t\t\tif (actionId == EditorInfo.IME_ACTION_GO) {\n\t\t\t\t\t\tString url = mUrl.getText().toString();\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!url.startsWith(\"http\")) {\n\t\t\t\t\t\t\turl = \"http:\/\/\" + url;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tmWeb.loadUrl(url);\n\t\t\t\t\t\tswitchCustom();\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t});\n\t\tmWeb.addJavascriptInterface(new MyJavascriptInterface(), \"HTMLOUT\");\n\t\t\n\t\tmWeb.loadUrl(\"about:blank\");\n\t\t\n\t\tswitchCustom();\n\t\t\n\t\tmToolbar.setOnClickListener(new View.OnClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tswitchCustom();\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tprotected int getLayoutResource() {\n\t\treturn R.layout.browser;\n\t}\n\n\t@Override\n\tpublic boolean onCreateOptionsMenu(Menu menu) {\n\t\tgetMenuInflater().inflate(R.menu.browser, menu);\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tswitch (item.getItemId()) {\n\t\t\tcase android.R.id.home:\n\t\t\t\tfinish();\n\t\t\t\treturn true;\n\t\t\tcase R.id.detector:\n\t\t\t\tmWeb.loadUrl(\"javascript:window.HTMLOUT.processHTML(''+document.getElementsByTagName('html')[0].innerHTML+'<\/head>');\");\n\t\t\t\treturn true;\n\t\t\tdefault:\n\t\t\t\treturn super.onOptionsItemSelected(item);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onBackPressed() {\n\t\tif (mWeb.canGoBack()) {\n\t\t\tmWeb.goBack();\n\t\t} else {\n\t\t\tfinish();\n\t\t}\n\t}\n\t\n\tprivate void switchCustom() {\n\t\tint opt = getSupportActionBar().getDisplayOptions();\n\t\t\n\t\tif ((opt & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t} else {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(true);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\tmUrl.setText(mWeb.getUrl());\n\t\t\tmUrl.setSelection(0, mUrl.getText().length());\n\t\t}\n\t}\n\t\n\tprivate void showVideoChoices(final String[] vids) {\n\t\tnew AlertDialog.Builder(this)\n\t\t\t.setItems(vids, new DialogInterface.OnClickListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(vids[id]), \"application\/octet-stream\");\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t})\n\t\t\t.show();\n\t}\n\t\n\tclass MyJavascriptInterface {\n\t\tprivate static final String TAG = MyJavascriptInterface.class.getSimpleName();\n\t\t\n\t\tprivate static final String PATTERN = \"[http|https]+[:\/\/]+[0-9A-Za-z:\/[-]_#[?][=][.][&]]*\";\n\t\tprivate static final String[] VIDEO_SUFFIXES = new String[]{\n\t\t\t\".mp4\",\n\t\t\t\".flv\",\n\t\t\t\".rm\",\n\t\t\t\".rmvb\",\n\t\t\t\".wmv\",\n\t\t\t\".avi\",\n\t\t\t\".mkv\",\n\t\t\t\".webm\"\n\t\t};\n\t\t\n\t\t@JavascriptInterface\n\t\tpublic void processHTML(String html) {\n\t\t\tPattern pattern = Pattern.compile(PATTERN);\n\t\t\tMatcher matcher = pattern.matcher(html);\n\t\t\t\n\t\t\tArrayList vid = new ArrayList();\n\t\t\t\n\t\t\twhile (matcher.find()) {\n\t\t\t\tString url = matcher.group();\n\t\t\t\t\n\t\t\t\tboolean isVid = false;\n\t\t\t\t\n\t\t\t\tfor (String suffix : VIDEO_SUFFIXES) {\n\t\t\t\t\tif (url.contains(suffix)) {\n\t\t\t\t\t\tisVid = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (isVid) {\n\t\t\t\t\t\n\t\t\t\t\tvid.add(url);\n\t\t\t\t\t\n\t\t\t\t\tif (DEBUG) {\n\t\t\t\t\t\tLog.d(TAG, \"found url:\" + url);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (vid.size() == 0) return;\n\t\t\t\n\t\t\tString[] arr = new String[vid.size()];\n\t\t\tshowVideoChoices(vid.toArray(arr));\n\t\t}\n\t}\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage us.shandian.giga.ui.web;\n\nimport android.app.AlertDialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.ContextThemeWrapper;\nimport android.view.KeyEvent;\nimport android.view.LayoutInflater;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.webkit.DownloadListener;\nimport android.webkit.JavascriptInterface;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.EditText;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\n\nimport android.support.v7.app.ActionBar;\n\nimport java.util.ArrayList;\nimport java.util.regex.Pattern;\nimport java.util.regex.Matcher;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.ui.common.ToolbarActivity;\nimport us.shandian.giga.ui.main.MainActivity;\nimport us.shandian.giga.util.Utility;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class BrowserActivity extends ToolbarActivity\n{\n\tprivate WebView mWeb;\n\tprivate ProgressBar mProgress;\n\tprivate EditText mUrl;\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\t\n\t\t\/\/ Toolbar\n\t\tgetSupportActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowHomeEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\n\t\t\/\/ Custom view\n\t\tif (Build.VERSION.SDK_INT < 21) {\n\t\t\tContextThemeWrapper wrap = new ContextThemeWrapper(this, R.style.Theme_AppCompat);\n\t\t\tLayoutInflater inflater = (LayoutInflater) wrap.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n\t\t\tView custom = inflater.inflate(R.layout.browser_url, null);\n\t\t\tgetSupportActionBar().setCustomView(custom);\n\t\t} else {\n\t\t\tgetSupportActionBar().setCustomView(R.layout.browser_url);\n\t\t}\n\t\t\n\t\t\/\/ Initialize WebView\n\t\tmProgress = Utility.findViewById(this, R.id.progress);\n\t\tmUrl = Utility.findViewById(getSupportActionBar().getCustomView(), R.id.browser_url);\n\t\tmWeb = Utility.findViewById(this, R.id.web);\n\t\tmWeb.setWebViewClient(new WebViewClient() {\n\t\t\t@Override\n\t\t\tpublic boolean shouldOverrideUrlLoading(WebView view, String url) {\n\t\t\t\tview.loadUrl(url);\n\t\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onPageFinished(WebView view, String url) {\n\t\t\t\tmProgress.setProgress(0);\n\t\t\t}\n\t\t});\n\t\tmWeb.setWebChromeClient(new WebChromeClient() {\n\t\t\t@Override\n\t\t\tpublic void onProgressChanged(WebView v, int progress) {\n\t\t\t\tmProgress.setProgress(progress);\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onReceivedTitle(WebView v, String title) {\n\t\t\t\tgetSupportActionBar().setTitle(title);\n\t\t\t}\n\t\t});\n\t\tmWeb.getSettings().setJavaScriptEnabled(true);\n\t\tmWeb.setDownloadListener(new DownloadListener() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {\n\t\t\t\t\t\/\/ Start MainActivity for downloading\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(url), mimeType);\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t\n\t\t});\n\t\tmUrl.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n\t\t\t@Override\n\t\t\tpublic boolean onEditorAction(TextView v, int actionId, KeyEvent ev) {\n\t\t\t\t\tif (actionId == EditorInfo.IME_ACTION_GO) {\n\t\t\t\t\t\tString url = mUrl.getText().toString();\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!url.startsWith(\"http\")) {\n\t\t\t\t\t\t\turl = \"http:\/\/\" + url;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tmWeb.loadUrl(url);\n\t\t\t\t\t\tswitchCustom();\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t});\n\t\tmWeb.addJavascriptInterface(new MyJavascriptInterface(), \"HTMLOUT\");\n\t\t\n\t\tmWeb.loadUrl(\"about:blank\");\n\t\t\n\t\tswitchCustom();\n\t\t\n\t\tmToolbar.setOnClickListener(new View.OnClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tswitchCustom();\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tprotected int getLayoutResource() {\n\t\treturn R.layout.browser;\n\t}\n\n\t@Override\n\tpublic boolean onCreateOptionsMenu(Menu menu) {\n\t\tgetMenuInflater().inflate(R.menu.browser, menu);\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tswitch (item.getItemId()) {\n\t\t\tcase android.R.id.home:\n\t\t\t\tfinish();\n\t\t\t\treturn true;\n\t\t\tcase R.id.detector:\n\t\t\t\tmWeb.loadUrl(\"javascript:window.HTMLOUT.processHTML(''+document.getElementsByTagName('html')[0].innerHTML+'<\/head>');\");\n\t\t\t\treturn true;\n\t\t\tdefault:\n\t\t\t\treturn super.onOptionsItemSelected(item);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onBackPressed() {\n\t\tif (mWeb.canGoBack()) {\n\t\t\tmWeb.goBack();\n\t\t} else {\n\t\t\tfinish();\n\t\t}\n\t}\n\t\n\tprivate void switchCustom() {\n\t\tint opt = getSupportActionBar().getDisplayOptions();\n\t\t\n\t\tif ((opt & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t} else {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(true);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\tmUrl.setText(mWeb.getUrl());\n\t\t\tmUrl.setSelection(0, mUrl.getText().length());\n\t\t}\n\t}\n\t\n\tprivate void showVideoChoices(final String[] vids) {\n\t\tnew AlertDialog.Builder(this)\n\t\t\t.setItems(vids, new DialogInterface.OnClickListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(vids[id]), \"application\/octet-stream\");\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t})\n\t\t\t.show();\n\t}\n\t\n\tclass MyJavascriptInterface {\n\t\tprivate static final String TAG = MyJavascriptInterface.class.getSimpleName();\n\t\t\n\t\tprivate static final String PATTERN = \"[http|https]+[:\/\/]+[0-9A-Za-z:\/[-]_#[?][=][.][&]]*\";\n\t\tprivate static final String[] VIDEO_SUFFIXES = new String[]{\n\t\t\t\".mp4\",\n\t\t\t\".flv\",\n\t\t\t\".rm\",\n\t\t\t\".rmvb\",\n\t\t\t\".wmv\",\n\t\t\t\".avi\",\n\t\t\t\".mkv\",\n\t\t\t\".webm\"\n\t\t};\n\t\t\n\t\t@JavascriptInterface\n\t\tpublic void processHTML(String html) {\n\t\t\tPattern pattern = Pattern.compile(PATTERN);\n\t\t\tMatcher matcher = pattern.matcher(html);\n\t\t\t\n\t\t\tArrayList vid = new ArrayList();\n\t\t\t\n\t\t\twhile (matcher.find()) {\n\t\t\t\tString url = matcher.group();\n\t\t\t\t\n\t\t\t\tboolean isVid = false;\n\t\t\t\t\n\t\t\t\tfor (String suffix : VIDEO_SUFFIXES) {\n\t\t\t\t\tif (url.contains(suffix)) {\n\t\t\t\t\t\tisVid = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (isVid) {\n\t\t\t\t\t\n\t\t\t\t\tvid.add(url);\n\t\t\t\t\t\n\t\t\t\t\tif (DEBUG) {\n\t\t\t\t\t\tLog.d(TAG, \"found url:\" + url);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (vid.size() == 0) return;\n\t\t\t\n\t\t\tString[] arr = new String[vid.size()];\n\t\t\tshowVideoChoices(vid.toArray(arr));\n\t\t}\n\t}\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage us.shandian.giga.ui.web;\n\nimport android.app.AlertDialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.ContextThemeWrapper;\nimport android.view.KeyEvent;\nimport android.view.LayoutInflater;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.webkit.DownloadListener;\nimport android.webkit.JavascriptInterface;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.EditText;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\n\nimport android.support.v7.app.ActionBar;\n\nimport java.util.ArrayList;\nimport java.util.regex.Pattern;\nimport java.util.regex.Matcher;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.ui.common.ToolbarActivity;\nimport us.shandian.giga.ui.main.MainActivity;\nimport us.shandian.giga.util.Utility;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class BrowserActivity extends ToolbarActivity\n{\n\tprivate WebView mWeb;\n\tprivate ProgressBar mProgress;\n\tprivate EditText mUrl;\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\t\n\t\t\/\/ Toolbar\n\t\tgetSupportActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowHomeEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\n\t\t\/\/ Custom view\n\t\tif (Build.VERSION.SDK_INT < 21) {\n\t\t\tContextThemeWrapper wrap = new ContextThemeWrapper(this, R.style.Theme_AppCompat);\n\t\t\tLayoutInflater inflater = (LayoutInflater) wrap.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n\t\t\tView custom = inflater.inflate(R.layout.browser_url, null);\n\t\t\tgetSupportActionBar().setCustomView(custom);\n\t\t} else {\n\t\t\tgetSupportActionBar().setCustomView(R.layout.browser_url);\n\t\t}\n\t\t\n\t\t\/\/ Initialize WebView\n\t\tmProgress = Utility.findViewById(this, R.id.progress);\n\t\tmUrl = Utility.findViewById(getSupportActionBar().getCustomView(), R.id.browser_url);\n\t\tmWeb = Utility.findViewById(this, R.id.web);\n\t\tmWeb.setWebViewClient(new WebViewClient() {\n\t\t\t@Override\n\t\t\tpublic boolean shouldOverrideUrlLoading(WebView view, String url) {\n\t\t\t\tview.loadUrl(url);\n\t\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onPageFinished(WebView view, String url) {\n\t\t\t\tmProgress.setProgress(0);\n\t\t\t}\n\t\t});\n\t\tmWeb.setWebChromeClient(new WebChromeClient() {\n\t\t\t@Override\n\t\t\tpublic void onProgressChanged(WebView v, int progress) {\n\t\t\t\tmProgress.setProgress(progress);\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onReceivedTitle(WebView v, String title) {\n\t\t\t\tgetSupportActionBar().setTitle(title);\n\t\t\t}\n\t\t});\n\t\tmWeb.getSettings().setJavaScriptEnabled(true);\n\t\tmWeb.setDownloadListener(new DownloadListener() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {\n\t\t\t\t\t\/\/ Start MainActivity for downloading\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(url), mimeType);\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t\n\t\t});\n\t\tmUrl.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n\t\t\t@Override\n\t\t\tpublic boolean onEditorAction(TextView v, int actionId, KeyEvent ev) {\n\t\t\t\t\tif (actionId == EditorInfo.IME_ACTION_GO) {\n\t\t\t\t\t\tString url = mUrl.getText().toString();\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!url.startsWith(\"http\")) {\n\t\t\t\t\t\t\turl = \"http:\/\/\" + url;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tmWeb.loadUrl(url);\n\t\t\t\t\t\tswitchCustom();\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t});\n\t\tmWeb.addJavascriptInterface(new MyJavascriptInterface(), \"HTMLOUT\");\n\t\t\n\t\tmWeb.loadUrl(\"about:blank\");\n\t\t\n\t\tswitchCustom();\n\t\t\n\t\tmToolbar.setOnClickListener(new View.OnClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tswitchCustom();\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tprotected int getLayoutResource() {\n\t\treturn R.layout.browser;\n\t}\n\n\t@Override\n\tpublic boolean onCreateOptionsMenu(Menu menu) {\n\t\tgetMenuInflater().inflate(R.menu.browser, menu);\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tswitch (item.getItemId()) {\n\t\t\tcase android.R.id.home:\n\t\t\t\tfinish();\n\t\t\t\treturn true;\n\t\t\tcase R.id.detector:\n\t\t\t\tmWeb.loadUrl(\"javascript:window.HTMLOUT.processHTML(''+document.getElementsByTagName('html')[0].innerHTML+'<\/head>');\");\n\t\t\t\treturn true;\n\t\t\tdefault:\n\t\t\t\treturn super.onOptionsItemSelected(item);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onBackPressed() {\n\t\tif (mWeb.canGoBack()) {\n\t\t\tmWeb.goBack();\n\t\t} else {\n\t\t\tfinish();\n\t\t}\n\t}\n\t\n\tprivate void switchCustom() {\n\t\tint opt = getSupportActionBar().getDisplayOptions();\n\t\t\n\t\tif ((opt & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t} else {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(true);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\tmUrl.setText(mWeb.getUrl());\n\t\t\tmUrl.setSelection(0, mUrl.getText().length());\n\t\t}\n\t}\n\t\n\tprivate void showVideoChoices(final String[] vids) {\n\t\tnew AlertDialog.Builder(this)\n\t\t\t.setItems(vids, new DialogInterface.OnClickListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(vids[id]), \"application\/octet-stream\");\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t})\n\t\t\t.show();\n\t}\n\t\n\tclass MyJavascriptInterface {\n\t\tprivate static final String TAG = MyJavascriptInterface.class.getSimpleName();\n\t\t\n\t\tprivate static final String PATTERN = \"[http|https]+[:\/\/]+[0-9A-Za-z:\/[-]_#[?][=][.][&]]*\";\n\t\tprivate static final String[] VIDEO_SUFFIXES = new String[]{\n\t\t\t\".mp4\",\n\t\t\t\".flv\",\n\t\t\t\".rm\",\n\t\t\t\".rmvb\",\n\t\t\t\".wmv\",\n\t\t\t\".avi\",\n\t\t\t\".mkv\",\n\t\t\t\".webm\"\n\t\t};\n\t\t\n\t\t@JavascriptInterface\n\t\tpublic void processHTML(String html) {\n\t\t\tPattern pattern = Pattern.compile(PATTERN);\n\t\t\tMatcher matcher = pattern.matcher(html);\n\t\t\t\n\t\t\tArrayList vid = new ArrayList();\n\t\t\t\n\t\t\twhile (matcher.find()) {\n\t\t\t\tString url = matcher.group();\n\t\t\t\t\n\t\t\t\tboolean isVid = false;\n\t\t\t\t\n\t\t\t\tfor (String suffix : VIDEO_SUFFIXES) {\n\t\t\t\t\tif (url.contains(suffix)) {\n\t\t\t\t\t\tisVid = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (isVid) {\n\t\t\t\t\t\n\t\t\t\t\tvid.add(url);\n\t\t\t\t\t\n\t\t\t\t\tif (DEBUG) {\n\t\t\t\t\t\tLog.d(TAG, \"found url:\" + url);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (vid.size() == 0) return;\n\t\t\t\n\t\t\tString[] arr = new String[vid.size()];\n\t\t\tshowVideoChoices(vid.toArray(arr));\n\t\t}\n\t}\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite BrowserActivity to optimize input method for execution time. Write the entire code and no other text in the response.\n\n### Concepts:\n[+] android.view.inputmethod.InputMethodManager\n[+] InputMethodManager mInput\n[+] getSystemService(Context.INPUT_METHOD_SERVICE)\n[+] mInput.toggleSoftInput(enum, enum)\n[in] onCreate function\n[in] switchCustom function\n\n### Given program:\n```java\npackage us.shandian.giga.ui.web;\n\nimport android.app.AlertDialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.ContextThemeWrapper;\nimport android.view.KeyEvent;\nimport android.view.LayoutInflater;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.webkit.DownloadListener;\nimport android.webkit.JavascriptInterface;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.EditText;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\n\nimport android.support.v7.app.ActionBar;\n\nimport java.util.ArrayList;\nimport java.util.regex.Pattern;\nimport java.util.regex.Matcher;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.ui.common.ToolbarActivity;\nimport us.shandian.giga.ui.main.MainActivity;\nimport us.shandian.giga.util.Utility;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class BrowserActivity extends ToolbarActivity\n{\n\tprivate WebView mWeb;\n\tprivate ProgressBar mProgress;\n\tprivate EditText mUrl;\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\t\n\t\t\/\/ Toolbar\n\t\tgetSupportActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowHomeEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\n\t\t\/\/ Custom view\n\t\tif (Build.VERSION.SDK_INT < 21) {\n\t\t\tContextThemeWrapper wrap = new ContextThemeWrapper(this, R.style.Theme_AppCompat);\n\t\t\tLayoutInflater inflater = (LayoutInflater) wrap.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n\t\t\tView custom = inflater.inflate(R.layout.browser_url, null);\n\t\t\tgetSupportActionBar().setCustomView(custom);\n\t\t} else {\n\t\t\tgetSupportActionBar().setCustomView(R.layout.browser_url);\n\t\t}\n\t\t\n\t\t\/\/ Initialize WebView\n\t\tmProgress = Utility.findViewById(this, R.id.progress);\n\t\tmUrl = Utility.findViewById(getSupportActionBar().getCustomView(), R.id.browser_url);\n\t\tmWeb = Utility.findViewById(this, R.id.web);\n\t\tmWeb.setWebViewClient(new WebViewClient() {\n\t\t\t@Override\n\t\t\tpublic boolean shouldOverrideUrlLoading(WebView view, String url) {\n\t\t\t\tview.loadUrl(url);\n\t\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onPageFinished(WebView view, String url) {\n\t\t\t\tmProgress.setProgress(0);\n\t\t\t}\n\t\t});\n\t\tmWeb.setWebChromeClient(new WebChromeClient() {\n\t\t\t@Override\n\t\t\tpublic void onProgressChanged(WebView v, int progress) {\n\t\t\t\tmProgress.setProgress(progress);\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onReceivedTitle(WebView v, String title) {\n\t\t\t\tgetSupportActionBar().setTitle(title);\n\t\t\t}\n\t\t});\n\t\tmWeb.getSettings().setJavaScriptEnabled(true);\n\t\tmWeb.setDownloadListener(new DownloadListener() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {\n\t\t\t\t\t\/\/ Start MainActivity for downloading\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(url), mimeType);\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t\n\t\t});\n\t\tmUrl.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n\t\t\t@Override\n\t\t\tpublic boolean onEditorAction(TextView v, int actionId, KeyEvent ev) {\n\t\t\t\t\tif (actionId == EditorInfo.IME_ACTION_GO) {\n\t\t\t\t\t\tString url = mUrl.getText().toString();\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!url.startsWith(\"http\")) {\n\t\t\t\t\t\t\turl = \"http:\/\/\" + url;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tmWeb.loadUrl(url);\n\t\t\t\t\t\tswitchCustom();\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t});\n\t\tmWeb.addJavascriptInterface(new MyJavascriptInterface(), \"HTMLOUT\");\n\t\t\n\t\tmWeb.loadUrl(\"about:blank\");\n\t\t\n\t\tswitchCustom();\n\t\t\n\t\tmToolbar.setOnClickListener(new View.OnClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tswitchCustom();\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tprotected int getLayoutResource() {\n\t\treturn R.layout.browser;\n\t}\n\n\t@Override\n\tpublic boolean onCreateOptionsMenu(Menu menu) {\n\t\tgetMenuInflater().inflate(R.menu.browser, menu);\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tswitch (item.getItemId()) {\n\t\t\tcase android.R.id.home:\n\t\t\t\tfinish();\n\t\t\t\treturn true;\n\t\t\tcase R.id.detector:\n\t\t\t\tmWeb.loadUrl(\"javascript:window.HTMLOUT.processHTML(''+document.getElementsByTagName('html')[0].innerHTML+'<\/head>');\");\n\t\t\t\treturn true;\n\t\t\tdefault:\n\t\t\t\treturn super.onOptionsItemSelected(item);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onBackPressed() {\n\t\tif (mWeb.canGoBack()) {\n\t\t\tmWeb.goBack();\n\t\t} else {\n\t\t\tfinish();\n\t\t}\n\t}\n\t\n\tprivate void switchCustom() {\n\t\tint opt = getSupportActionBar().getDisplayOptions();\n\t\t\n\t\tif ((opt & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t} else {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(true);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\tmUrl.setText(mWeb.getUrl());\n\t\t\tmUrl.setSelection(0, mUrl.getText().length());\n\t\t}\n\t}\n\t\n\tprivate void showVideoChoices(final String[] vids) {\n\t\tnew AlertDialog.Builder(this)\n\t\t\t.setItems(vids, new DialogInterface.OnClickListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(vids[id]), \"application\/octet-stream\");\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t})\n\t\t\t.show();\n\t}\n\t\n\tclass MyJavascriptInterface {\n\t\tprivate static final String TAG = MyJavascriptInterface.class.getSimpleName();\n\t\t\n\t\tprivate static final String PATTERN = \"[http|https]+[:\/\/]+[0-9A-Za-z:\/[-]_#[?][=][.][&]]*\";\n\t\tprivate static final String[] VIDEO_SUFFIXES = new String[]{\n\t\t\t\".mp4\",\n\t\t\t\".flv\",\n\t\t\t\".rm\",\n\t\t\t\".rmvb\",\n\t\t\t\".wmv\",\n\t\t\t\".avi\",\n\t\t\t\".mkv\",\n\t\t\t\".webm\"\n\t\t};\n\t\t\n\t\t@JavascriptInterface\n\t\tpublic void processHTML(String html) {\n\t\t\tPattern pattern = Pattern.compile(PATTERN);\n\t\t\tMatcher matcher = pattern.matcher(html);\n\t\t\t\n\t\t\tArrayList vid = new ArrayList();\n\t\t\t\n\t\t\twhile (matcher.find()) {\n\t\t\t\tString url = matcher.group();\n\t\t\t\t\n\t\t\t\tboolean isVid = false;\n\t\t\t\t\n\t\t\t\tfor (String suffix : VIDEO_SUFFIXES) {\n\t\t\t\t\tif (url.contains(suffix)) {\n\t\t\t\t\t\tisVid = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (isVid) {\n\t\t\t\t\t\n\t\t\t\t\tvid.add(url);\n\t\t\t\t\t\n\t\t\t\t\tif (DEBUG) {\n\t\t\t\t\t\tLog.d(TAG, \"found url:\" + url);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (vid.size() == 0) return;\n\t\t\t\n\t\t\tString[] arr = new String[vid.size()];\n\t\t\tshowVideoChoices(vid.toArray(arr));\n\t\t}\n\t}\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage acr.browser.lightning.search;\n\nimport android.app.Application;\nimport android.content.Context;\nimport android.net.ConnectivityManager;\nimport android.net.NetworkInfo;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.InputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.net.URLEncoder;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.concurrent.TimeUnit;\nimport java.util.zip.GZIPInputStream;\n\nimport acr.browser.lightning.database.HistoryItem;\nimport acr.browser.lightning.utils.Utils;\nimport okhttp3.CacheControl;\nimport okhttp3.OkHttpClient;\nimport okhttp3.Request;\nimport okhttp3.Response;\n\nabstract class BaseSuggestionsTask {\n\n private static final String TAG = BaseSuggestionsTask.class.getSimpleName();\n\n static final int MAX_RESULTS = 5;\n private static final long INTERVAL_DAY = TimeUnit.DAYS.toMillis(1);\n private static final String DEFAULT_LANGUAGE = \"en\";\n @Nullable private static String sLanguage;\n @NonNull private final SuggestionsResult mResultCallback;\n @NonNull private final Application mApplication;\n @NonNull private final OkHttpClient mHttpClient = new OkHttpClient();\n @NonNull private final CacheControl mCacheControl;\n @NonNull private final ConnectivityManager mConnectivityManager;\n @NonNull private String mQuery;\n\n @NonNull\n protected abstract String getQueryUrl(@NonNull String query, @NonNull String language);\n\n protected abstract void parseResults(@NonNull FileInputStream inputStream, @NonNull List results) throws Exception;\n\n @NonNull\n protected abstract String getEncoding();\n\n BaseSuggestionsTask(@NonNull String query,\n @NonNull Application application,\n @NonNull SuggestionsResult callback) {\n mQuery = query;\n mResultCallback = callback;\n mApplication = application;\n mCacheControl = new CacheControl.Builder().maxStale(1, TimeUnit.DAYS).build();\n mConnectivityManager = getConnectivityManager(mApplication);\n }\n\n @NonNull\n private static synchronized String getLanguage() {\n if (sLanguage == null) {\n sLanguage = Locale.getDefault().getLanguage();\n }\n if (TextUtils.isEmpty(sLanguage)) {\n sLanguage = DEFAULT_LANGUAGE;\n }\n return sLanguage;\n }\n\n void run() {\n List filter = new ArrayList<>(5);\n try {\n mQuery = URLEncoder.encode(mQuery, getEncoding());\n } catch (UnsupportedEncodingException e) {\n Log.e(TAG, \"Unable to encode the URL\", e);\n }\n File cache = downloadSuggestionsForQuery(mQuery, getLanguage(), mApplication);\n if (!cache.exists()) {\n post(filter);\n return;\n }\n FileInputStream fileInput = null;\n try {\n fileInput = new FileInputStream(cache);\n parseResults(fileInput, filter);\n } catch (Exception e) {\n post(filter);\n Log.e(TAG, \"Unable to parse results\", e);\n return;\n } finally {\n Utils.close(fileInput);\n }\n post(filter);\n }\n\n private void post(@NonNull List result) {\n mResultCallback.resultReceived(result);\n }\n\n \/**\n * This method downloads the search suggestions for the specific query.\n * NOTE: This is a blocking operation, do not run on the UI thread.\n *\n * @param query the query to get suggestions for\n * @return the cache file containing the suggestions\n *\/\n @NonNull\n private File downloadSuggestionsForQuery(@NonNull String query, String language, @NonNull Application app) {\n String queryUrl = getQueryUrl(query, language);\n File cacheFile = new File(app.getCacheDir(), queryUrl.hashCode() + SuggestionsAdapter.CACHE_FILE_TYPE);\n if (System.currentTimeMillis() - INTERVAL_DAY < cacheFile.lastModified()) {\n return cacheFile;\n }\n if (!isNetworkConnected()) {\n return cacheFile;\n }\n InputStream in = null;\n FileOutputStream fos = null;\n try {\n URL url = new URL(queryUrl);\n Request suggestionsRequest = new Request.Builder().url(url)\n .addHeader(\"Accept-Encoding\", \"gzip\")\n .addHeader(\"Accept-Charset\", getEncoding())\n .cacheControl(mCacheControl)\n .build();\n\n Response suggestionsResponse = mHttpClient.newCall(suggestionsRequest).execute();\n\n if (suggestionsResponse.code() >= HttpURLConnection.HTTP_MULT_CHOICE ||\n suggestionsResponse.code() < HttpURLConnection.HTTP_OK) {\n Log.e(TAG, \"Search API Responded with code: \" + suggestionsResponse.code());\n suggestionsResponse.body().close();\n return cacheFile;\n }\n\n in = suggestionsResponse.body().byteStream();\n\n if (in != null) {\n in = new GZIPInputStream(in);\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n fos = new FileOutputStream(cacheFile);\n int buffer;\n while ((buffer = in.read()) != -1) {\n fos.write(buffer);\n }\n fos.flush();\n }\n suggestionsResponse.body().close();\n cacheFile.setLastModified(System.currentTimeMillis());\n } catch (Exception e) {\n Log.w(TAG, \"Problem getting search suggestions\", e);\n } finally {\n Utils.close(in);\n Utils.close(fos);\n }\n return cacheFile;\n }\n\n private boolean isNetworkConnected() {\n NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();\n return networkInfo != null && networkInfo.isConnected();\n }\n\n @NonNull\n private static ConnectivityManager getConnectivityManager(@NonNull Context context) {\n return (ConnectivityManager) context\n .getApplicationContext()\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n }\n\n}\n\n\nCode-B:\npackage acr.browser.lightning.search;\n\nimport android.app.Application;\nimport android.content.Context;\nimport android.net.ConnectivityManager;\nimport android.net.NetworkInfo;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.InputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.net.URLEncoder;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.concurrent.TimeUnit;\nimport java.util.zip.GZIPInputStream;\n\nimport acr.browser.lightning.database.HistoryItem;\nimport acr.browser.lightning.utils.Utils;\nimport okhttp3.CacheControl;\nimport okhttp3.OkHttpClient;\nimport okhttp3.Request;\nimport okhttp3.Response;\n\nabstract class BaseSuggestionsTask {\n\n private static final String TAG = BaseSuggestionsTask.class.getSimpleName();\n\n static final int MAX_RESULTS = 5;\n private static final long INTERVAL_DAY = TimeUnit.DAYS.toMillis(1);\n private static final String DEFAULT_LANGUAGE = \"en\";\n @Nullable private static String sLanguage;\n @NonNull private final SuggestionsResult mResultCallback;\n @NonNull private final Application mApplication;\n @NonNull private final OkHttpClient mHttpClient = new OkHttpClient();\n @NonNull private final CacheControl mCacheControl;\n @NonNull private String mQuery;\n\n @NonNull\n protected abstract String getQueryUrl(@NonNull String query, @NonNull String language);\n\n protected abstract void parseResults(@NonNull FileInputStream inputStream, @NonNull List results) throws Exception;\n\n @NonNull\n protected abstract String getEncoding();\n\n BaseSuggestionsTask(@NonNull String query,\n @NonNull Application application,\n @NonNull SuggestionsResult callback) {\n mQuery = query;\n mResultCallback = callback;\n mApplication = application;\n mCacheControl = new CacheControl.Builder().maxStale(1, TimeUnit.DAYS).build();\n }\n\n @NonNull\n private static synchronized String getLanguage() {\n if (sLanguage == null) {\n sLanguage = Locale.getDefault().getLanguage();\n }\n if (TextUtils.isEmpty(sLanguage)) {\n sLanguage = DEFAULT_LANGUAGE;\n }\n return sLanguage;\n }\n\n void run() {\n List filter = new ArrayList<>(5);\n try {\n mQuery = URLEncoder.encode(mQuery, getEncoding());\n } catch (UnsupportedEncodingException e) {\n Log.e(TAG, \"Unable to encode the URL\", e);\n }\n File cache = downloadSuggestionsForQuery(mQuery, getLanguage(), mApplication);\n if (!cache.exists()) {\n post(filter);\n return;\n }\n FileInputStream fileInput = null;\n try {\n fileInput = new FileInputStream(cache);\n parseResults(fileInput, filter);\n } catch (Exception e) {\n post(filter);\n Log.e(TAG, \"Unable to parse results\", e);\n return;\n } finally {\n Utils.close(fileInput);\n }\n post(filter);\n }\n\n private void post(@NonNull List result) {\n mResultCallback.resultReceived(result);\n }\n\n \/**\n * This method downloads the search suggestions for the specific query.\n * NOTE: This is a blocking operation, do not run on the UI thread.\n *\n * @param query the query to get suggestions for\n * @return the cache file containing the suggestions\n *\/\n @NonNull\n private File downloadSuggestionsForQuery(@NonNull String query, String language, @NonNull Application app) {\n String queryUrl = getQueryUrl(query, language);\n File cacheFile = new File(app.getCacheDir(), queryUrl.hashCode() + SuggestionsAdapter.CACHE_FILE_TYPE);\n if (System.currentTimeMillis() - INTERVAL_DAY < cacheFile.lastModified()) {\n return cacheFile;\n }\n if (!isNetworkConnected(app)) {\n return cacheFile;\n }\n InputStream in = null;\n FileOutputStream fos = null;\n try {\n URL url = new URL(queryUrl);\n Request suggestionsRequest = new Request.Builder().url(url)\n .addHeader(\"Accept-Encoding\", \"gzip\")\n .addHeader(\"Accept-Charset\", getEncoding())\n .cacheControl(mCacheControl)\n .build();\n\n Response suggestionsResponse = mHttpClient.newCall(suggestionsRequest).execute();\n\n if (suggestionsResponse.code() >= HttpURLConnection.HTTP_MULT_CHOICE ||\n suggestionsResponse.code() < HttpURLConnection.HTTP_OK) {\n Log.e(TAG, \"Search API Responded with code: \" + suggestionsResponse.code());\n suggestionsResponse.body().close();\n return cacheFile;\n }\n\n in = suggestionsResponse.body().byteStream();\n\n if (in != null) {\n in = new GZIPInputStream(in);\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n fos = new FileOutputStream(cacheFile);\n int buffer;\n while ((buffer = in.read()) != -1) {\n fos.write(buffer);\n }\n fos.flush();\n }\n suggestionsResponse.body().close();\n cacheFile.setLastModified(System.currentTimeMillis());\n } catch (Exception e) {\n Log.w(TAG, \"Problem getting search suggestions\", e);\n } finally {\n Utils.close(in);\n Utils.close(fos);\n }\n return cacheFile;\n }\n\n private static boolean isNetworkConnected(@NonNull Context context) {\n NetworkInfo networkInfo = getActiveNetworkInfo(context);\n return networkInfo != null && networkInfo.isConnected();\n }\n\n @Nullable\n private static NetworkInfo getActiveNetworkInfo(@NonNull Context context) {\n ConnectivityManager connectivity = (ConnectivityManager) context\n .getApplicationContext()\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n if (connectivity == null) {\n return null;\n }\n return connectivity.getActiveNetworkInfo();\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage acr.browser.lightning.search;\n\nimport android.app.Application;\nimport android.content.Context;\nimport android.net.ConnectivityManager;\nimport android.net.NetworkInfo;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.InputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.net.URLEncoder;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.concurrent.TimeUnit;\nimport java.util.zip.GZIPInputStream;\n\nimport acr.browser.lightning.database.HistoryItem;\nimport acr.browser.lightning.utils.Utils;\nimport okhttp3.CacheControl;\nimport okhttp3.OkHttpClient;\nimport okhttp3.Request;\nimport okhttp3.Response;\n\nabstract class BaseSuggestionsTask {\n\n private static final String TAG = BaseSuggestionsTask.class.getSimpleName();\n\n static final int MAX_RESULTS = 5;\n private static final long INTERVAL_DAY = TimeUnit.DAYS.toMillis(1);\n private static final String DEFAULT_LANGUAGE = \"en\";\n @Nullable private static String sLanguage;\n @NonNull private final SuggestionsResult mResultCallback;\n @NonNull private final Application mApplication;\n @NonNull private final OkHttpClient mHttpClient = new OkHttpClient();\n @NonNull private final CacheControl mCacheControl;\n @NonNull private String mQuery;\n\n @NonNull\n protected abstract String getQueryUrl(@NonNull String query, @NonNull String language);\n\n protected abstract void parseResults(@NonNull FileInputStream inputStream, @NonNull List results) throws Exception;\n\n @NonNull\n protected abstract String getEncoding();\n\n BaseSuggestionsTask(@NonNull String query,\n @NonNull Application application,\n @NonNull SuggestionsResult callback) {\n mQuery = query;\n mResultCallback = callback;\n mApplication = application;\n mCacheControl = new CacheControl.Builder().maxStale(1, TimeUnit.DAYS).build();\n }\n\n @NonNull\n private static synchronized String getLanguage() {\n if (sLanguage == null) {\n sLanguage = Locale.getDefault().getLanguage();\n }\n if (TextUtils.isEmpty(sLanguage)) {\n sLanguage = DEFAULT_LANGUAGE;\n }\n return sLanguage;\n }\n\n void run() {\n List filter = new ArrayList<>(5);\n try {\n mQuery = URLEncoder.encode(mQuery, getEncoding());\n } catch (UnsupportedEncodingException e) {\n Log.e(TAG, \"Unable to encode the URL\", e);\n }\n File cache = downloadSuggestionsForQuery(mQuery, getLanguage(), mApplication);\n if (!cache.exists()) {\n post(filter);\n return;\n }\n FileInputStream fileInput = null;\n try {\n fileInput = new FileInputStream(cache);\n parseResults(fileInput, filter);\n } catch (Exception e) {\n post(filter);\n Log.e(TAG, \"Unable to parse results\", e);\n return;\n } finally {\n Utils.close(fileInput);\n }\n post(filter);\n }\n\n private void post(@NonNull List result) {\n mResultCallback.resultReceived(result);\n }\n\n \/**\n * This method downloads the search suggestions for the specific query.\n * NOTE: This is a blocking operation, do not run on the UI thread.\n *\n * @param query the query to get suggestions for\n * @return the cache file containing the suggestions\n *\/\n @NonNull\n private File downloadSuggestionsForQuery(@NonNull String query, String language, @NonNull Application app) {\n String queryUrl = getQueryUrl(query, language);\n File cacheFile = new File(app.getCacheDir(), queryUrl.hashCode() + SuggestionsAdapter.CACHE_FILE_TYPE);\n if (System.currentTimeMillis() - INTERVAL_DAY < cacheFile.lastModified()) {\n return cacheFile;\n }\n if (!isNetworkConnected(app)) {\n return cacheFile;\n }\n InputStream in = null;\n FileOutputStream fos = null;\n try {\n URL url = new URL(queryUrl);\n Request suggestionsRequest = new Request.Builder().url(url)\n .addHeader(\"Accept-Encoding\", \"gzip\")\n .addHeader(\"Accept-Charset\", getEncoding())\n .cacheControl(mCacheControl)\n .build();\n\n Response suggestionsResponse = mHttpClient.newCall(suggestionsRequest).execute();\n\n if (suggestionsResponse.code() >= HttpURLConnection.HTTP_MULT_CHOICE ||\n suggestionsResponse.code() < HttpURLConnection.HTTP_OK) {\n Log.e(TAG, \"Search API Responded with code: \" + suggestionsResponse.code());\n suggestionsResponse.body().close();\n return cacheFile;\n }\n\n in = suggestionsResponse.body().byteStream();\n\n if (in != null) {\n in = new GZIPInputStream(in);\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n fos = new FileOutputStream(cacheFile);\n int buffer;\n while ((buffer = in.read()) != -1) {\n fos.write(buffer);\n }\n fos.flush();\n }\n suggestionsResponse.body().close();\n cacheFile.setLastModified(System.currentTimeMillis());\n } catch (Exception e) {\n Log.w(TAG, \"Problem getting search suggestions\", e);\n } finally {\n Utils.close(in);\n Utils.close(fos);\n }\n return cacheFile;\n }\n\n private static boolean isNetworkConnected(@NonNull Context context) {\n NetworkInfo networkInfo = getActiveNetworkInfo(context);\n return networkInfo != null && networkInfo.isConnected();\n }\n\n @Nullable\n private static NetworkInfo getActiveNetworkInfo(@NonNull Context context) {\n ConnectivityManager connectivity = (ConnectivityManager) context\n .getApplicationContext()\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n if (connectivity == null) {\n return null;\n }\n return connectivity.getActiveNetworkInfo();\n }\n\n}\n\n\nCode-B:\npackage acr.browser.lightning.search;\n\nimport android.app.Application;\nimport android.content.Context;\nimport android.net.ConnectivityManager;\nimport android.net.NetworkInfo;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.InputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.net.URLEncoder;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.concurrent.TimeUnit;\nimport java.util.zip.GZIPInputStream;\n\nimport acr.browser.lightning.database.HistoryItem;\nimport acr.browser.lightning.utils.Utils;\nimport okhttp3.CacheControl;\nimport okhttp3.OkHttpClient;\nimport okhttp3.Request;\nimport okhttp3.Response;\n\nabstract class BaseSuggestionsTask {\n\n private static final String TAG = BaseSuggestionsTask.class.getSimpleName();\n\n static final int MAX_RESULTS = 5;\n private static final long INTERVAL_DAY = TimeUnit.DAYS.toMillis(1);\n private static final String DEFAULT_LANGUAGE = \"en\";\n @Nullable private static String sLanguage;\n @NonNull private final SuggestionsResult mResultCallback;\n @NonNull private final Application mApplication;\n @NonNull private final OkHttpClient mHttpClient = new OkHttpClient();\n @NonNull private final CacheControl mCacheControl;\n @NonNull private final ConnectivityManager mConnectivityManager;\n @NonNull private String mQuery;\n\n @NonNull\n protected abstract String getQueryUrl(@NonNull String query, @NonNull String language);\n\n protected abstract void parseResults(@NonNull FileInputStream inputStream, @NonNull List results) throws Exception;\n\n @NonNull\n protected abstract String getEncoding();\n\n BaseSuggestionsTask(@NonNull String query,\n @NonNull Application application,\n @NonNull SuggestionsResult callback) {\n mQuery = query;\n mResultCallback = callback;\n mApplication = application;\n mCacheControl = new CacheControl.Builder().maxStale(1, TimeUnit.DAYS).build();\n mConnectivityManager = getConnectivityManager(mApplication);\n }\n\n @NonNull\n private static synchronized String getLanguage() {\n if (sLanguage == null) {\n sLanguage = Locale.getDefault().getLanguage();\n }\n if (TextUtils.isEmpty(sLanguage)) {\n sLanguage = DEFAULT_LANGUAGE;\n }\n return sLanguage;\n }\n\n void run() {\n List filter = new ArrayList<>(5);\n try {\n mQuery = URLEncoder.encode(mQuery, getEncoding());\n } catch (UnsupportedEncodingException e) {\n Log.e(TAG, \"Unable to encode the URL\", e);\n }\n File cache = downloadSuggestionsForQuery(mQuery, getLanguage(), mApplication);\n if (!cache.exists()) {\n post(filter);\n return;\n }\n FileInputStream fileInput = null;\n try {\n fileInput = new FileInputStream(cache);\n parseResults(fileInput, filter);\n } catch (Exception e) {\n post(filter);\n Log.e(TAG, \"Unable to parse results\", e);\n return;\n } finally {\n Utils.close(fileInput);\n }\n post(filter);\n }\n\n private void post(@NonNull List result) {\n mResultCallback.resultReceived(result);\n }\n\n \/**\n * This method downloads the search suggestions for the specific query.\n * NOTE: This is a blocking operation, do not run on the UI thread.\n *\n * @param query the query to get suggestions for\n * @return the cache file containing the suggestions\n *\/\n @NonNull\n private File downloadSuggestionsForQuery(@NonNull String query, String language, @NonNull Application app) {\n String queryUrl = getQueryUrl(query, language);\n File cacheFile = new File(app.getCacheDir(), queryUrl.hashCode() + SuggestionsAdapter.CACHE_FILE_TYPE);\n if (System.currentTimeMillis() - INTERVAL_DAY < cacheFile.lastModified()) {\n return cacheFile;\n }\n if (!isNetworkConnected()) {\n return cacheFile;\n }\n InputStream in = null;\n FileOutputStream fos = null;\n try {\n URL url = new URL(queryUrl);\n Request suggestionsRequest = new Request.Builder().url(url)\n .addHeader(\"Accept-Encoding\", \"gzip\")\n .addHeader(\"Accept-Charset\", getEncoding())\n .cacheControl(mCacheControl)\n .build();\n\n Response suggestionsResponse = mHttpClient.newCall(suggestionsRequest).execute();\n\n if (suggestionsResponse.code() >= HttpURLConnection.HTTP_MULT_CHOICE ||\n suggestionsResponse.code() < HttpURLConnection.HTTP_OK) {\n Log.e(TAG, \"Search API Responded with code: \" + suggestionsResponse.code());\n suggestionsResponse.body().close();\n return cacheFile;\n }\n\n in = suggestionsResponse.body().byteStream();\n\n if (in != null) {\n in = new GZIPInputStream(in);\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n fos = new FileOutputStream(cacheFile);\n int buffer;\n while ((buffer = in.read()) != -1) {\n fos.write(buffer);\n }\n fos.flush();\n }\n suggestionsResponse.body().close();\n cacheFile.setLastModified(System.currentTimeMillis());\n } catch (Exception e) {\n Log.w(TAG, \"Problem getting search suggestions\", e);\n } finally {\n Utils.close(in);\n Utils.close(fos);\n }\n return cacheFile;\n }\n\n private boolean isNetworkConnected() {\n NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();\n return networkInfo != null && networkInfo.isConnected();\n }\n\n @NonNull\n private static ConnectivityManager getConnectivityManager(@NonNull Context context) {\n return (ConnectivityManager) context\n .getApplicationContext()\n .getSystemService(Context.CONNECTIVITY_SERVICE);\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/vaginessa\/TestBrowser-Lightning\/commit\/80ab4aff3541f4fc26349393e658603fe97c36c5","commit_message":"'\\\\\"Improving performance of adblocking code by utilizing stringbuilder\\\\n\\\\\"'","source_code":"package acr.browser.lightning.utils;\n\nimport android.content.Context;\nimport android.content.res.AssetManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.util.Log;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.inject.Inject;\nimport javax.inject.Singleton;\n\nimport acr.browser.lightning.app.BrowserApp;\nimport acr.browser.lightning.constant.Constants;\nimport acr.browser.lightning.preference.PreferenceManager;\n\n@Singleton\npublic class AdBlock {\n\n private static final String TAG = \"AdBlock\";\n private static final String BLOCKED_DOMAINS_LIST_FILE_NAME = \"hosts.txt\";\n private static final String LOCAL_IP_V4 = \"127.0.0.1\";\n private static final String LOCAL_IP_V4_ALT = \"0.0.0.0\";\n private static final String LOCAL_IP_V6 = \"::1\";\n private static final String LOCALHOST = \"localhost\";\n private static final String COMMENT = \"#\";\n private static final String TAB = \"\\t\";\n private static final String SPACE = \" \";\n private static final String EMPTY = \"\";\n private final Set mBlockedDomainsList = new HashSet<>();\n private boolean mBlockAds;\n\n @Inject PreferenceManager mPreferenceManager;\n\n @Inject\n public AdBlock(@NonNull Context context) {\n BrowserApp.getAppComponent().inject(this);\n if (mBlockedDomainsList.isEmpty() && Constants.FULL_VERSION) {\n loadHostsFile(context);\n }\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n public void updatePreference() {\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n private void loadBlockedDomainsList(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n String line;\n while ((line = reader.readLine()) != null) {\n mBlockedDomainsList.add(line.trim());\n }\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n\n \/**\n * a method that determines if the given URL is an ad or not. It performs\n * a search of the URL's domain on the blocked domain hash set.\n *\n * @param url the URL to check for being an ad\n * @return true if it is an ad, false if it is not an ad\n *\/\n public boolean isAd(@Nullable String url) {\n if (!mBlockAds || url == null) {\n return false;\n }\n\n String domain;\n try {\n domain = getDomainName(url);\n } catch (URISyntaxException e) {\n Log.d(TAG, \"URL '\" + url + \"' is invalid\", e);\n return false;\n }\n\n boolean isOnBlacklist = mBlockedDomainsList.contains(domain);\n if (isOnBlacklist) {\n Log.d(TAG, \"URL '\" + url + \"' is an ad\");\n }\n return isOnBlacklist;\n }\n\n \/**\n * Returns the probable domain name for a given URL\n *\n * @param url the url to parse\n * @return returns the domain\n * @throws URISyntaxException throws an exception if the string cannot form a URI\n *\/\n @NonNull\n private static String getDomainName(@NonNull String url) throws URISyntaxException {\n int index = url.indexOf('\/', 8);\n if (index != -1) {\n url = url.substring(0, index);\n }\n\n URI uri = new URI(url);\n String domain = uri.getHost();\n if (domain == null) {\n return url;\n }\n\n return domain.startsWith(\"www.\") ? domain.substring(4) : domain;\n }\n\n \/**\n * This method reads through a hosts file and extracts the domains that should\n * be redirected to localhost (a.k.a. IP address 127.0.0.1). It can handle files that\n * simply have a list of hostnames to block, or it can handle a full blown hosts file.\n * It will strip out comments, references to the base IP address and just extract the\n * domains to be used\n *\n * @param context the context needed to read the file\n *\/\n private void loadHostsFile(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n String line;\n while ((line = reader.readLine()) != null) {\n if (!line.isEmpty() && !line.startsWith(COMMENT)) {\n line = line.replace(LOCAL_IP_V4, EMPTY)\n .replace(LOCAL_IP_V4_ALT, EMPTY)\n .replace(LOCAL_IP_V6, EMPTY)\n .replace(TAB, EMPTY);\n int comment = line.indexOf(COMMENT);\n if (comment >= 0) {\n line = line.substring(0, comment);\n }\n line = line.trim();\n if (!line.isEmpty() && !line.equals(LOCALHOST)) {\n while (line.contains(SPACE)) {\n int space = line.indexOf(SPACE);\n String host = line.substring(0, space);\n mBlockedDomainsList.add(host.trim());\n line = line.substring(space, line.length()).trim();\n }\n mBlockedDomainsList.add(line.trim());\n }\n }\n }\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n}\n","target_code":"package acr.browser.lightning.utils;\n\nimport android.content.Context;\nimport android.content.res.AssetManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.util.Log;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.inject.Inject;\nimport javax.inject.Singleton;\n\nimport acr.browser.lightning.app.BrowserApp;\nimport acr.browser.lightning.constant.Constants;\nimport acr.browser.lightning.preference.PreferenceManager;\n\n@Singleton\npublic class AdBlock {\n\n private static final String TAG = \"AdBlock\";\n private static final String BLOCKED_DOMAINS_LIST_FILE_NAME = \"hosts.txt\";\n private static final String LOCAL_IP_V4 = \"127.0.0.1\";\n private static final String LOCAL_IP_V4_ALT = \"0.0.0.0\";\n private static final String LOCAL_IP_V6 = \"::1\";\n private static final String LOCALHOST = \"localhost\";\n private static final String COMMENT = \"#\";\n private static final String TAB = \"\\t\";\n private static final String SPACE = \" \";\n private static final String EMPTY = \"\";\n private final Set mBlockedDomainsList = new HashSet<>();\n private boolean mBlockAds;\n\n @Inject PreferenceManager mPreferenceManager;\n\n @Inject\n public AdBlock(@NonNull Context context) {\n BrowserApp.getAppComponent().inject(this);\n if (mBlockedDomainsList.isEmpty() && Constants.FULL_VERSION) {\n loadHostsFile(context);\n }\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n public void updatePreference() {\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n private void loadBlockedDomainsList(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n String line;\n while ((line = reader.readLine()) != null) {\n mBlockedDomainsList.add(line.trim());\n }\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n\n \/**\n * a method that determines if the given URL is an ad or not. It performs\n * a search of the URL's domain on the blocked domain hash set.\n *\n * @param url the URL to check for being an ad\n * @return true if it is an ad, false if it is not an ad\n *\/\n public boolean isAd(@Nullable String url) {\n if (!mBlockAds || url == null) {\n return false;\n }\n\n String domain;\n try {\n domain = getDomainName(url);\n } catch (URISyntaxException e) {\n Log.d(TAG, \"URL '\" + url + \"' is invalid\", e);\n return false;\n }\n\n boolean isOnBlacklist = mBlockedDomainsList.contains(domain);\n if (isOnBlacklist) {\n Log.d(TAG, \"URL '\" + url + \"' is an ad\");\n }\n return isOnBlacklist;\n }\n\n \/**\n * Returns the probable domain name for a given URL\n *\n * @param url the url to parse\n * @return returns the domain\n * @throws URISyntaxException throws an exception if the string cannot form a URI\n *\/\n @NonNull\n private static String getDomainName(@NonNull String url) throws URISyntaxException {\n int index = url.indexOf('\/', 8);\n if (index != -1) {\n url = url.substring(0, index);\n }\n\n URI uri = new URI(url);\n String domain = uri.getHost();\n if (domain == null) {\n return url;\n }\n\n return domain.startsWith(\"www.\") ? domain.substring(4) : domain;\n }\n\n \/**\n * This method reads through a hosts file and extracts the domains that should\n * be redirected to localhost (a.k.a. IP address 127.0.0.1). It can handle files that\n * simply have a list of hostnames to block, or it can handle a full blown hosts file.\n * It will strip out comments, references to the base IP address and just extract the\n * domains to be used\n *\n * @param context the context needed to read the file\n *\/\n private void loadHostsFile(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n StringBuilder lineBuilder = new StringBuilder();\n String line;\n long time = System.currentTimeMillis();\n \/\/ TODO: 4\/23\/17 Improve performance by reading in on IO thread and then processing on worker thread\n while ((line = reader.readLine()) != null) {\n lineBuilder.append(line);\n\n if (!isEmpty(lineBuilder) && !startsWith(lineBuilder, COMMENT)) {\n replace(lineBuilder, LOCAL_IP_V4, EMPTY);\n replace(lineBuilder, LOCAL_IP_V4_ALT, EMPTY);\n replace(lineBuilder, LOCAL_IP_V6, EMPTY);\n replace(lineBuilder, TAB, EMPTY);\n\n int comment = lineBuilder.indexOf(COMMENT);\n if (comment >= 0) {\n lineBuilder.replace(comment, lineBuilder.length(), EMPTY);\n }\n\n trim(lineBuilder);\n\n if (!isEmpty(lineBuilder) && !AdBlock.equals(lineBuilder, LOCALHOST)) {\n while (contains(lineBuilder, SPACE)) {\n int space = lineBuilder.indexOf(SPACE);\n String host = lineBuilder.substring(0, space);\n replace(lineBuilder, host, EMPTY);\n mBlockedDomainsList.add(host.trim());\n }\n if (lineBuilder.length() > 0) {\n mBlockedDomainsList.add(lineBuilder.toString());\n }\n }\n }\n lineBuilder.setLength(0);\n }\n Log.d(TAG, \"Loaded ad list in: \" + (System.currentTimeMillis() - time) + \" ms\");\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n\n \/\/ TODO: 4\/23\/17 Move all these methods to a StringUtils class\n private static void replace(@NonNull StringBuilder stringBuilder,\n @NonNull String toReplace,\n @NonNull String replacement) {\n int index = stringBuilder.indexOf(toReplace);\n if (index >= 0) {\n stringBuilder.replace(index, index + toReplace.length(), replacement);\n }\n }\n\n private static void trim(@NonNull StringBuilder stringBuilder) {\n while (stringBuilder.indexOf(SPACE) == 0) {\n stringBuilder.replace(0, 1, EMPTY);\n }\n\n while (stringBuilder.lastIndexOf(SPACE) == (stringBuilder.length() - 1)) {\n stringBuilder.replace(stringBuilder.length() - 1, stringBuilder.length(), EMPTY);\n }\n }\n\n private static boolean isEmpty(@NonNull StringBuilder stringBuilder) {\n return stringBuilder.length() == 0;\n }\n\n private static boolean startsWith(@NonNull StringBuilder stringBuilder, @NonNull String start) {\n return stringBuilder.indexOf(start) == 0;\n }\n\n private static boolean contains(@NonNull StringBuilder stringBuilder, @NonNull String contains) {\n return stringBuilder.indexOf(contains) >= 0;\n }\n\n private static boolean equals(@NonNull StringBuilder stringBuilder, @NonNull String equal) {\n int index = stringBuilder.indexOf(equal);\n return index >= 0 && stringBuilder.length() == equal.length();\n }\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage acr.browser.lightning.utils;\n\nimport android.content.Context;\nimport android.content.res.AssetManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.util.Log;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.inject.Inject;\nimport javax.inject.Singleton;\n\nimport acr.browser.lightning.app.BrowserApp;\nimport acr.browser.lightning.constant.Constants;\nimport acr.browser.lightning.preference.PreferenceManager;\n\n@Singleton\npublic class AdBlock {\n\n private static final String TAG = \"AdBlock\";\n private static final String BLOCKED_DOMAINS_LIST_FILE_NAME = \"hosts.txt\";\n private static final String LOCAL_IP_V4 = \"127.0.0.1\";\n private static final String LOCAL_IP_V4_ALT = \"0.0.0.0\";\n private static final String LOCAL_IP_V6 = \"::1\";\n private static final String LOCALHOST = \"localhost\";\n private static final String COMMENT = \"#\";\n private static final String TAB = \"\\t\";\n private static final String SPACE = \" \";\n private static final String EMPTY = \"\";\n private final Set mBlockedDomainsList = new HashSet<>();\n private boolean mBlockAds;\n\n @Inject PreferenceManager mPreferenceManager;\n\n @Inject\n public AdBlock(@NonNull Context context) {\n BrowserApp.getAppComponent().inject(this);\n if (mBlockedDomainsList.isEmpty() && Constants.FULL_VERSION) {\n loadHostsFile(context);\n }\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n public void updatePreference() {\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n private void loadBlockedDomainsList(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n String line;\n while ((line = reader.readLine()) != null) {\n mBlockedDomainsList.add(line.trim());\n }\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n\n \/**\n * a method that determines if the given URL is an ad or not. It performs\n * a search of the URL's domain on the blocked domain hash set.\n *\n * @param url the URL to check for being an ad\n * @return true if it is an ad, false if it is not an ad\n *\/\n public boolean isAd(@Nullable String url) {\n if (!mBlockAds || url == null) {\n return false;\n }\n\n String domain;\n try {\n domain = getDomainName(url);\n } catch (URISyntaxException e) {\n Log.d(TAG, \"URL '\" + url + \"' is invalid\", e);\n return false;\n }\n\n boolean isOnBlacklist = mBlockedDomainsList.contains(domain);\n if (isOnBlacklist) {\n Log.d(TAG, \"URL '\" + url + \"' is an ad\");\n }\n return isOnBlacklist;\n }\n\n \/**\n * Returns the probable domain name for a given URL\n *\n * @param url the url to parse\n * @return returns the domain\n * @throws URISyntaxException throws an exception if the string cannot form a URI\n *\/\n @NonNull\n private static String getDomainName(@NonNull String url) throws URISyntaxException {\n int index = url.indexOf('\/', 8);\n if (index != -1) {\n url = url.substring(0, index);\n }\n\n URI uri = new URI(url);\n String domain = uri.getHost();\n if (domain == null) {\n return url;\n }\n\n return domain.startsWith(\"www.\") ? domain.substring(4) : domain;\n }\n\n \/**\n * This method reads through a hosts file and extracts the domains that should\n * be redirected to localhost (a.k.a. IP address 127.0.0.1). It can handle files that\n * simply have a list of hostnames to block, or it can handle a full blown hosts file.\n * It will strip out comments, references to the base IP address and just extract the\n * domains to be used\n *\n * @param context the context needed to read the file\n *\/\n private void loadHostsFile(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n String line;\n while ((line = reader.readLine()) != null) {\n if (!line.isEmpty() && !line.startsWith(COMMENT)) {\n line = line.replace(LOCAL_IP_V4, EMPTY)\n .replace(LOCAL_IP_V4_ALT, EMPTY)\n .replace(LOCAL_IP_V6, EMPTY)\n .replace(TAB, EMPTY);\n int comment = line.indexOf(COMMENT);\n if (comment >= 0) {\n line = line.substring(0, comment);\n }\n line = line.trim();\n if (!line.isEmpty() && !line.equals(LOCALHOST)) {\n while (line.contains(SPACE)) {\n int space = line.indexOf(SPACE);\n String host = line.substring(0, space);\n mBlockedDomainsList.add(host.trim());\n line = line.substring(space, line.length()).trim();\n }\n mBlockedDomainsList.add(line.trim());\n }\n }\n }\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage acr.browser.lightning.utils;\n\nimport android.content.Context;\nimport android.content.res.AssetManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.util.Log;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.inject.Inject;\nimport javax.inject.Singleton;\n\nimport acr.browser.lightning.app.BrowserApp;\nimport acr.browser.lightning.constant.Constants;\nimport acr.browser.lightning.preference.PreferenceManager;\n\n@Singleton\npublic class AdBlock {\n\n private static final String TAG = \"AdBlock\";\n private static final String BLOCKED_DOMAINS_LIST_FILE_NAME = \"hosts.txt\";\n private static final String LOCAL_IP_V4 = \"127.0.0.1\";\n private static final String LOCAL_IP_V4_ALT = \"0.0.0.0\";\n private static final String LOCAL_IP_V6 = \"::1\";\n private static final String LOCALHOST = \"localhost\";\n private static final String COMMENT = \"#\";\n private static final String TAB = \"\\t\";\n private static final String SPACE = \" \";\n private static final String EMPTY = \"\";\n private final Set mBlockedDomainsList = new HashSet<>();\n private boolean mBlockAds;\n\n @Inject PreferenceManager mPreferenceManager;\n\n @Inject\n public AdBlock(@NonNull Context context) {\n BrowserApp.getAppComponent().inject(this);\n if (mBlockedDomainsList.isEmpty() && Constants.FULL_VERSION) {\n loadHostsFile(context);\n }\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n public void updatePreference() {\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n private void loadBlockedDomainsList(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n String line;\n while ((line = reader.readLine()) != null) {\n mBlockedDomainsList.add(line.trim());\n }\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n\n \/**\n * a method that determines if the given URL is an ad or not. It performs\n * a search of the URL's domain on the blocked domain hash set.\n *\n * @param url the URL to check for being an ad\n * @return true if it is an ad, false if it is not an ad\n *\/\n public boolean isAd(@Nullable String url) {\n if (!mBlockAds || url == null) {\n return false;\n }\n\n String domain;\n try {\n domain = getDomainName(url);\n } catch (URISyntaxException e) {\n Log.d(TAG, \"URL '\" + url + \"' is invalid\", e);\n return false;\n }\n\n boolean isOnBlacklist = mBlockedDomainsList.contains(domain);\n if (isOnBlacklist) {\n Log.d(TAG, \"URL '\" + url + \"' is an ad\");\n }\n return isOnBlacklist;\n }\n\n \/**\n * Returns the probable domain name for a given URL\n *\n * @param url the url to parse\n * @return returns the domain\n * @throws URISyntaxException throws an exception if the string cannot form a URI\n *\/\n @NonNull\n private static String getDomainName(@NonNull String url) throws URISyntaxException {\n int index = url.indexOf('\/', 8);\n if (index != -1) {\n url = url.substring(0, index);\n }\n\n URI uri = new URI(url);\n String domain = uri.getHost();\n if (domain == null) {\n return url;\n }\n\n return domain.startsWith(\"www.\") ? domain.substring(4) : domain;\n }\n\n \/**\n * This method reads through a hosts file and extracts the domains that should\n * be redirected to localhost (a.k.a. IP address 127.0.0.1). It can handle files that\n * simply have a list of hostnames to block, or it can handle a full blown hosts file.\n * It will strip out comments, references to the base IP address and just extract the\n * domains to be used\n *\n * @param context the context needed to read the file\n *\/\n private void loadHostsFile(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n String line;\n while ((line = reader.readLine()) != null) {\n if (!line.isEmpty() && !line.startsWith(COMMENT)) {\n line = line.replace(LOCAL_IP_V4, EMPTY)\n .replace(LOCAL_IP_V4_ALT, EMPTY)\n .replace(LOCAL_IP_V6, EMPTY)\n .replace(TAB, EMPTY);\n int comment = line.indexOf(COMMENT);\n if (comment >= 0) {\n line = line.substring(0, comment);\n }\n line = line.trim();\n if (!line.isEmpty() && !line.equals(LOCALHOST)) {\n while (line.contains(SPACE)) {\n int space = line.indexOf(SPACE);\n String host = line.substring(0, space);\n mBlockedDomainsList.add(host.trim());\n line = line.substring(space, line.length()).trim();\n }\n mBlockedDomainsList.add(line.trim());\n }\n }\n }\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage acr.browser.lightning.utils;\n\nimport android.content.Context;\nimport android.content.res.AssetManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.util.Log;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.inject.Inject;\nimport javax.inject.Singleton;\n\nimport acr.browser.lightning.app.BrowserApp;\nimport acr.browser.lightning.constant.Constants;\nimport acr.browser.lightning.preference.PreferenceManager;\n\n@Singleton\npublic class AdBlock {\n\n private static final String TAG = \"AdBlock\";\n private static final String BLOCKED_DOMAINS_LIST_FILE_NAME = \"hosts.txt\";\n private static final String LOCAL_IP_V4 = \"127.0.0.1\";\n private static final String LOCAL_IP_V4_ALT = \"0.0.0.0\";\n private static final String LOCAL_IP_V6 = \"::1\";\n private static final String LOCALHOST = \"localhost\";\n private static final String COMMENT = \"#\";\n private static final String TAB = \"\\t\";\n private static final String SPACE = \" \";\n private static final String EMPTY = \"\";\n private final Set mBlockedDomainsList = new HashSet<>();\n private boolean mBlockAds;\n\n @Inject PreferenceManager mPreferenceManager;\n\n @Inject\n public AdBlock(@NonNull Context context) {\n BrowserApp.getAppComponent().inject(this);\n if (mBlockedDomainsList.isEmpty() && Constants.FULL_VERSION) {\n loadHostsFile(context);\n }\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n public void updatePreference() {\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n private void loadBlockedDomainsList(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n String line;\n while ((line = reader.readLine()) != null) {\n mBlockedDomainsList.add(line.trim());\n }\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n\n \/**\n * a method that determines if the given URL is an ad or not. It performs\n * a search of the URL's domain on the blocked domain hash set.\n *\n * @param url the URL to check for being an ad\n * @return true if it is an ad, false if it is not an ad\n *\/\n public boolean isAd(@Nullable String url) {\n if (!mBlockAds || url == null) {\n return false;\n }\n\n String domain;\n try {\n domain = getDomainName(url);\n } catch (URISyntaxException e) {\n Log.d(TAG, \"URL '\" + url + \"' is invalid\", e);\n return false;\n }\n\n boolean isOnBlacklist = mBlockedDomainsList.contains(domain);\n if (isOnBlacklist) {\n Log.d(TAG, \"URL '\" + url + \"' is an ad\");\n }\n return isOnBlacklist;\n }\n\n \/**\n * Returns the probable domain name for a given URL\n *\n * @param url the url to parse\n * @return returns the domain\n * @throws URISyntaxException throws an exception if the string cannot form a URI\n *\/\n @NonNull\n private static String getDomainName(@NonNull String url) throws URISyntaxException {\n int index = url.indexOf('\/', 8);\n if (index != -1) {\n url = url.substring(0, index);\n }\n\n URI uri = new URI(url);\n String domain = uri.getHost();\n if (domain == null) {\n return url;\n }\n\n return domain.startsWith(\"www.\") ? domain.substring(4) : domain;\n }\n\n \/**\n * This method reads through a hosts file and extracts the domains that should\n * be redirected to localhost (a.k.a. IP address 127.0.0.1). It can handle files that\n * simply have a list of hostnames to block, or it can handle a full blown hosts file.\n * It will strip out comments, references to the base IP address and just extract the\n * domains to be used\n *\n * @param context the context needed to read the file\n *\/\n private void loadHostsFile(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n String line;\n while ((line = reader.readLine()) != null) {\n if (!line.isEmpty() && !line.startsWith(COMMENT)) {\n line = line.replace(LOCAL_IP_V4, EMPTY)\n .replace(LOCAL_IP_V4_ALT, EMPTY)\n .replace(LOCAL_IP_V6, EMPTY)\n .replace(TAB, EMPTY);\n int comment = line.indexOf(COMMENT);\n if (comment >= 0) {\n line = line.substring(0, comment);\n }\n line = line.trim();\n if (!line.isEmpty() && !line.equals(LOCALHOST)) {\n while (line.contains(SPACE)) {\n int space = line.indexOf(SPACE);\n String host = line.substring(0, space);\n mBlockedDomainsList.add(host.trim());\n line = line.substring(space, line.length()).trim();\n }\n mBlockedDomainsList.add(line.trim());\n }\n }\n }\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nImprove the performance of adblocking code by utilizing StringBuilder. Write the entire code and no other text in the response.\n\n### Concepts:\n[+] StringBuilder\n[in] loadHostsFile function\n[implement] void replace(@NonNull StringBuilder stringBuilder, @NonNull String toReplace, @NonNull String replacement)\n[implement] void trim(@NonNull StringBuilder stringBuilder)\n[implement] boolean isEmpty(@NonNull StringBuilder stringBuilder)\n[implement] boolean startsWith(@NonNull StringBuilder stringBuilder, @NonNull String start)\n[implement] boolean contains(@NonNull StringBuilder stringBuilder, @NonNull String contains)\n[implement] boolean equals(@NonNull StringBuilder stringBuilder, @NonNull String equal)\n\n### Given program:\n```java\npackage acr.browser.lightning.utils;\n\nimport android.content.Context;\nimport android.content.res.AssetManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.util.Log;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.inject.Inject;\nimport javax.inject.Singleton;\n\nimport acr.browser.lightning.app.BrowserApp;\nimport acr.browser.lightning.constant.Constants;\nimport acr.browser.lightning.preference.PreferenceManager;\n\n@Singleton\npublic class AdBlock {\n\n private static final String TAG = \"AdBlock\";\n private static final String BLOCKED_DOMAINS_LIST_FILE_NAME = \"hosts.txt\";\n private static final String LOCAL_IP_V4 = \"127.0.0.1\";\n private static final String LOCAL_IP_V4_ALT = \"0.0.0.0\";\n private static final String LOCAL_IP_V6 = \"::1\";\n private static final String LOCALHOST = \"localhost\";\n private static final String COMMENT = \"#\";\n private static final String TAB = \"\\t\";\n private static final String SPACE = \" \";\n private static final String EMPTY = \"\";\n private final Set mBlockedDomainsList = new HashSet<>();\n private boolean mBlockAds;\n\n @Inject PreferenceManager mPreferenceManager;\n\n @Inject\n public AdBlock(@NonNull Context context) {\n BrowserApp.getAppComponent().inject(this);\n if (mBlockedDomainsList.isEmpty() && Constants.FULL_VERSION) {\n loadHostsFile(context);\n }\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n public void updatePreference() {\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n private void loadBlockedDomainsList(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n String line;\n while ((line = reader.readLine()) != null) {\n mBlockedDomainsList.add(line.trim());\n }\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n\n \/**\n * a method that determines if the given URL is an ad or not. It performs\n * a search of the URL's domain on the blocked domain hash set.\n *\n * @param url the URL to check for being an ad\n * @return true if it is an ad, false if it is not an ad\n *\/\n public boolean isAd(@Nullable String url) {\n if (!mBlockAds || url == null) {\n return false;\n }\n\n String domain;\n try {\n domain = getDomainName(url);\n } catch (URISyntaxException e) {\n Log.d(TAG, \"URL '\" + url + \"' is invalid\", e);\n return false;\n }\n\n boolean isOnBlacklist = mBlockedDomainsList.contains(domain);\n if (isOnBlacklist) {\n Log.d(TAG, \"URL '\" + url + \"' is an ad\");\n }\n return isOnBlacklist;\n }\n\n \/**\n * Returns the probable domain name for a given URL\n *\n * @param url the url to parse\n * @return returns the domain\n * @throws URISyntaxException throws an exception if the string cannot form a URI\n *\/\n @NonNull\n private static String getDomainName(@NonNull String url) throws URISyntaxException {\n int index = url.indexOf('\/', 8);\n if (index != -1) {\n url = url.substring(0, index);\n }\n\n URI uri = new URI(url);\n String domain = uri.getHost();\n if (domain == null) {\n return url;\n }\n\n return domain.startsWith(\"www.\") ? domain.substring(4) : domain;\n }\n\n \/**\n * This method reads through a hosts file and extracts the domains that should\n * be redirected to localhost (a.k.a. IP address 127.0.0.1). It can handle files that\n * simply have a list of hostnames to block, or it can handle a full blown hosts file.\n * It will strip out comments, references to the base IP address and just extract the\n * domains to be used\n *\n * @param context the context needed to read the file\n *\/\n private void loadHostsFile(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n String line;\n while ((line = reader.readLine()) != null) {\n if (!line.isEmpty() && !line.startsWith(COMMENT)) {\n line = line.replace(LOCAL_IP_V4, EMPTY)\n .replace(LOCAL_IP_V4_ALT, EMPTY)\n .replace(LOCAL_IP_V6, EMPTY)\n .replace(TAB, EMPTY);\n int comment = line.indexOf(COMMENT);\n if (comment >= 0) {\n line = line.substring(0, comment);\n }\n line = line.trim();\n if (!line.isEmpty() && !line.equals(LOCALHOST)) {\n while (line.contains(SPACE)) {\n int space = line.indexOf(SPACE);\n String host = line.substring(0, space);\n mBlockedDomainsList.add(host.trim());\n line = line.substring(space, line.length()).trim();\n }\n mBlockedDomainsList.add(line.trim());\n }\n }\n }\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage org.fdroid.fdroid;\n\nimport android.app.IntentService;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.net.Uri;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport org.fdroid.fdroid.data.Apk;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.InstalledAppProviderService;\nimport org.fdroid.fdroid.installer.ApkCache;\nimport org.fdroid.fdroid.installer.InstallManagerService;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\n\/**\n * Scans the list of downloaded .apk files in the cache for each app which can be updated.\n * If a valid .apk file is found then it will tell the {@link AppUpdateStatusManager} that it is\n * {@link AppUpdateStatusManager.Status#ReadyToInstall}. This is an {@link IntentService} so as to\n * run on a background thread, as it hits the disk a bit to figure out the hash of each downloaded\n * file.\n *\/\n@SuppressWarnings(\"LineLength\")\npublic class AppUpdateStatusService extends IntentService {\n\n private static final String TAG = \"AppUpdateStatusService\";\n\n \/**\n * Queue up a background scan of all downloaded apk files to see if we should notify the user\n * that they are ready to install.\n *\/\n public static void scanDownloadedApks(Context context) {\n context.startService(new Intent(context, AppUpdateStatusService.class));\n }\n\n public AppUpdateStatusService() {\n super(\"AppUpdateStatusService\");\n }\n\n @Override\n protected void onHandleIntent(@Nullable Intent intent) {\n Utils.debugLog(TAG, \"Scanning apk cache to see if we need to prompt the user to install any apks.\");\n File cacheDir = ApkCache.getApkCacheDir(this);\n if (cacheDir == null) {\n return;\n }\n String[] cacheDirList = cacheDir.list();\n if (cacheDirList == null) {\n return;\n }\n List apksReadyToInstall = new ArrayList<>();\n for (String repoDirName : cacheDirList) {\n File repoDir = new File(cacheDir, repoDirName);\n String[] apks = repoDir.list();\n if (apks == null) {\n continue;\n }\n for (String apkFileName : apks) {\n Apk apk = processDownloadedApk(new File(repoDir, apkFileName));\n if (apk != null) {\n Log.i(TAG, \"Found downloaded apk \" + apk.packageName + \". Notifying user that it should be installed.\");\n apksReadyToInstall.add(apk);\n }\n }\n }\n\n if (apksReadyToInstall.size() > 0) {\n AppUpdateStatusManager.getInstance(this).addApks(apksReadyToInstall, AppUpdateStatusManager.Status.ReadyToInstall);\n InstallManagerService.managePreviouslyDownloadedApks(this);\n }\n }\n\n \/**\n * Verifies that {@param apkPath} is a valid apk which the user intends to install.\n * If it is corrupted to the point where {@link PackageManager} can't read it, doesn't match the hash of any apk\n * we know about in our database, is not pending install, or is already installed, then it will return null.\n *\/\n @Nullable\n private Apk processDownloadedApk(File apkPath) {\n Utils.debugLog(TAG, \"Checking \" + apkPath);\n PackageInfo downloadedInfo = getPackageManager().getPackageArchiveInfo(apkPath.getAbsolutePath(), PackageManager.GET_GIDS);\n if (downloadedInfo == null) {\n Log.i(TAG, \"Skipping \" + apkPath + \" because PackageManager was unable to read it.\");\n return null;\n }\n\n Utils.debugLog(TAG, \"Found package for \" + downloadedInfo.packageName + \", checking its hash to see if it downloaded correctly.\");\n Apk downloadedApk = findApkMatchingHash(apkPath);\n if (downloadedApk == null) {\n Log.i(TAG, \"Either the apk wasn't downloaded fully, or the repo it came from has been disabled. Either way, not notifying the user about it.\");\n return null;\n }\n\n if (!AppUpdateStatusManager.getInstance(this).isPendingInstall(downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is NOT pending install, probably just left over from a previous install.\");\n return null;\n }\n\n try {\n PackageInfo info = getPackageManager().getPackageInfo(downloadedApk.packageName, 0);\n File pathToInstalled = InstalledAppProviderService.getPathToInstalledApk(info);\n if (pathToInstalled != null && pathToInstalled.canRead() &&\n pathToInstalled.length() == downloadedApk.size && \/\/ Check size before hash for performance.\n TextUtils.equals(Utils.getBinaryHash(pathToInstalled, \"sha256\"), downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is pending install, but we already have the correct version installed.\");\n AppUpdateStatusManager.getInstance(this).markAsNoLongerPendingInstall(downloadedApk.getUrl());\n return null;\n }\n } catch (PackageManager.NameNotFoundException ignored) { }\n\n Utils.debugLog(TAG, downloadedApk.packageName + \" is pending install, so we need to notify the user about installing it.\");\n return downloadedApk;\n }\n\n \/**\n * There could be multiple apks with the same hash, provided by different repositories.\n * This method looks for all matching records in the database. It then asks each of these\n * {@link Apk} instances where they expect to be downloaded. If they expect to be downloaded\n * to {@param apkPath} then that instance is returned.\n *\n * If no files have a matching hash, or only those which don't belong to the correct repo, then\n * this will return null.\n *\/\n @Nullable\n private Apk findApkMatchingHash(File apkPath) {\n\n \/\/ NOTE: This presumes SHA256 is the only supported hash. It seems like that is an assumption\n \/\/ in more than one place in the F-Droid client. If this becomes a problem in the future, we\n \/\/ can query the Apk table for `SELECT DISTINCT hashType FROM fdroid_apk` and then we can just\n \/\/ try each of the hash types that have been specified in the metadata. Seems a bit overkill\n \/\/ at the time of writing though.\n String hash = Utils.getBinaryHash(apkPath, \"sha256\");\n\n List apksMatchingHash = ApkProvider.Helper.findApksByHash(this, hash);\n Utils.debugLog(TAG, \"Found \" + apksMatchingHash.size() + \" apk(s) matching the hash \" + hash);\n\n for (Apk apk : apksMatchingHash) {\n if (apkPath.equals(ApkCache.getApkDownloadPath(this, Uri.parse(apk.getUrl())))) {\n return apk;\n }\n }\n\n return null;\n }\n}\n\nCode-B:\npackage org.fdroid.fdroid;\n\nimport android.app.IntentService;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.net.Uri;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport org.fdroid.fdroid.data.Apk;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.InstalledAppProviderService;\nimport org.fdroid.fdroid.installer.ApkCache;\nimport org.fdroid.fdroid.installer.InstallManagerService;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\n\/**\n * Scans the list of downloaded .apk files in the cache for each app which can be updated.\n * If a valid .apk file is found then it will tell the {@link AppUpdateStatusManager} that it is\n * {@link AppUpdateStatusManager.Status#ReadyToInstall}. This is an {@link IntentService} so as to\n * run on a background thread, as it hits the disk a bit to figure out the hash of each downloaded\n * file.\n *\/\n@SuppressWarnings(\"LineLength\")\npublic class AppUpdateStatusService extends IntentService {\n\n private static final String TAG = \"AppUpdateStatusService\";\n\n \/**\n * Queue up a background scan of all downloaded apk files to see if we should notify the user\n * that they are ready to install.\n *\/\n public static void scanDownloadedApks(Context context) {\n context.startService(new Intent(context, AppUpdateStatusService.class));\n }\n\n public AppUpdateStatusService() {\n super(\"AppUpdateStatusService\");\n }\n\n @Override\n protected void onHandleIntent(@Nullable Intent intent) {\n Utils.debugLog(TAG, \"Scanning apk cache to see if we need to prompt the user to install any apks.\");\n File cacheDir = ApkCache.getApkCacheDir(this);\n if (cacheDir == null) {\n return;\n }\n String[] cacheDirList = cacheDir.list();\n if (cacheDirList == null) {\n return;\n }\n List apksReadyToInstall = new ArrayList<>();\n for (String repoDirName : cacheDirList) {\n File repoDir = new File(cacheDir, repoDirName);\n String[] apks = repoDir.list();\n if (apks == null) {\n continue;\n }\n for (String apkFileName : apks) {\n Apk apk = processDownloadedApk(new File(repoDir, apkFileName));\n if (apk != null) {\n Log.i(TAG, \"Found downloaded apk \" + apk.packageName + \". Notifying user that it should be installed.\");\n apksReadyToInstall.add(apk);\n }\n }\n }\n\n if (apksReadyToInstall.size() > 0) {\n AppUpdateStatusManager.getInstance(this).addApks(apksReadyToInstall, AppUpdateStatusManager.Status.ReadyToInstall);\n InstallManagerService.managePreviouslyDownloadedApks(this);\n }\n }\n\n \/**\n * Verifies that {@param apkPath} is a valid apk which the user intends to install.\n * If it is corrupted to the point where {@link PackageManager} can't read it, doesn't match the hash of any apk\n * we know about in our database, is not pending install, or is already installed, then it will return null.\n *\/\n @Nullable\n private Apk processDownloadedApk(File apkPath) {\n Utils.debugLog(TAG, \"Checking \" + apkPath);\n PackageInfo downloadedInfo = getPackageManager().getPackageArchiveInfo(apkPath.getAbsolutePath(), PackageManager.GET_GIDS);\n if (downloadedInfo == null) {\n Log.i(TAG, \"Skipping \" + apkPath + \" because PackageManager was unable to read it.\");\n return null;\n }\n\n Utils.debugLog(TAG, \"Found package for \" + downloadedInfo.packageName + \", checking its hash to see if it downloaded correctly.\");\n Apk downloadedApk = findApkMatchingHash(apkPath);\n if (downloadedApk == null) {\n Log.i(TAG, \"Either the apk wasn't downloaded fully, or the repo it came from has been disabled. Either way, not notifying the user about it.\");\n return null;\n }\n\n if (!AppUpdateStatusManager.getInstance(this).isPendingInstall(downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is NOT pending install, probably just left over from a previous install.\");\n return null;\n }\n\n try {\n PackageInfo info = getPackageManager().getPackageInfo(downloadedApk.packageName, 0);\n File pathToInstalled = InstalledAppProviderService.getPathToInstalledApk(info);\n if (pathToInstalled != null && pathToInstalled.canRead() &&\n TextUtils.equals(Utils.getBinaryHash(pathToInstalled, \"sha256\"), downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is pending install, but we already have the correct version installed.\");\n AppUpdateStatusManager.getInstance(this).markAsNoLongerPendingInstall(downloadedApk.getUrl());\n return null;\n }\n } catch (PackageManager.NameNotFoundException ignored) { }\n\n Utils.debugLog(TAG, downloadedApk.packageName + \" is pending install, so we need to notify the user about installing it.\");\n return downloadedApk;\n }\n\n \/**\n * There could be multiple apks with the same hash, provided by different repositories.\n * This method looks for all matching records in the database. It then asks each of these\n * {@link Apk} instances where they expect to be downloaded. If they expect to be downloaded\n * to {@param apkPath} then that instance is returned.\n *\n * If no files have a matching hash, or only those which don't belong to the correct repo, then\n * this will return null.\n *\/\n @Nullable\n private Apk findApkMatchingHash(File apkPath) {\n\n \/\/ NOTE: This presumes SHA256 is the only supported hash. It seems like that is an assumption\n \/\/ in more than one place in the F-Droid client. If this becomes a problem in the future, we\n \/\/ can query the Apk table for `SELECT DISTINCT hashType FROM fdroid_apk` and then we can just\n \/\/ try each of the hash types that have been specified in the metadata. Seems a bit overkill\n \/\/ at the time of writing though.\n String hash = Utils.getBinaryHash(apkPath, \"sha256\");\n\n List apksMatchingHash = ApkProvider.Helper.findApksByHash(this, hash);\n Utils.debugLog(TAG, \"Found \" + apksMatchingHash.size() + \" apk(s) matching the hash \" + hash);\n\n for (Apk apk : apksMatchingHash) {\n if (apkPath.equals(ApkCache.getApkDownloadPath(this, Uri.parse(apk.getUrl())))) {\n return apk;\n }\n }\n\n return null;\n }\n}\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage org.fdroid.fdroid;\n\nimport android.app.IntentService;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.net.Uri;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport org.fdroid.fdroid.data.Apk;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.InstalledAppProviderService;\nimport org.fdroid.fdroid.installer.ApkCache;\nimport org.fdroid.fdroid.installer.InstallManagerService;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\n\/**\n * Scans the list of downloaded .apk files in the cache for each app which can be updated.\n * If a valid .apk file is found then it will tell the {@link AppUpdateStatusManager} that it is\n * {@link AppUpdateStatusManager.Status#ReadyToInstall}. This is an {@link IntentService} so as to\n * run on a background thread, as it hits the disk a bit to figure out the hash of each downloaded\n * file.\n *\/\n@SuppressWarnings(\"LineLength\")\npublic class AppUpdateStatusService extends IntentService {\n\n private static final String TAG = \"AppUpdateStatusService\";\n\n \/**\n * Queue up a background scan of all downloaded apk files to see if we should notify the user\n * that they are ready to install.\n *\/\n public static void scanDownloadedApks(Context context) {\n context.startService(new Intent(context, AppUpdateStatusService.class));\n }\n\n public AppUpdateStatusService() {\n super(\"AppUpdateStatusService\");\n }\n\n @Override\n protected void onHandleIntent(@Nullable Intent intent) {\n Utils.debugLog(TAG, \"Scanning apk cache to see if we need to prompt the user to install any apks.\");\n File cacheDir = ApkCache.getApkCacheDir(this);\n if (cacheDir == null) {\n return;\n }\n String[] cacheDirList = cacheDir.list();\n if (cacheDirList == null) {\n return;\n }\n List apksReadyToInstall = new ArrayList<>();\n for (String repoDirName : cacheDirList) {\n File repoDir = new File(cacheDir, repoDirName);\n String[] apks = repoDir.list();\n if (apks == null) {\n continue;\n }\n for (String apkFileName : apks) {\n Apk apk = processDownloadedApk(new File(repoDir, apkFileName));\n if (apk != null) {\n Log.i(TAG, \"Found downloaded apk \" + apk.packageName + \". Notifying user that it should be installed.\");\n apksReadyToInstall.add(apk);\n }\n }\n }\n\n if (apksReadyToInstall.size() > 0) {\n AppUpdateStatusManager.getInstance(this).addApks(apksReadyToInstall, AppUpdateStatusManager.Status.ReadyToInstall);\n InstallManagerService.managePreviouslyDownloadedApks(this);\n }\n }\n\n \/**\n * Verifies that {@param apkPath} is a valid apk which the user intends to install.\n * If it is corrupted to the point where {@link PackageManager} can't read it, doesn't match the hash of any apk\n * we know about in our database, is not pending install, or is already installed, then it will return null.\n *\/\n @Nullable\n private Apk processDownloadedApk(File apkPath) {\n Utils.debugLog(TAG, \"Checking \" + apkPath);\n PackageInfo downloadedInfo = getPackageManager().getPackageArchiveInfo(apkPath.getAbsolutePath(), PackageManager.GET_GIDS);\n if (downloadedInfo == null) {\n Log.i(TAG, \"Skipping \" + apkPath + \" because PackageManager was unable to read it.\");\n return null;\n }\n\n Utils.debugLog(TAG, \"Found package for \" + downloadedInfo.packageName + \", checking its hash to see if it downloaded correctly.\");\n Apk downloadedApk = findApkMatchingHash(apkPath);\n if (downloadedApk == null) {\n Log.i(TAG, \"Either the apk wasn't downloaded fully, or the repo it came from has been disabled. Either way, not notifying the user about it.\");\n return null;\n }\n\n if (!AppUpdateStatusManager.getInstance(this).isPendingInstall(downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is NOT pending install, probably just left over from a previous install.\");\n return null;\n }\n\n try {\n PackageInfo info = getPackageManager().getPackageInfo(downloadedApk.packageName, 0);\n File pathToInstalled = InstalledAppProviderService.getPathToInstalledApk(info);\n if (pathToInstalled != null && pathToInstalled.canRead() &&\n TextUtils.equals(Utils.getBinaryHash(pathToInstalled, \"sha256\"), downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is pending install, but we already have the correct version installed.\");\n AppUpdateStatusManager.getInstance(this).markAsNoLongerPendingInstall(downloadedApk.getUrl());\n return null;\n }\n } catch (PackageManager.NameNotFoundException ignored) { }\n\n Utils.debugLog(TAG, downloadedApk.packageName + \" is pending install, so we need to notify the user about installing it.\");\n return downloadedApk;\n }\n\n \/**\n * There could be multiple apks with the same hash, provided by different repositories.\n * This method looks for all matching records in the database. It then asks each of these\n * {@link Apk} instances where they expect to be downloaded. If they expect to be downloaded\n * to {@param apkPath} then that instance is returned.\n *\n * If no files have a matching hash, or only those which don't belong to the correct repo, then\n * this will return null.\n *\/\n @Nullable\n private Apk findApkMatchingHash(File apkPath) {\n\n \/\/ NOTE: This presumes SHA256 is the only supported hash. It seems like that is an assumption\n \/\/ in more than one place in the F-Droid client. If this becomes a problem in the future, we\n \/\/ can query the Apk table for `SELECT DISTINCT hashType FROM fdroid_apk` and then we can just\n \/\/ try each of the hash types that have been specified in the metadata. Seems a bit overkill\n \/\/ at the time of writing though.\n String hash = Utils.getBinaryHash(apkPath, \"sha256\");\n\n List apksMatchingHash = ApkProvider.Helper.findApksByHash(this, hash);\n Utils.debugLog(TAG, \"Found \" + apksMatchingHash.size() + \" apk(s) matching the hash \" + hash);\n\n for (Apk apk : apksMatchingHash) {\n if (apkPath.equals(ApkCache.getApkDownloadPath(this, Uri.parse(apk.getUrl())))) {\n return apk;\n }\n }\n\n return null;\n }\n}\n\nCode-B:\npackage org.fdroid.fdroid;\n\nimport android.app.IntentService;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.net.Uri;\nimport android.support.annotation.Nullable;\nimport android.text.TextUtils;\nimport android.util.Log;\n\nimport org.fdroid.fdroid.data.Apk;\nimport org.fdroid.fdroid.data.ApkProvider;\nimport org.fdroid.fdroid.data.InstalledAppProviderService;\nimport org.fdroid.fdroid.installer.ApkCache;\nimport org.fdroid.fdroid.installer.InstallManagerService;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.List;\n\n\/**\n * Scans the list of downloaded .apk files in the cache for each app which can be updated.\n * If a valid .apk file is found then it will tell the {@link AppUpdateStatusManager} that it is\n * {@link AppUpdateStatusManager.Status#ReadyToInstall}. This is an {@link IntentService} so as to\n * run on a background thread, as it hits the disk a bit to figure out the hash of each downloaded\n * file.\n *\/\n@SuppressWarnings(\"LineLength\")\npublic class AppUpdateStatusService extends IntentService {\n\n private static final String TAG = \"AppUpdateStatusService\";\n\n \/**\n * Queue up a background scan of all downloaded apk files to see if we should notify the user\n * that they are ready to install.\n *\/\n public static void scanDownloadedApks(Context context) {\n context.startService(new Intent(context, AppUpdateStatusService.class));\n }\n\n public AppUpdateStatusService() {\n super(\"AppUpdateStatusService\");\n }\n\n @Override\n protected void onHandleIntent(@Nullable Intent intent) {\n Utils.debugLog(TAG, \"Scanning apk cache to see if we need to prompt the user to install any apks.\");\n File cacheDir = ApkCache.getApkCacheDir(this);\n if (cacheDir == null) {\n return;\n }\n String[] cacheDirList = cacheDir.list();\n if (cacheDirList == null) {\n return;\n }\n List apksReadyToInstall = new ArrayList<>();\n for (String repoDirName : cacheDirList) {\n File repoDir = new File(cacheDir, repoDirName);\n String[] apks = repoDir.list();\n if (apks == null) {\n continue;\n }\n for (String apkFileName : apks) {\n Apk apk = processDownloadedApk(new File(repoDir, apkFileName));\n if (apk != null) {\n Log.i(TAG, \"Found downloaded apk \" + apk.packageName + \". Notifying user that it should be installed.\");\n apksReadyToInstall.add(apk);\n }\n }\n }\n\n if (apksReadyToInstall.size() > 0) {\n AppUpdateStatusManager.getInstance(this).addApks(apksReadyToInstall, AppUpdateStatusManager.Status.ReadyToInstall);\n InstallManagerService.managePreviouslyDownloadedApks(this);\n }\n }\n\n \/**\n * Verifies that {@param apkPath} is a valid apk which the user intends to install.\n * If it is corrupted to the point where {@link PackageManager} can't read it, doesn't match the hash of any apk\n * we know about in our database, is not pending install, or is already installed, then it will return null.\n *\/\n @Nullable\n private Apk processDownloadedApk(File apkPath) {\n Utils.debugLog(TAG, \"Checking \" + apkPath);\n PackageInfo downloadedInfo = getPackageManager().getPackageArchiveInfo(apkPath.getAbsolutePath(), PackageManager.GET_GIDS);\n if (downloadedInfo == null) {\n Log.i(TAG, \"Skipping \" + apkPath + \" because PackageManager was unable to read it.\");\n return null;\n }\n\n Utils.debugLog(TAG, \"Found package for \" + downloadedInfo.packageName + \", checking its hash to see if it downloaded correctly.\");\n Apk downloadedApk = findApkMatchingHash(apkPath);\n if (downloadedApk == null) {\n Log.i(TAG, \"Either the apk wasn't downloaded fully, or the repo it came from has been disabled. Either way, not notifying the user about it.\");\n return null;\n }\n\n if (!AppUpdateStatusManager.getInstance(this).isPendingInstall(downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is NOT pending install, probably just left over from a previous install.\");\n return null;\n }\n\n try {\n PackageInfo info = getPackageManager().getPackageInfo(downloadedApk.packageName, 0);\n File pathToInstalled = InstalledAppProviderService.getPathToInstalledApk(info);\n if (pathToInstalled != null && pathToInstalled.canRead() &&\n pathToInstalled.length() == downloadedApk.size && \/\/ Check size before hash for performance.\n TextUtils.equals(Utils.getBinaryHash(pathToInstalled, \"sha256\"), downloadedApk.hash)) {\n Log.i(TAG, downloadedApk.packageName + \" is pending install, but we already have the correct version installed.\");\n AppUpdateStatusManager.getInstance(this).markAsNoLongerPendingInstall(downloadedApk.getUrl());\n return null;\n }\n } catch (PackageManager.NameNotFoundException ignored) { }\n\n Utils.debugLog(TAG, downloadedApk.packageName + \" is pending install, so we need to notify the user about installing it.\");\n return downloadedApk;\n }\n\n \/**\n * There could be multiple apks with the same hash, provided by different repositories.\n * This method looks for all matching records in the database. It then asks each of these\n * {@link Apk} instances where they expect to be downloaded. If they expect to be downloaded\n * to {@param apkPath} then that instance is returned.\n *\n * If no files have a matching hash, or only those which don't belong to the correct repo, then\n * this will return null.\n *\/\n @Nullable\n private Apk findApkMatchingHash(File apkPath) {\n\n \/\/ NOTE: This presumes SHA256 is the only supported hash. It seems like that is an assumption\n \/\/ in more than one place in the F-Droid client. If this becomes a problem in the future, we\n \/\/ can query the Apk table for `SELECT DISTINCT hashType FROM fdroid_apk` and then we can just\n \/\/ try each of the hash types that have been specified in the metadata. Seems a bit overkill\n \/\/ at the time of writing though.\n String hash = Utils.getBinaryHash(apkPath, \"sha256\");\n\n List apksMatchingHash = ApkProvider.Helper.findApksByHash(this, hash);\n Utils.debugLog(TAG, \"Found \" + apksMatchingHash.size() + \" apk(s) matching the hash \" + hash);\n\n for (Apk apk : apksMatchingHash) {\n if (apkPath.equals(ApkCache.getApkDownloadPath(this, Uri.parse(apk.getUrl())))) {\n return apk;\n }\n }\n\n return null;\n }\n}\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/bpeterson09\/AvareGUI\/commit\/d63eaed53863bce9b3a1b8ac5cddeee0dd1c6f2a","commit_message":"'\\\\\"Optimize draw shape\\\\ndraw all the lines at the same time\\\\nreuse offsetX and offsetY values.\\\\n\\\\\"'","source_code":"\/*\nCopyright (c) 2012, Apps4Av Inc. (apps4av.com) \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\npackage com.ds.avare.shapes;\n\nimport java.util.LinkedList;\n\nimport com.ds.avare.place.Plan;\nimport com.ds.avare.position.Coordinate;\nimport com.ds.avare.position.Movement;\nimport com.ds.avare.position.Origin;\nimport com.ds.avare.position.Scale;\nimport com.sromku.polygon.Point;\nimport com.sromku.polygon.Polygon;\nimport com.sromku.polygon.Polygon.Builder;\n\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.Typeface;\n\n\/**\n * @author zkhan\n *\n *\/\npublic abstract class Shape {\n\n protected LinkedList mCoords;\n protected double mLonMin;\n protected double mLonMax;\n protected double mLatMin;\n protected double mLatMax;\n \n protected String mText;\n \n private Builder mPolyBuilder;\n private Polygon mPoly;\n \n \/**\n * \n *\/\n public Shape(String label) {\n mCoords = new LinkedList();\n mLonMin = 180;\n mLonMax = -180;\n mLatMin = 180;\n mLatMax = -180;\n mText = label;\n mPolyBuilder = Polygon.Builder(); \n }\n\n \/**\n * \n * @param coords\n *\/\n public void add(double lon, double lat, boolean issep) {\n \tadd(lon,lat,issep, 0);\n }\n \n public void add(double lon, double lat, boolean issep, int segment) {\n Coordinate c = new Coordinate(lon, lat);\n if(issep) {\n c.makeSeparate();\n }\n c.setSegment(segment);\n \n mCoords.add(c);\n mPolyBuilder.addVertex(new Point((float)lon, (float)lat));\n \n \/*\n * Calculate start points\n *\/\n if(lon < mLonMin) {\n mLonMin = lon;\n }\n if(lon >= mLonMax) {\n mLonMax = lon;\n }\n if(lat < mLatMin) {\n mLatMin = lat;\n }\n if(lat >= mLatMax) {\n mLatMax = lat;\n }\n }\n\n public void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack) {\n \tdrawShape(c, origin, scale,movement,paint,night, drawTrack, null);\n }\n \n \/**\n * This will draw the closed shape in canvas with given screen params\n * @param c\n * @param origin\n * @param scale\n * @param movement\n * @param paint\n *\/\n\tpublic void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack, Plan plan) {\n\n \/*\n * Do a tab on top of shape\n *\/\n \/*\n * Draw pivots at end of track\n *\/\n float width = paint.getStrokeWidth();\n int color = paint.getColor();\n \n \/\/ TrackShape type is used for a flight plan destination\n if (this instanceof TrackShape) {\n \n \/*\n * Draw background on track shapes, so draw twice\n *\/\n \tint cMax = getNumCoords();\n for(int coord = 0; coord < (cMax - 1); coord++) {\n float x1 = (float)origin.getOffsetX(mCoords.get(coord).getLongitude());\n float x2 = (float)origin.getOffsetX(mCoords.get(coord + 1).getLongitude());\n float y1 = (float)origin.getOffsetY(mCoords.get(coord).getLatitude());\n float y2 = (float)origin.getOffsetY(mCoords.get(coord + 1).getLatitude());;\n\n if(drawTrack) {\n\t paint.setStrokeWidth(width + 4);\n\t paint.setColor(night? Color.WHITE : Color.BLACK);\n\t c.drawLine(x1, y1, x2, y2, paint);\n\t paint.setStrokeWidth(width);\n\n\t if(null == plan) {\n\t \tpaint.setColor(color);\n\t } else {\n\t \tpaint.setColor(TrackShape.getLegColor(plan.findNextNotPassed(), mCoords.get(coord).getLeg()));\n\t }\n\n\t c.drawLine(x1, y1, x2, y2, paint);\n }\n\n\t\t\t\tif(mCoords.get(coord + 1).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x2, y2, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x2, y2, 8, paint);\n paint.setColor(color);\n }\n if(mCoords.get(coord).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x1, y1, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x1, y1, 8, paint);\n paint.setColor(color);\n }\n }\n } else {\n \/*\n * Draw the shape segment by segment\n *\/\n for(int coord = 0; coord < (getNumCoords() - 1); coord++) {\n float x1 = (float)origin.getOffsetX(mCoords.get(coord).getLongitude());\n float x2 = (float)origin.getOffsetX(mCoords.get(coord + 1).getLongitude());\n float y1 = (float)origin.getOffsetY(mCoords.get(coord).getLatitude());\n float y2 = (float)origin.getOffsetY(mCoords.get(coord + 1).getLatitude());;\n c.drawLine(x1, y1, x2, y2, paint);\n }\n }\n }\n \n \/**\n * \n * @return\n *\/\n public int getNumCoords() {\n return mCoords.size();\n }\n\n \/**\n * \n * @return\n *\/\n public double getLatitudeMinimum() {\n return mLatMin;\n }\n \n \/**\n * \n * @param lon\n * @param lat\n * @return\n *\/\n public String getTextIfTouched(double lon, double lat) {\n if(null == mPoly) {\n return null;\n }\n if(mPoly.contains(new Point((float)lon, (float)lat))) {\n return mText;\n }\n return null;\n }\n \n \/**\n * \n *\/\n public void makePolygon() {\n if(getNumCoords() > 2) {\n mPoly = mPolyBuilder.build();\n }\n } \n}\n","target_code":"\/*\nCopyright (c) 2012, Apps4Av Inc. (apps4av.com) \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\npackage com.ds.avare.shapes;\n\nimport java.util.LinkedList;\n\nimport com.ds.avare.place.Plan;\nimport com.ds.avare.position.Coordinate;\nimport com.ds.avare.position.Movement;\nimport com.ds.avare.position.Origin;\nimport com.ds.avare.position.Scale;\nimport com.sromku.polygon.Point;\nimport com.sromku.polygon.Polygon;\nimport com.sromku.polygon.Polygon.Builder;\n\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.Typeface;\n\n\/**\n * @author zkhan\n * @author plinel\n *\n *\/\npublic abstract class Shape {\n\n protected LinkedList mCoords;\n protected double mLonMin;\n protected double mLonMax;\n protected double mLatMin;\n protected double mLatMax;\n \n protected String mText;\n \n private Builder mPolyBuilder;\n private Polygon mPoly;\n \n \/**\n * \n *\/\n public Shape(String label) {\n mCoords = new LinkedList();\n mLonMin = 180;\n mLonMax = -180;\n mLatMin = 180;\n mLatMax = -180;\n mText = label;\n mPolyBuilder = Polygon.Builder(); \n }\n\n \/**\n * \n * @param coords\n *\/\n public void add(double lon, double lat, boolean issep) {\n \tadd(lon,lat,issep, 0);\n }\n \n public void add(double lon, double lat, boolean issep, int segment) {\n Coordinate c = new Coordinate(lon, lat);\n if(issep) {\n c.makeSeparate();\n }\n c.setSegment(segment);\n \n mCoords.add(c);\n mPolyBuilder.addVertex(new Point((float)lon, (float)lat));\n \n \/*\n * Calculate start points\n *\/\n if(lon < mLonMin) {\n mLonMin = lon;\n }\n if(lon >= mLonMax) {\n mLonMax = lon;\n }\n if(lat < mLatMin) {\n mLatMin = lat;\n }\n if(lat >= mLatMax) {\n mLatMax = lat;\n }\n }\n\n public void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack) {\n \tdrawShape(c, origin, scale,movement,paint,night, drawTrack, null);\n }\n \n \/**\n * This will draw the closed shape in canvas with given screen params\n * @param c\n * @param origin\n * @param scale\n * @param movement\n * @param paint\n *\/\n\tpublic void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack, Plan plan) {\n\n \/*\n * Do a tab on top of shape\n *\/\n \/*\n * Draw pivots at end of track\n *\/\n float width = paint.getStrokeWidth();\n int color = paint.getColor();\n \n \/\/ TrackShape type is used for a flight plan destination\n if (this instanceof TrackShape) {\n \n \/*\n * Draw background on track shapes, so draw twice\n *\/\n \tint cMax = getNumCoords();\n for(int coord = 0; coord < (cMax - 1); coord++) {\n float x1 = (float)origin.getOffsetX(mCoords.get(coord).getLongitude());\n float x2 = (float)origin.getOffsetX(mCoords.get(coord + 1).getLongitude());\n float y1 = (float)origin.getOffsetY(mCoords.get(coord).getLatitude());\n float y2 = (float)origin.getOffsetY(mCoords.get(coord + 1).getLatitude());;\n\n if(drawTrack) {\n\t paint.setStrokeWidth(width + 4);\n\t paint.setColor(night? Color.WHITE : Color.BLACK);\n\t c.drawLine(x1, y1, x2, y2, paint);\n\t paint.setStrokeWidth(width);\n\n\t if(null == plan) {\n\t \tpaint.setColor(color);\n\t } else {\n\t \tpaint.setColor(TrackShape.getLegColor(plan.findNextNotPassed(), mCoords.get(coord).getLeg()));\n\t }\n\n\t c.drawLine(x1, y1, x2, y2, paint);\n }\n\n\t\t\t\tif(mCoords.get(coord + 1).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x2, y2, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x2, y2, 8, paint);\n paint.setColor(color);\n }\n if(mCoords.get(coord).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x1, y1, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x1, y1, 8, paint);\n paint.setColor(color);\n }\n }\n } else {\n \/*\n * Draw the shape segment by segment\n *\/\n if(getNumCoords()>0) {\n float pts[] = new float[(getNumCoords()) * 4];\n int i = 0;\n int coord = 0;\n float x1 = (float) origin.getOffsetX(mCoords.get(coord).getLongitude());\n float y1 = (float) origin.getOffsetY(mCoords.get(coord).getLatitude());\n float x2;\n float y2;\n\n for (coord = 1; coord < getNumCoords(); coord++) {\n x2 = (float) origin.getOffsetX(mCoords.get(coord).getLongitude());\n y2 = (float) origin.getOffsetY(mCoords.get(coord).getLatitude());\n\n pts[i++] = x1;\n pts[i++] = y1;\n pts[i++] = x2;\n pts[i++] = y2;\n\n x1 = x2;\n y1 = y2;\n }\n c.drawLines(pts, paint);\n }\n }\n }\n \n \/**\n * \n * @return\n *\/\n public int getNumCoords() {\n return mCoords.size();\n }\n\n \/**\n * \n * @return\n *\/\n public double getLatitudeMinimum() {\n return mLatMin;\n }\n \n \/**\n * \n * @param lon\n * @param lat\n * @return\n *\/\n public String getTextIfTouched(double lon, double lat) {\n if(null == mPoly) {\n return null;\n }\n if(mPoly.contains(new Point((float)lon, (float)lat))) {\n return mText;\n }\n return null;\n }\n \n \/**\n * \n *\/\n public void makePolygon() {\n if(getNumCoords() > 2) {\n mPoly = mPolyBuilder.build();\n }\n } \n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\nCopyright (c) 2012, Apps4Av Inc. (apps4av.com) \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\npackage com.ds.avare.shapes;\n\nimport java.util.LinkedList;\n\nimport com.ds.avare.place.Plan;\nimport com.ds.avare.position.Coordinate;\nimport com.ds.avare.position.Movement;\nimport com.ds.avare.position.Origin;\nimport com.ds.avare.position.Scale;\nimport com.sromku.polygon.Point;\nimport com.sromku.polygon.Polygon;\nimport com.sromku.polygon.Polygon.Builder;\n\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.Typeface;\n\n\/**\n * @author zkhan\n *\n *\/\npublic abstract class Shape {\n\n protected LinkedList mCoords;\n protected double mLonMin;\n protected double mLonMax;\n protected double mLatMin;\n protected double mLatMax;\n \n protected String mText;\n \n private Builder mPolyBuilder;\n private Polygon mPoly;\n \n \/**\n * \n *\/\n public Shape(String label) {\n mCoords = new LinkedList();\n mLonMin = 180;\n mLonMax = -180;\n mLatMin = 180;\n mLatMax = -180;\n mText = label;\n mPolyBuilder = Polygon.Builder(); \n }\n\n \/**\n * \n * @param coords\n *\/\n public void add(double lon, double lat, boolean issep) {\n \tadd(lon,lat,issep, 0);\n }\n \n public void add(double lon, double lat, boolean issep, int segment) {\n Coordinate c = new Coordinate(lon, lat);\n if(issep) {\n c.makeSeparate();\n }\n c.setSegment(segment);\n \n mCoords.add(c);\n mPolyBuilder.addVertex(new Point((float)lon, (float)lat));\n \n \/*\n * Calculate start points\n *\/\n if(lon < mLonMin) {\n mLonMin = lon;\n }\n if(lon >= mLonMax) {\n mLonMax = lon;\n }\n if(lat < mLatMin) {\n mLatMin = lat;\n }\n if(lat >= mLatMax) {\n mLatMax = lat;\n }\n }\n\n public void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack) {\n \tdrawShape(c, origin, scale,movement,paint,night, drawTrack, null);\n }\n \n \/**\n * This will draw the closed shape in canvas with given screen params\n * @param c\n * @param origin\n * @param scale\n * @param movement\n * @param paint\n *\/\n\tpublic void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack, Plan plan) {\n\n \/*\n * Do a tab on top of shape\n *\/\n \/*\n * Draw pivots at end of track\n *\/\n float width = paint.getStrokeWidth();\n int color = paint.getColor();\n \n \/\/ TrackShape type is used for a flight plan destination\n if (this instanceof TrackShape) {\n \n \/*\n * Draw background on track shapes, so draw twice\n *\/\n \tint cMax = getNumCoords();\n for(int coord = 0; coord < (cMax - 1); coord++) {\n float x1 = (float)origin.getOffsetX(mCoords.get(coord).getLongitude());\n float x2 = (float)origin.getOffsetX(mCoords.get(coord + 1).getLongitude());\n float y1 = (float)origin.getOffsetY(mCoords.get(coord).getLatitude());\n float y2 = (float)origin.getOffsetY(mCoords.get(coord + 1).getLatitude());;\n\n if(drawTrack) {\n\t paint.setStrokeWidth(width + 4);\n\t paint.setColor(night? Color.WHITE : Color.BLACK);\n\t c.drawLine(x1, y1, x2, y2, paint);\n\t paint.setStrokeWidth(width);\n\n\t if(null == plan) {\n\t \tpaint.setColor(color);\n\t } else {\n\t \tpaint.setColor(TrackShape.getLegColor(plan.findNextNotPassed(), mCoords.get(coord).getLeg()));\n\t }\n\n\t c.drawLine(x1, y1, x2, y2, paint);\n }\n\n\t\t\t\tif(mCoords.get(coord + 1).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x2, y2, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x2, y2, 8, paint);\n paint.setColor(color);\n }\n if(mCoords.get(coord).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x1, y1, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x1, y1, 8, paint);\n paint.setColor(color);\n }\n }\n } else {\n \/*\n * Draw the shape segment by segment\n *\/\n for(int coord = 0; coord < (getNumCoords() - 1); coord++) {\n float x1 = (float)origin.getOffsetX(mCoords.get(coord).getLongitude());\n float x2 = (float)origin.getOffsetX(mCoords.get(coord + 1).getLongitude());\n float y1 = (float)origin.getOffsetY(mCoords.get(coord).getLatitude());\n float y2 = (float)origin.getOffsetY(mCoords.get(coord + 1).getLatitude());;\n c.drawLine(x1, y1, x2, y2, paint);\n }\n }\n }\n \n \/**\n * \n * @return\n *\/\n public int getNumCoords() {\n return mCoords.size();\n }\n\n \/**\n * \n * @return\n *\/\n public double getLatitudeMinimum() {\n return mLatMin;\n }\n \n \/**\n * \n * @param lon\n * @param lat\n * @return\n *\/\n public String getTextIfTouched(double lon, double lat) {\n if(null == mPoly) {\n return null;\n }\n if(mPoly.contains(new Point((float)lon, (float)lat))) {\n return mText;\n }\n return null;\n }\n \n \/**\n * \n *\/\n public void makePolygon() {\n if(getNumCoords() > 2) {\n mPoly = mPolyBuilder.build();\n }\n } \n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\nCopyright (c) 2012, Apps4Av Inc. (apps4av.com) \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\npackage com.ds.avare.shapes;\n\nimport java.util.LinkedList;\n\nimport com.ds.avare.place.Plan;\nimport com.ds.avare.position.Coordinate;\nimport com.ds.avare.position.Movement;\nimport com.ds.avare.position.Origin;\nimport com.ds.avare.position.Scale;\nimport com.sromku.polygon.Point;\nimport com.sromku.polygon.Polygon;\nimport com.sromku.polygon.Polygon.Builder;\n\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.Typeface;\n\n\/**\n * @author zkhan\n *\n *\/\npublic abstract class Shape {\n\n protected LinkedList mCoords;\n protected double mLonMin;\n protected double mLonMax;\n protected double mLatMin;\n protected double mLatMax;\n \n protected String mText;\n \n private Builder mPolyBuilder;\n private Polygon mPoly;\n \n \/**\n * \n *\/\n public Shape(String label) {\n mCoords = new LinkedList();\n mLonMin = 180;\n mLonMax = -180;\n mLatMin = 180;\n mLatMax = -180;\n mText = label;\n mPolyBuilder = Polygon.Builder(); \n }\n\n \/**\n * \n * @param coords\n *\/\n public void add(double lon, double lat, boolean issep) {\n \tadd(lon,lat,issep, 0);\n }\n \n public void add(double lon, double lat, boolean issep, int segment) {\n Coordinate c = new Coordinate(lon, lat);\n if(issep) {\n c.makeSeparate();\n }\n c.setSegment(segment);\n \n mCoords.add(c);\n mPolyBuilder.addVertex(new Point((float)lon, (float)lat));\n \n \/*\n * Calculate start points\n *\/\n if(lon < mLonMin) {\n mLonMin = lon;\n }\n if(lon >= mLonMax) {\n mLonMax = lon;\n }\n if(lat < mLatMin) {\n mLatMin = lat;\n }\n if(lat >= mLatMax) {\n mLatMax = lat;\n }\n }\n\n public void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack) {\n \tdrawShape(c, origin, scale,movement,paint,night, drawTrack, null);\n }\n \n \/**\n * This will draw the closed shape in canvas with given screen params\n * @param c\n * @param origin\n * @param scale\n * @param movement\n * @param paint\n *\/\n\tpublic void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack, Plan plan) {\n\n \/*\n * Do a tab on top of shape\n *\/\n \/*\n * Draw pivots at end of track\n *\/\n float width = paint.getStrokeWidth();\n int color = paint.getColor();\n \n \/\/ TrackShape type is used for a flight plan destination\n if (this instanceof TrackShape) {\n \n \/*\n * Draw background on track shapes, so draw twice\n *\/\n \tint cMax = getNumCoords();\n for(int coord = 0; coord < (cMax - 1); coord++) {\n float x1 = (float)origin.getOffsetX(mCoords.get(coord).getLongitude());\n float x2 = (float)origin.getOffsetX(mCoords.get(coord + 1).getLongitude());\n float y1 = (float)origin.getOffsetY(mCoords.get(coord).getLatitude());\n float y2 = (float)origin.getOffsetY(mCoords.get(coord + 1).getLatitude());;\n\n if(drawTrack) {\n\t paint.setStrokeWidth(width + 4);\n\t paint.setColor(night? Color.WHITE : Color.BLACK);\n\t c.drawLine(x1, y1, x2, y2, paint);\n\t paint.setStrokeWidth(width);\n\n\t if(null == plan) {\n\t \tpaint.setColor(color);\n\t } else {\n\t \tpaint.setColor(TrackShape.getLegColor(plan.findNextNotPassed(), mCoords.get(coord).getLeg()));\n\t }\n\n\t c.drawLine(x1, y1, x2, y2, paint);\n }\n\n\t\t\t\tif(mCoords.get(coord + 1).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x2, y2, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x2, y2, 8, paint);\n paint.setColor(color);\n }\n if(mCoords.get(coord).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x1, y1, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x1, y1, 8, paint);\n paint.setColor(color);\n }\n }\n } else {\n \/*\n * Draw the shape segment by segment\n *\/\n for(int coord = 0; coord < (getNumCoords() - 1); coord++) {\n float x1 = (float)origin.getOffsetX(mCoords.get(coord).getLongitude());\n float x2 = (float)origin.getOffsetX(mCoords.get(coord + 1).getLongitude());\n float y1 = (float)origin.getOffsetY(mCoords.get(coord).getLatitude());\n float y2 = (float)origin.getOffsetY(mCoords.get(coord + 1).getLatitude());;\n c.drawLine(x1, y1, x2, y2, paint);\n }\n }\n }\n \n \/**\n * \n * @return\n *\/\n public int getNumCoords() {\n return mCoords.size();\n }\n\n \/**\n * \n * @return\n *\/\n public double getLatitudeMinimum() {\n return mLatMin;\n }\n \n \/**\n * \n * @param lon\n * @param lat\n * @return\n *\/\n public String getTextIfTouched(double lon, double lat) {\n if(null == mPoly) {\n return null;\n }\n if(mPoly.contains(new Point((float)lon, (float)lat))) {\n return mText;\n }\n return null;\n }\n \n \/**\n * \n *\/\n public void makePolygon() {\n if(getNumCoords() > 2) {\n mPoly = mPolyBuilder.build();\n }\n } \n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\nCopyright (c) 2012, Apps4Av Inc. (apps4av.com) \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\npackage com.ds.avare.shapes;\n\nimport java.util.LinkedList;\n\nimport com.ds.avare.place.Plan;\nimport com.ds.avare.position.Coordinate;\nimport com.ds.avare.position.Movement;\nimport com.ds.avare.position.Origin;\nimport com.ds.avare.position.Scale;\nimport com.sromku.polygon.Point;\nimport com.sromku.polygon.Polygon;\nimport com.sromku.polygon.Polygon.Builder;\n\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.Typeface;\n\n\/**\n * @author zkhan\n *\n *\/\npublic abstract class Shape {\n\n protected LinkedList mCoords;\n protected double mLonMin;\n protected double mLonMax;\n protected double mLatMin;\n protected double mLatMax;\n \n protected String mText;\n \n private Builder mPolyBuilder;\n private Polygon mPoly;\n \n \/**\n * \n *\/\n public Shape(String label) {\n mCoords = new LinkedList();\n mLonMin = 180;\n mLonMax = -180;\n mLatMin = 180;\n mLatMax = -180;\n mText = label;\n mPolyBuilder = Polygon.Builder(); \n }\n\n \/**\n * \n * @param coords\n *\/\n public void add(double lon, double lat, boolean issep) {\n \tadd(lon,lat,issep, 0);\n }\n \n public void add(double lon, double lat, boolean issep, int segment) {\n Coordinate c = new Coordinate(lon, lat);\n if(issep) {\n c.makeSeparate();\n }\n c.setSegment(segment);\n \n mCoords.add(c);\n mPolyBuilder.addVertex(new Point((float)lon, (float)lat));\n \n \/*\n * Calculate start points\n *\/\n if(lon < mLonMin) {\n mLonMin = lon;\n }\n if(lon >= mLonMax) {\n mLonMax = lon;\n }\n if(lat < mLatMin) {\n mLatMin = lat;\n }\n if(lat >= mLatMax) {\n mLatMax = lat;\n }\n }\n\n public void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack) {\n \tdrawShape(c, origin, scale,movement,paint,night, drawTrack, null);\n }\n \n \/**\n * This will draw the closed shape in canvas with given screen params\n * @param c\n * @param origin\n * @param scale\n * @param movement\n * @param paint\n *\/\n\tpublic void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack, Plan plan) {\n\n \/*\n * Do a tab on top of shape\n *\/\n \/*\n * Draw pivots at end of track\n *\/\n float width = paint.getStrokeWidth();\n int color = paint.getColor();\n \n \/\/ TrackShape type is used for a flight plan destination\n if (this instanceof TrackShape) {\n \n \/*\n * Draw background on track shapes, so draw twice\n *\/\n \tint cMax = getNumCoords();\n for(int coord = 0; coord < (cMax - 1); coord++) {\n float x1 = (float)origin.getOffsetX(mCoords.get(coord).getLongitude());\n float x2 = (float)origin.getOffsetX(mCoords.get(coord + 1).getLongitude());\n float y1 = (float)origin.getOffsetY(mCoords.get(coord).getLatitude());\n float y2 = (float)origin.getOffsetY(mCoords.get(coord + 1).getLatitude());;\n\n if(drawTrack) {\n\t paint.setStrokeWidth(width + 4);\n\t paint.setColor(night? Color.WHITE : Color.BLACK);\n\t c.drawLine(x1, y1, x2, y2, paint);\n\t paint.setStrokeWidth(width);\n\n\t if(null == plan) {\n\t \tpaint.setColor(color);\n\t } else {\n\t \tpaint.setColor(TrackShape.getLegColor(plan.findNextNotPassed(), mCoords.get(coord).getLeg()));\n\t }\n\n\t c.drawLine(x1, y1, x2, y2, paint);\n }\n\n\t\t\t\tif(mCoords.get(coord + 1).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x2, y2, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x2, y2, 8, paint);\n paint.setColor(color);\n }\n if(mCoords.get(coord).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x1, y1, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x1, y1, 8, paint);\n paint.setColor(color);\n }\n }\n } else {\n \/*\n * Draw the shape segment by segment\n *\/\n for(int coord = 0; coord < (getNumCoords() - 1); coord++) {\n float x1 = (float)origin.getOffsetX(mCoords.get(coord).getLongitude());\n float x2 = (float)origin.getOffsetX(mCoords.get(coord + 1).getLongitude());\n float y1 = (float)origin.getOffsetY(mCoords.get(coord).getLatitude());\n float y2 = (float)origin.getOffsetY(mCoords.get(coord + 1).getLatitude());;\n c.drawLine(x1, y1, x2, y2, paint);\n }\n }\n }\n \n \/**\n * \n * @return\n *\/\n public int getNumCoords() {\n return mCoords.size();\n }\n\n \/**\n * \n * @return\n *\/\n public double getLatitudeMinimum() {\n return mLatMin;\n }\n \n \/**\n * \n * @param lon\n * @param lat\n * @return\n *\/\n public String getTextIfTouched(double lon, double lat) {\n if(null == mPoly) {\n return null;\n }\n if(mPoly.contains(new Point((float)lon, (float)lat))) {\n return mText;\n }\n return null;\n }\n \n \/**\n * \n *\/\n public void makePolygon() {\n if(getNumCoords() > 2) {\n mPoly = mPolyBuilder.build();\n }\n } \n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the code to optimize draw shape for execution time. Write the entire code and no other text in the response.\n\n### Concepts:\n[in] drawShape function\n[hint] draw all the lines at the same time\nreuse offsetX and offsetY values.\n\n### Given program:\n```java\n\/*\nCopyright (c) 2012, Apps4Av Inc. (apps4av.com) \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\npackage com.ds.avare.shapes;\n\nimport java.util.LinkedList;\n\nimport com.ds.avare.place.Plan;\nimport com.ds.avare.position.Coordinate;\nimport com.ds.avare.position.Movement;\nimport com.ds.avare.position.Origin;\nimport com.ds.avare.position.Scale;\nimport com.sromku.polygon.Point;\nimport com.sromku.polygon.Polygon;\nimport com.sromku.polygon.Polygon.Builder;\n\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.Typeface;\n\n\/**\n * @author zkhan\n *\n *\/\npublic abstract class Shape {\n\n protected LinkedList mCoords;\n protected double mLonMin;\n protected double mLonMax;\n protected double mLatMin;\n protected double mLatMax;\n \n protected String mText;\n \n private Builder mPolyBuilder;\n private Polygon mPoly;\n \n \/**\n * \n *\/\n public Shape(String label) {\n mCoords = new LinkedList();\n mLonMin = 180;\n mLonMax = -180;\n mLatMin = 180;\n mLatMax = -180;\n mText = label;\n mPolyBuilder = Polygon.Builder(); \n }\n\n \/**\n * \n * @param coords\n *\/\n public void add(double lon, double lat, boolean issep) {\n \tadd(lon,lat,issep, 0);\n }\n \n public void add(double lon, double lat, boolean issep, int segment) {\n Coordinate c = new Coordinate(lon, lat);\n if(issep) {\n c.makeSeparate();\n }\n c.setSegment(segment);\n \n mCoords.add(c);\n mPolyBuilder.addVertex(new Point((float)lon, (float)lat));\n \n \/*\n * Calculate start points\n *\/\n if(lon < mLonMin) {\n mLonMin = lon;\n }\n if(lon >= mLonMax) {\n mLonMax = lon;\n }\n if(lat < mLatMin) {\n mLatMin = lat;\n }\n if(lat >= mLatMax) {\n mLatMax = lat;\n }\n }\n\n public void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack) {\n \tdrawShape(c, origin, scale,movement,paint,night, drawTrack, null);\n }\n \n \/**\n * This will draw the closed shape in canvas with given screen params\n * @param c\n * @param origin\n * @param scale\n * @param movement\n * @param paint\n *\/\n\tpublic void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack, Plan plan) {\n\n \/*\n * Do a tab on top of shape\n *\/\n \/*\n * Draw pivots at end of track\n *\/\n float width = paint.getStrokeWidth();\n int color = paint.getColor();\n \n \/\/ TrackShape type is used for a flight plan destination\n if (this instanceof TrackShape) {\n \n \/*\n * Draw background on track shapes, so draw twice\n *\/\n \tint cMax = getNumCoords();\n for(int coord = 0; coord < (cMax - 1); coord++) {\n float x1 = (float)origin.getOffsetX(mCoords.get(coord).getLongitude());\n float x2 = (float)origin.getOffsetX(mCoords.get(coord + 1).getLongitude());\n float y1 = (float)origin.getOffsetY(mCoords.get(coord).getLatitude());\n float y2 = (float)origin.getOffsetY(mCoords.get(coord + 1).getLatitude());;\n\n if(drawTrack) {\n\t paint.setStrokeWidth(width + 4);\n\t paint.setColor(night? Color.WHITE : Color.BLACK);\n\t c.drawLine(x1, y1, x2, y2, paint);\n\t paint.setStrokeWidth(width);\n\n\t if(null == plan) {\n\t \tpaint.setColor(color);\n\t } else {\n\t \tpaint.setColor(TrackShape.getLegColor(plan.findNextNotPassed(), mCoords.get(coord).getLeg()));\n\t }\n\n\t c.drawLine(x1, y1, x2, y2, paint);\n }\n\n\t\t\t\tif(mCoords.get(coord + 1).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x2, y2, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x2, y2, 8, paint);\n paint.setColor(color);\n }\n if(mCoords.get(coord).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x1, y1, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x1, y1, 8, paint);\n paint.setColor(color);\n }\n }\n } else {\n \/*\n * Draw the shape segment by segment\n *\/\n for(int coord = 0; coord < (getNumCoords() - 1); coord++) {\n float x1 = (float)origin.getOffsetX(mCoords.get(coord).getLongitude());\n float x2 = (float)origin.getOffsetX(mCoords.get(coord + 1).getLongitude());\n float y1 = (float)origin.getOffsetY(mCoords.get(coord).getLatitude());\n float y2 = (float)origin.getOffsetY(mCoords.get(coord + 1).getLatitude());;\n c.drawLine(x1, y1, x2, y2, paint);\n }\n }\n }\n \n \/**\n * \n * @return\n *\/\n public int getNumCoords() {\n return mCoords.size();\n }\n\n \/**\n * \n * @return\n *\/\n public double getLatitudeMinimum() {\n return mLatMin;\n }\n \n \/**\n * \n * @param lon\n * @param lat\n * @return\n *\/\n public String getTextIfTouched(double lon, double lat) {\n if(null == mPoly) {\n return null;\n }\n if(mPoly.contains(new Point((float)lon, (float)lat))) {\n return mText;\n }\n return null;\n }\n \n \/**\n * \n *\/\n public void makePolygon() {\n if(getNumCoords() > 2) {\n mPoly = mPolyBuilder.build();\n }\n } \n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage us.shandian.giga.ui.web;\n\nimport android.app.AlertDialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.ContextThemeWrapper;\nimport android.view.KeyEvent;\nimport android.view.LayoutInflater;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.view.inputmethod.InputMethodManager;\nimport android.webkit.DownloadListener;\nimport android.webkit.JavascriptInterface;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.EditText;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\n\nimport android.support.v7.app.ActionBar;\n\nimport java.util.ArrayList;\nimport java.util.regex.Pattern;\nimport java.util.regex.Matcher;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.ui.common.ToolbarActivity;\nimport us.shandian.giga.ui.main.MainActivity;\nimport us.shandian.giga.util.Utility;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class BrowserActivity extends ToolbarActivity\n{\n\tprivate WebView mWeb;\n\tprivate ProgressBar mProgress;\n\tprivate EditText mUrl;\n\tprivate InputMethodManager mInput;\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\t\n\t\tmInput = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);\n\t\t\n\t\t\/\/ Toolbar\n\t\tgetSupportActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowHomeEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\n\t\t\/\/ Custom view\n\t\tif (Build.VERSION.SDK_INT < 21) {\n\t\t\tContextThemeWrapper wrap = new ContextThemeWrapper(this, R.style.Theme_AppCompat);\n\t\t\tLayoutInflater inflater = (LayoutInflater) wrap.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n\t\t\tView custom = inflater.inflate(R.layout.browser_url, null);\n\t\t\tgetSupportActionBar().setCustomView(custom);\n\t\t} else {\n\t\t\tgetSupportActionBar().setCustomView(R.layout.browser_url);\n\t\t}\n\t\t\n\t\t\/\/ Initialize WebView\n\t\tmProgress = Utility.findViewById(this, R.id.progress);\n\t\tmUrl = Utility.findViewById(getSupportActionBar().getCustomView(), R.id.browser_url);\n\t\tmWeb = Utility.findViewById(this, R.id.web);\n\t\tmWeb.setWebViewClient(new WebViewClient() {\n\t\t\t@Override\n\t\t\tpublic boolean shouldOverrideUrlLoading(WebView view, String url) {\n\t\t\t\tview.loadUrl(url);\n\t\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t\t\tmInput.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onPageFinished(WebView view, String url) {\n\t\t\t\tmProgress.setProgress(0);\n\t\t\t}\n\t\t});\n\t\tmWeb.setWebChromeClient(new WebChromeClient() {\n\t\t\t@Override\n\t\t\tpublic void onProgressChanged(WebView v, int progress) {\n\t\t\t\tmProgress.setProgress(progress);\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onReceivedTitle(WebView v, String title) {\n\t\t\t\tgetSupportActionBar().setTitle(title);\n\t\t\t}\n\t\t});\n\t\tmWeb.getSettings().setJavaScriptEnabled(true);\n\t\tmWeb.setDownloadListener(new DownloadListener() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {\n\t\t\t\t\t\/\/ Start MainActivity for downloading\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(url), mimeType);\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t\n\t\t});\n\t\tmUrl.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n\t\t\t@Override\n\t\t\tpublic boolean onEditorAction(TextView v, int actionId, KeyEvent ev) {\n\t\t\t\t\tif (actionId == EditorInfo.IME_ACTION_GO) {\n\t\t\t\t\t\tString url = mUrl.getText().toString();\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!url.startsWith(\"http\")) {\n\t\t\t\t\t\t\turl = \"http:\/\/\" + url;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tmWeb.loadUrl(url);\n\t\t\t\t\t\tswitchCustom();\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t});\n\t\tmWeb.addJavascriptInterface(new MyJavascriptInterface(), \"HTMLOUT\");\n\t\t\n\t\tmWeb.loadUrl(\"about:blank\");\n\t\t\n\t\tswitchCustom();\n\t\t\n\t\tmToolbar.setOnClickListener(new View.OnClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tswitchCustom();\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tprotected int getLayoutResource() {\n\t\treturn R.layout.browser;\n\t}\n\n\t@Override\n\tpublic boolean onCreateOptionsMenu(Menu menu) {\n\t\tgetMenuInflater().inflate(R.menu.browser, menu);\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tswitch (item.getItemId()) {\n\t\t\tcase android.R.id.home:\n\t\t\t\tfinish();\n\t\t\t\treturn true;\n\t\t\tcase R.id.detector:\n\t\t\t\tmWeb.loadUrl(\"javascript:window.HTMLOUT.processHTML(''+document.getElementsByTagName('html')[0].innerHTML+'<\/head>');\");\n\t\t\t\treturn true;\n\t\t\tdefault:\n\t\t\t\treturn super.onOptionsItemSelected(item);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onBackPressed() {\n\t\tif (mWeb.canGoBack()) {\n\t\t\tmWeb.goBack();\n\t\t} else {\n\t\t\tfinish();\n\t\t}\n\t}\n\t\n\tprivate void switchCustom() {\n\t\tint opt = getSupportActionBar().getDisplayOptions();\n\t\t\n\t\tif ((opt & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t\tmInput.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);\n\t\t} else {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(true);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\tmInput.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);\n\t\t\tmUrl.requestFocus();\n\t\t\tmUrl.setText(mWeb.getUrl());\n\t\t\tmUrl.setSelection(0, mUrl.getText().length());\n\t\t}\n\t}\n\t\n\tprivate void showVideoChoices(final String[] vids) {\n\t\tnew AlertDialog.Builder(this)\n\t\t\t.setItems(vids, new DialogInterface.OnClickListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(vids[id]), \"application\/octet-stream\");\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t})\n\t\t\t.show();\n\t}\n\t\n\tclass MyJavascriptInterface {\n\t\tprivate static final String TAG = MyJavascriptInterface.class.getSimpleName();\n\t\t\n\t\tprivate static final String PATTERN = \"[http|https]+[:\/\/]+[0-9A-Za-z:\/[-]_#[?][=][.][&]]*\";\n\t\tprivate static final String[] VIDEO_SUFFIXES = new String[]{\n\t\t\t\".mp4\",\n\t\t\t\".flv\",\n\t\t\t\".rm\",\n\t\t\t\".rmvb\",\n\t\t\t\".wmv\",\n\t\t\t\".avi\",\n\t\t\t\".mkv\",\n\t\t\t\".webm\"\n\t\t};\n\t\t\n\t\t@JavascriptInterface\n\t\tpublic void processHTML(String html) {\n\t\t\tPattern pattern = Pattern.compile(PATTERN);\n\t\t\tMatcher matcher = pattern.matcher(html);\n\t\t\t\n\t\t\tArrayList vid = new ArrayList();\n\t\t\t\n\t\t\twhile (matcher.find()) {\n\t\t\t\tString url = matcher.group();\n\t\t\t\t\n\t\t\t\tboolean isVid = false;\n\t\t\t\t\n\t\t\t\tfor (String suffix : VIDEO_SUFFIXES) {\n\t\t\t\t\tif (url.contains(suffix)) {\n\t\t\t\t\t\tisVid = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (isVid) {\n\t\t\t\t\t\n\t\t\t\t\tvid.add(url);\n\t\t\t\t\t\n\t\t\t\t\tif (DEBUG) {\n\t\t\t\t\t\tLog.d(TAG, \"found url:\" + url);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (vid.size() == 0) return;\n\t\t\t\n\t\t\tString[] arr = new String[vid.size()];\n\t\t\tshowVideoChoices(vid.toArray(arr));\n\t\t}\n\t}\n}\n\n\nCode-B:\npackage us.shandian.giga.ui.web;\n\nimport android.app.AlertDialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.ContextThemeWrapper;\nimport android.view.KeyEvent;\nimport android.view.LayoutInflater;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.webkit.DownloadListener;\nimport android.webkit.JavascriptInterface;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.EditText;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\n\nimport android.support.v7.app.ActionBar;\n\nimport java.util.ArrayList;\nimport java.util.regex.Pattern;\nimport java.util.regex.Matcher;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.ui.common.ToolbarActivity;\nimport us.shandian.giga.ui.main.MainActivity;\nimport us.shandian.giga.util.Utility;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class BrowserActivity extends ToolbarActivity\n{\n\tprivate WebView mWeb;\n\tprivate ProgressBar mProgress;\n\tprivate EditText mUrl;\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\t\n\t\t\/\/ Toolbar\n\t\tgetSupportActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowHomeEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\n\t\t\/\/ Custom view\n\t\tif (Build.VERSION.SDK_INT < 21) {\n\t\t\tContextThemeWrapper wrap = new ContextThemeWrapper(this, R.style.Theme_AppCompat);\n\t\t\tLayoutInflater inflater = (LayoutInflater) wrap.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n\t\t\tView custom = inflater.inflate(R.layout.browser_url, null);\n\t\t\tgetSupportActionBar().setCustomView(custom);\n\t\t} else {\n\t\t\tgetSupportActionBar().setCustomView(R.layout.browser_url);\n\t\t}\n\t\t\n\t\t\/\/ Initialize WebView\n\t\tmProgress = Utility.findViewById(this, R.id.progress);\n\t\tmUrl = Utility.findViewById(getSupportActionBar().getCustomView(), R.id.browser_url);\n\t\tmWeb = Utility.findViewById(this, R.id.web);\n\t\tmWeb.setWebViewClient(new WebViewClient() {\n\t\t\t@Override\n\t\t\tpublic boolean shouldOverrideUrlLoading(WebView view, String url) {\n\t\t\t\tview.loadUrl(url);\n\t\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onPageFinished(WebView view, String url) {\n\t\t\t\tmProgress.setProgress(0);\n\t\t\t}\n\t\t});\n\t\tmWeb.setWebChromeClient(new WebChromeClient() {\n\t\t\t@Override\n\t\t\tpublic void onProgressChanged(WebView v, int progress) {\n\t\t\t\tmProgress.setProgress(progress);\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onReceivedTitle(WebView v, String title) {\n\t\t\t\tgetSupportActionBar().setTitle(title);\n\t\t\t}\n\t\t});\n\t\tmWeb.getSettings().setJavaScriptEnabled(true);\n\t\tmWeb.setDownloadListener(new DownloadListener() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {\n\t\t\t\t\t\/\/ Start MainActivity for downloading\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(url), mimeType);\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t\n\t\t});\n\t\tmUrl.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n\t\t\t@Override\n\t\t\tpublic boolean onEditorAction(TextView v, int actionId, KeyEvent ev) {\n\t\t\t\t\tif (actionId == EditorInfo.IME_ACTION_GO) {\n\t\t\t\t\t\tString url = mUrl.getText().toString();\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!url.startsWith(\"http\")) {\n\t\t\t\t\t\t\turl = \"http:\/\/\" + url;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tmWeb.loadUrl(url);\n\t\t\t\t\t\tswitchCustom();\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t});\n\t\tmWeb.addJavascriptInterface(new MyJavascriptInterface(), \"HTMLOUT\");\n\t\t\n\t\tmWeb.loadUrl(\"about:blank\");\n\t\t\n\t\tswitchCustom();\n\t\t\n\t\tmToolbar.setOnClickListener(new View.OnClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tswitchCustom();\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tprotected int getLayoutResource() {\n\t\treturn R.layout.browser;\n\t}\n\n\t@Override\n\tpublic boolean onCreateOptionsMenu(Menu menu) {\n\t\tgetMenuInflater().inflate(R.menu.browser, menu);\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tswitch (item.getItemId()) {\n\t\t\tcase android.R.id.home:\n\t\t\t\tfinish();\n\t\t\t\treturn true;\n\t\t\tcase R.id.detector:\n\t\t\t\tmWeb.loadUrl(\"javascript:window.HTMLOUT.processHTML(''+document.getElementsByTagName('html')[0].innerHTML+'<\/head>');\");\n\t\t\t\treturn true;\n\t\t\tdefault:\n\t\t\t\treturn super.onOptionsItemSelected(item);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onBackPressed() {\n\t\tif (mWeb.canGoBack()) {\n\t\t\tmWeb.goBack();\n\t\t} else {\n\t\t\tfinish();\n\t\t}\n\t}\n\t\n\tprivate void switchCustom() {\n\t\tint opt = getSupportActionBar().getDisplayOptions();\n\t\t\n\t\tif ((opt & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t} else {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(true);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\tmUrl.setText(mWeb.getUrl());\n\t\t\tmUrl.setSelection(0, mUrl.getText().length());\n\t\t}\n\t}\n\t\n\tprivate void showVideoChoices(final String[] vids) {\n\t\tnew AlertDialog.Builder(this)\n\t\t\t.setItems(vids, new DialogInterface.OnClickListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(vids[id]), \"application\/octet-stream\");\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t})\n\t\t\t.show();\n\t}\n\t\n\tclass MyJavascriptInterface {\n\t\tprivate static final String TAG = MyJavascriptInterface.class.getSimpleName();\n\t\t\n\t\tprivate static final String PATTERN = \"[http|https]+[:\/\/]+[0-9A-Za-z:\/[-]_#[?][=][.][&]]*\";\n\t\tprivate static final String[] VIDEO_SUFFIXES = new String[]{\n\t\t\t\".mp4\",\n\t\t\t\".flv\",\n\t\t\t\".rm\",\n\t\t\t\".rmvb\",\n\t\t\t\".wmv\",\n\t\t\t\".avi\",\n\t\t\t\".mkv\",\n\t\t\t\".webm\"\n\t\t};\n\t\t\n\t\t@JavascriptInterface\n\t\tpublic void processHTML(String html) {\n\t\t\tPattern pattern = Pattern.compile(PATTERN);\n\t\t\tMatcher matcher = pattern.matcher(html);\n\t\t\t\n\t\t\tArrayList vid = new ArrayList();\n\t\t\t\n\t\t\twhile (matcher.find()) {\n\t\t\t\tString url = matcher.group();\n\t\t\t\t\n\t\t\t\tboolean isVid = false;\n\t\t\t\t\n\t\t\t\tfor (String suffix : VIDEO_SUFFIXES) {\n\t\t\t\t\tif (url.contains(suffix)) {\n\t\t\t\t\t\tisVid = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (isVid) {\n\t\t\t\t\t\n\t\t\t\t\tvid.add(url);\n\t\t\t\t\t\n\t\t\t\t\tif (DEBUG) {\n\t\t\t\t\t\tLog.d(TAG, \"found url:\" + url);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (vid.size() == 0) return;\n\t\t\t\n\t\t\tString[] arr = new String[vid.size()];\n\t\t\tshowVideoChoices(vid.toArray(arr));\n\t\t}\n\t}\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage us.shandian.giga.ui.web;\n\nimport android.app.AlertDialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.ContextThemeWrapper;\nimport android.view.KeyEvent;\nimport android.view.LayoutInflater;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.webkit.DownloadListener;\nimport android.webkit.JavascriptInterface;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.EditText;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\n\nimport android.support.v7.app.ActionBar;\n\nimport java.util.ArrayList;\nimport java.util.regex.Pattern;\nimport java.util.regex.Matcher;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.ui.common.ToolbarActivity;\nimport us.shandian.giga.ui.main.MainActivity;\nimport us.shandian.giga.util.Utility;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class BrowserActivity extends ToolbarActivity\n{\n\tprivate WebView mWeb;\n\tprivate ProgressBar mProgress;\n\tprivate EditText mUrl;\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\t\n\t\t\/\/ Toolbar\n\t\tgetSupportActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowHomeEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\n\t\t\/\/ Custom view\n\t\tif (Build.VERSION.SDK_INT < 21) {\n\t\t\tContextThemeWrapper wrap = new ContextThemeWrapper(this, R.style.Theme_AppCompat);\n\t\t\tLayoutInflater inflater = (LayoutInflater) wrap.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n\t\t\tView custom = inflater.inflate(R.layout.browser_url, null);\n\t\t\tgetSupportActionBar().setCustomView(custom);\n\t\t} else {\n\t\t\tgetSupportActionBar().setCustomView(R.layout.browser_url);\n\t\t}\n\t\t\n\t\t\/\/ Initialize WebView\n\t\tmProgress = Utility.findViewById(this, R.id.progress);\n\t\tmUrl = Utility.findViewById(getSupportActionBar().getCustomView(), R.id.browser_url);\n\t\tmWeb = Utility.findViewById(this, R.id.web);\n\t\tmWeb.setWebViewClient(new WebViewClient() {\n\t\t\t@Override\n\t\t\tpublic boolean shouldOverrideUrlLoading(WebView view, String url) {\n\t\t\t\tview.loadUrl(url);\n\t\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onPageFinished(WebView view, String url) {\n\t\t\t\tmProgress.setProgress(0);\n\t\t\t}\n\t\t});\n\t\tmWeb.setWebChromeClient(new WebChromeClient() {\n\t\t\t@Override\n\t\t\tpublic void onProgressChanged(WebView v, int progress) {\n\t\t\t\tmProgress.setProgress(progress);\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onReceivedTitle(WebView v, String title) {\n\t\t\t\tgetSupportActionBar().setTitle(title);\n\t\t\t}\n\t\t});\n\t\tmWeb.getSettings().setJavaScriptEnabled(true);\n\t\tmWeb.setDownloadListener(new DownloadListener() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {\n\t\t\t\t\t\/\/ Start MainActivity for downloading\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(url), mimeType);\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t\n\t\t});\n\t\tmUrl.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n\t\t\t@Override\n\t\t\tpublic boolean onEditorAction(TextView v, int actionId, KeyEvent ev) {\n\t\t\t\t\tif (actionId == EditorInfo.IME_ACTION_GO) {\n\t\t\t\t\t\tString url = mUrl.getText().toString();\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!url.startsWith(\"http\")) {\n\t\t\t\t\t\t\turl = \"http:\/\/\" + url;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tmWeb.loadUrl(url);\n\t\t\t\t\t\tswitchCustom();\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t});\n\t\tmWeb.addJavascriptInterface(new MyJavascriptInterface(), \"HTMLOUT\");\n\t\t\n\t\tmWeb.loadUrl(\"about:blank\");\n\t\t\n\t\tswitchCustom();\n\t\t\n\t\tmToolbar.setOnClickListener(new View.OnClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tswitchCustom();\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tprotected int getLayoutResource() {\n\t\treturn R.layout.browser;\n\t}\n\n\t@Override\n\tpublic boolean onCreateOptionsMenu(Menu menu) {\n\t\tgetMenuInflater().inflate(R.menu.browser, menu);\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tswitch (item.getItemId()) {\n\t\t\tcase android.R.id.home:\n\t\t\t\tfinish();\n\t\t\t\treturn true;\n\t\t\tcase R.id.detector:\n\t\t\t\tmWeb.loadUrl(\"javascript:window.HTMLOUT.processHTML(''+document.getElementsByTagName('html')[0].innerHTML+'<\/head>');\");\n\t\t\t\treturn true;\n\t\t\tdefault:\n\t\t\t\treturn super.onOptionsItemSelected(item);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onBackPressed() {\n\t\tif (mWeb.canGoBack()) {\n\t\t\tmWeb.goBack();\n\t\t} else {\n\t\t\tfinish();\n\t\t}\n\t}\n\t\n\tprivate void switchCustom() {\n\t\tint opt = getSupportActionBar().getDisplayOptions();\n\t\t\n\t\tif ((opt & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t} else {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(true);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\tmUrl.setText(mWeb.getUrl());\n\t\t\tmUrl.setSelection(0, mUrl.getText().length());\n\t\t}\n\t}\n\t\n\tprivate void showVideoChoices(final String[] vids) {\n\t\tnew AlertDialog.Builder(this)\n\t\t\t.setItems(vids, new DialogInterface.OnClickListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(vids[id]), \"application\/octet-stream\");\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t})\n\t\t\t.show();\n\t}\n\t\n\tclass MyJavascriptInterface {\n\t\tprivate static final String TAG = MyJavascriptInterface.class.getSimpleName();\n\t\t\n\t\tprivate static final String PATTERN = \"[http|https]+[:\/\/]+[0-9A-Za-z:\/[-]_#[?][=][.][&]]*\";\n\t\tprivate static final String[] VIDEO_SUFFIXES = new String[]{\n\t\t\t\".mp4\",\n\t\t\t\".flv\",\n\t\t\t\".rm\",\n\t\t\t\".rmvb\",\n\t\t\t\".wmv\",\n\t\t\t\".avi\",\n\t\t\t\".mkv\",\n\t\t\t\".webm\"\n\t\t};\n\t\t\n\t\t@JavascriptInterface\n\t\tpublic void processHTML(String html) {\n\t\t\tPattern pattern = Pattern.compile(PATTERN);\n\t\t\tMatcher matcher = pattern.matcher(html);\n\t\t\t\n\t\t\tArrayList vid = new ArrayList();\n\t\t\t\n\t\t\twhile (matcher.find()) {\n\t\t\t\tString url = matcher.group();\n\t\t\t\t\n\t\t\t\tboolean isVid = false;\n\t\t\t\t\n\t\t\t\tfor (String suffix : VIDEO_SUFFIXES) {\n\t\t\t\t\tif (url.contains(suffix)) {\n\t\t\t\t\t\tisVid = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (isVid) {\n\t\t\t\t\t\n\t\t\t\t\tvid.add(url);\n\t\t\t\t\t\n\t\t\t\t\tif (DEBUG) {\n\t\t\t\t\t\tLog.d(TAG, \"found url:\" + url);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (vid.size() == 0) return;\n\t\t\t\n\t\t\tString[] arr = new String[vid.size()];\n\t\t\tshowVideoChoices(vid.toArray(arr));\n\t\t}\n\t}\n}\n\n\nCode-B:\npackage us.shandian.giga.ui.web;\n\nimport android.app.AlertDialog;\nimport android.content.Context;\nimport android.content.DialogInterface;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.ContextThemeWrapper;\nimport android.view.KeyEvent;\nimport android.view.LayoutInflater;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.view.inputmethod.InputMethodManager;\nimport android.webkit.DownloadListener;\nimport android.webkit.JavascriptInterface;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebView;\nimport android.webkit.WebViewClient;\nimport android.widget.EditText;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\n\nimport android.support.v7.app.ActionBar;\n\nimport java.util.ArrayList;\nimport java.util.regex.Pattern;\nimport java.util.regex.Matcher;\n\nimport us.shandian.giga.R;\nimport us.shandian.giga.ui.common.ToolbarActivity;\nimport us.shandian.giga.ui.main.MainActivity;\nimport us.shandian.giga.util.Utility;\nimport static us.shandian.giga.BuildConfig.DEBUG;\n\npublic class BrowserActivity extends ToolbarActivity\n{\n\tprivate WebView mWeb;\n\tprivate ProgressBar mProgress;\n\tprivate EditText mUrl;\n\tprivate InputMethodManager mInput;\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\t\n\t\tmInput = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);\n\t\t\n\t\t\/\/ Toolbar\n\t\tgetSupportActionBar().setDisplayHomeAsUpEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowHomeEnabled(true);\n\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\n\t\t\/\/ Custom view\n\t\tif (Build.VERSION.SDK_INT < 21) {\n\t\t\tContextThemeWrapper wrap = new ContextThemeWrapper(this, R.style.Theme_AppCompat);\n\t\t\tLayoutInflater inflater = (LayoutInflater) wrap.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n\t\t\tView custom = inflater.inflate(R.layout.browser_url, null);\n\t\t\tgetSupportActionBar().setCustomView(custom);\n\t\t} else {\n\t\t\tgetSupportActionBar().setCustomView(R.layout.browser_url);\n\t\t}\n\t\t\n\t\t\/\/ Initialize WebView\n\t\tmProgress = Utility.findViewById(this, R.id.progress);\n\t\tmUrl = Utility.findViewById(getSupportActionBar().getCustomView(), R.id.browser_url);\n\t\tmWeb = Utility.findViewById(this, R.id.web);\n\t\tmWeb.setWebViewClient(new WebViewClient() {\n\t\t\t@Override\n\t\t\tpublic boolean shouldOverrideUrlLoading(WebView view, String url) {\n\t\t\t\tview.loadUrl(url);\n\t\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t\t\tmInput.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onPageFinished(WebView view, String url) {\n\t\t\t\tmProgress.setProgress(0);\n\t\t\t}\n\t\t});\n\t\tmWeb.setWebChromeClient(new WebChromeClient() {\n\t\t\t@Override\n\t\t\tpublic void onProgressChanged(WebView v, int progress) {\n\t\t\t\tmProgress.setProgress(progress);\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void onReceivedTitle(WebView v, String title) {\n\t\t\t\tgetSupportActionBar().setTitle(title);\n\t\t\t}\n\t\t});\n\t\tmWeb.getSettings().setJavaScriptEnabled(true);\n\t\tmWeb.setDownloadListener(new DownloadListener() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {\n\t\t\t\t\t\/\/ Start MainActivity for downloading\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(url), mimeType);\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t\n\t\t});\n\t\tmUrl.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n\t\t\t@Override\n\t\t\tpublic boolean onEditorAction(TextView v, int actionId, KeyEvent ev) {\n\t\t\t\t\tif (actionId == EditorInfo.IME_ACTION_GO) {\n\t\t\t\t\t\tString url = mUrl.getText().toString();\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (!url.startsWith(\"http\")) {\n\t\t\t\t\t\t\turl = \"http:\/\/\" + url;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tmWeb.loadUrl(url);\n\t\t\t\t\t\tswitchCustom();\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t});\n\t\tmWeb.addJavascriptInterface(new MyJavascriptInterface(), \"HTMLOUT\");\n\t\t\n\t\tmWeb.loadUrl(\"about:blank\");\n\t\t\n\t\tswitchCustom();\n\t\t\n\t\tmToolbar.setOnClickListener(new View.OnClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tswitchCustom();\n\t\t\t}\n\t\t});\n\t}\n\n\t@Override\n\tprotected int getLayoutResource() {\n\t\treturn R.layout.browser;\n\t}\n\n\t@Override\n\tpublic boolean onCreateOptionsMenu(Menu menu) {\n\t\tgetMenuInflater().inflate(R.menu.browser, menu);\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tswitch (item.getItemId()) {\n\t\t\tcase android.R.id.home:\n\t\t\t\tfinish();\n\t\t\t\treturn true;\n\t\t\tcase R.id.detector:\n\t\t\t\tmWeb.loadUrl(\"javascript:window.HTMLOUT.processHTML(''+document.getElementsByTagName('html')[0].innerHTML+'<\/head>');\");\n\t\t\t\treturn true;\n\t\t\tdefault:\n\t\t\t\treturn super.onOptionsItemSelected(item);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void onBackPressed() {\n\t\tif (mWeb.canGoBack()) {\n\t\t\tmWeb.goBack();\n\t\t} else {\n\t\t\tfinish();\n\t\t}\n\t}\n\t\n\tprivate void switchCustom() {\n\t\tint opt = getSupportActionBar().getDisplayOptions();\n\t\t\n\t\tif ((opt & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(false);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(true);\n\t\t\tmInput.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);\n\t\t} else {\n\t\t\tgetSupportActionBar().setDisplayShowCustomEnabled(true);\n\t\t\tgetSupportActionBar().setDisplayShowTitleEnabled(false);\n\t\t\tmInput.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);\n\t\t\tmUrl.requestFocus();\n\t\t\tmUrl.setText(mWeb.getUrl());\n\t\t\tmUrl.setSelection(0, mUrl.getText().length());\n\t\t}\n\t}\n\t\n\tprivate void showVideoChoices(final String[] vids) {\n\t\tnew AlertDialog.Builder(this)\n\t\t\t.setItems(vids, new DialogInterface.OnClickListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(DialogInterface dialog, int id) {\n\t\t\t\t\tIntent i = new Intent();\n\t\t\t\t\ti.setAction(Intent.ACTION_VIEW);\n\t\t\t\t\ti.setDataAndType(Uri.parse(vids[id]), \"application\/octet-stream\");\n\t\t\t\t\tstartActivity(i);\n\t\t\t\t\tfinish();\n\t\t\t\t}\n\t\t\t})\n\t\t\t.show();\n\t}\n\t\n\tclass MyJavascriptInterface {\n\t\tprivate static final String TAG = MyJavascriptInterface.class.getSimpleName();\n\t\t\n\t\tprivate static final String PATTERN = \"[http|https]+[:\/\/]+[0-9A-Za-z:\/[-]_#[?][=][.][&]]*\";\n\t\tprivate static final String[] VIDEO_SUFFIXES = new String[]{\n\t\t\t\".mp4\",\n\t\t\t\".flv\",\n\t\t\t\".rm\",\n\t\t\t\".rmvb\",\n\t\t\t\".wmv\",\n\t\t\t\".avi\",\n\t\t\t\".mkv\",\n\t\t\t\".webm\"\n\t\t};\n\t\t\n\t\t@JavascriptInterface\n\t\tpublic void processHTML(String html) {\n\t\t\tPattern pattern = Pattern.compile(PATTERN);\n\t\t\tMatcher matcher = pattern.matcher(html);\n\t\t\t\n\t\t\tArrayList vid = new ArrayList();\n\t\t\t\n\t\t\twhile (matcher.find()) {\n\t\t\t\tString url = matcher.group();\n\t\t\t\t\n\t\t\t\tboolean isVid = false;\n\t\t\t\t\n\t\t\t\tfor (String suffix : VIDEO_SUFFIXES) {\n\t\t\t\t\tif (url.contains(suffix)) {\n\t\t\t\t\t\tisVid = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (isVid) {\n\t\t\t\t\t\n\t\t\t\t\tvid.add(url);\n\t\t\t\t\t\n\t\t\t\t\tif (DEBUG) {\n\t\t\t\t\t\tLog.d(TAG, \"found url:\" + url);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (vid.size() == 0) return;\n\t\t\t\n\t\t\tString[] arr = new String[vid.size()];\n\t\t\tshowVideoChoices(vid.toArray(arr));\n\t\t}\n\t}\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/erikusaj\/fdroidTvClient\/commit\/6e64438fa6dcdaeed0158da783749b2af51b2c05","commit_message":"'\\\\\"disable UIL image handling while scrolling\\\\n\\\\nThis should speed up the scrolling","source_code":"package org.fdroid.fdroid.views.apps;\n\nimport android.content.Intent;\nimport android.database.Cursor;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.v4.app.LoaderManager;\nimport android.support.v4.content.CursorLoader;\nimport android.support.v4.content.Loader;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.KeyEvent;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.view.inputmethod.InputMethodManager;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport org.fdroid.fdroid.FDroidApp;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.data.AppProvider;\nimport org.fdroid.fdroid.data.Schema;\n\npublic class AppListActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks,\n CategoryTextWatcher.SearchTermsChangedListener {\n\n public static final String EXTRA_CATEGORY\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_CATEGORY\";\n public static final String EXTRA_SEARCH_TERMS\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_SEARCH_TERMS\";\n\n private RecyclerView appView;\n private AppListAdapter appAdapter;\n private String category;\n private String searchTerms;\n private String sortClauseSelected = SortClause.LAST_UPDATED;\n private TextView emptyState;\n private EditText searchInput;\n private ImageView sortImage;\n\n private interface SortClause {\n String NAME = Schema.AppMetadataTable.NAME + \".\" + Schema.AppMetadataTable.Cols.NAME + \" asc\";\n String LAST_UPDATED = Schema.AppMetadataTable.NAME + \".\"\n + Schema.AppMetadataTable.Cols.LAST_UPDATED + \" desc\";\n }\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n ((FDroidApp) getApplication()).applyTheme(this);\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.activity_app_list);\n\n searchInput = (EditText) findViewById(R.id.search);\n searchInput.addTextChangedListener(new CategoryTextWatcher(this, searchInput, this));\n searchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_SEARCH) {\n \/\/ Hide the keyboard (http:\/\/stackoverflow.com\/a\/1109108 (when pressing search)\n InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);\n inputManager.hideSoftInputFromWindow(searchInput.getWindowToken(), 0);\n\n \/\/ Change focus from the search input to the app list.\n appView.requestFocus();\n return true;\n }\n return false;\n }\n });\n\n sortImage = (ImageView) findViewById(R.id.sort);\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n sortImage.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n if (sortClauseSelected.equalsIgnoreCase(SortClause.LAST_UPDATED)) {\n sortClauseSelected = SortClause.NAME;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_az_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_az_white);\n }\n } else {\n sortClauseSelected = SortClause.LAST_UPDATED;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n }\n getSupportLoaderManager().restartLoader(0, null, AppListActivity.this);\n appView.scrollToPosition(0);\n }\n });\n\n emptyState = (TextView) findViewById(R.id.empty_state);\n\n View backButton = findViewById(R.id.back);\n backButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n finish();\n }\n });\n\n View clearButton = findViewById(R.id.clear);\n clearButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n searchInput.setText(\"\");\n }\n });\n\n appAdapter = new AppListAdapter(this);\n\n appView = (RecyclerView) findViewById(R.id.app_list);\n appView.setHasFixedSize(true);\n appView.setLayoutManager(new LinearLayoutManager(this));\n appView.setAdapter(appAdapter);\n\n parseIntentForSearchQuery();\n }\n\n private void parseIntentForSearchQuery() {\n Intent intent = getIntent();\n category = intent.hasExtra(EXTRA_CATEGORY) ? intent.getStringExtra(EXTRA_CATEGORY) : null;\n searchTerms = intent.hasExtra(EXTRA_SEARCH_TERMS) ? intent.getStringExtra(EXTRA_SEARCH_TERMS) : null;\n\n searchInput.setText(getSearchText(category, searchTerms));\n searchInput.setSelection(searchInput.getText().length());\n\n if (category != null) {\n \/\/ Do this so that the search input does not get focus by default. This allows for a user\n \/\/ experience where the user scrolls through the apps in the category.\n appView.requestFocus();\n }\n\n getSupportLoaderManager().initLoader(0, null, this);\n }\n\n private CharSequence getSearchText(@Nullable String category, @Nullable String searchTerms) {\n StringBuilder string = new StringBuilder();\n if (category != null) {\n string.append(category).append(\":\");\n }\n\n if (searchTerms != null) {\n string.append(searchTerms);\n }\n\n return string.toString();\n }\n\n @Override\n public Loader onCreateLoader(int id, Bundle args) {\n return new CursorLoader(\n this,\n AppProvider.getSearchUri(searchTerms, category),\n Schema.AppMetadataTable.Cols.ALL,\n null,\n null,\n sortClauseSelected\n );\n }\n\n @Override\n public void onLoadFinished(Loader loader, Cursor cursor) {\n appAdapter.setAppCursor(cursor);\n if (cursor.getCount() > 0) {\n emptyState.setVisibility(View.GONE);\n appView.setVisibility(View.VISIBLE);\n } else {\n emptyState.setVisibility(View.VISIBLE);\n appView.setVisibility(View.GONE);\n }\n }\n\n @Override\n public void onLoaderReset(Loader loader) {\n appAdapter.setAppCursor(null);\n }\n\n @Override\n public void onSearchTermsChanged(@Nullable String category, @NonNull String searchTerms) {\n this.category = category;\n this.searchTerms = searchTerms;\n getSupportLoaderManager().restartLoader(0, null, this);\n }\n}\n","target_code":"package org.fdroid.fdroid.views.apps;\n\nimport android.content.Intent;\nimport android.database.Cursor;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.v4.app.LoaderManager;\nimport android.support.v4.content.CursorLoader;\nimport android.support.v4.content.Loader;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.KeyEvent;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.view.inputmethod.InputMethodManager;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport com.nostra13.universalimageloader.core.ImageLoader;\nimport org.fdroid.fdroid.FDroidApp;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.data.AppProvider;\nimport org.fdroid.fdroid.data.Schema;\n\npublic class AppListActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks,\n CategoryTextWatcher.SearchTermsChangedListener {\n\n public static final String EXTRA_CATEGORY\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_CATEGORY\";\n public static final String EXTRA_SEARCH_TERMS\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_SEARCH_TERMS\";\n\n private RecyclerView appView;\n private AppListAdapter appAdapter;\n private String category;\n private String searchTerms;\n private String sortClauseSelected = SortClause.LAST_UPDATED;\n private TextView emptyState;\n private EditText searchInput;\n private ImageView sortImage;\n\n private interface SortClause {\n String NAME = Schema.AppMetadataTable.NAME + \".\" + Schema.AppMetadataTable.Cols.NAME + \" asc\";\n String LAST_UPDATED = Schema.AppMetadataTable.NAME + \".\"\n + Schema.AppMetadataTable.Cols.LAST_UPDATED + \" desc\";\n }\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n ((FDroidApp) getApplication()).applyTheme(this);\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.activity_app_list);\n\n searchInput = (EditText) findViewById(R.id.search);\n searchInput.addTextChangedListener(new CategoryTextWatcher(this, searchInput, this));\n searchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_SEARCH) {\n \/\/ Hide the keyboard (http:\/\/stackoverflow.com\/a\/1109108 (when pressing search)\n InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);\n inputManager.hideSoftInputFromWindow(searchInput.getWindowToken(), 0);\n\n \/\/ Change focus from the search input to the app list.\n appView.requestFocus();\n return true;\n }\n return false;\n }\n });\n\n sortImage = (ImageView) findViewById(R.id.sort);\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n sortImage.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n if (sortClauseSelected.equalsIgnoreCase(SortClause.LAST_UPDATED)) {\n sortClauseSelected = SortClause.NAME;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_az_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_az_white);\n }\n } else {\n sortClauseSelected = SortClause.LAST_UPDATED;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n }\n getSupportLoaderManager().restartLoader(0, null, AppListActivity.this);\n appView.scrollToPosition(0);\n }\n });\n\n emptyState = (TextView) findViewById(R.id.empty_state);\n\n View backButton = findViewById(R.id.back);\n backButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n finish();\n }\n });\n\n View clearButton = findViewById(R.id.clear);\n clearButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n searchInput.setText(\"\");\n }\n });\n\n appAdapter = new AppListAdapter(this);\n\n appView = (RecyclerView) findViewById(R.id.app_list);\n appView.setHasFixedSize(true);\n appView.setLayoutManager(new LinearLayoutManager(this));\n appView.setAdapter(appAdapter);\n appView.addOnScrollListener(new RecyclerView.OnScrollListener() {\n private final ImageLoader imageLoader = ImageLoader.getInstance();\n\n @Override\n public void onScrollStateChanged(RecyclerView recyclerView, int newState) {\n switch (newState) {\n case RecyclerView.SCROLL_STATE_DRAGGING:\n imageLoader.pause();\n break;\n case RecyclerView.SCROLL_STATE_IDLE:\n imageLoader.resume();\n break;\n }\n super.onScrollStateChanged(recyclerView, newState);\n }\n });\n\n parseIntentForSearchQuery();\n }\n\n private void parseIntentForSearchQuery() {\n Intent intent = getIntent();\n category = intent.hasExtra(EXTRA_CATEGORY) ? intent.getStringExtra(EXTRA_CATEGORY) : null;\n searchTerms = intent.hasExtra(EXTRA_SEARCH_TERMS) ? intent.getStringExtra(EXTRA_SEARCH_TERMS) : null;\n\n searchInput.setText(getSearchText(category, searchTerms));\n searchInput.setSelection(searchInput.getText().length());\n\n if (category != null) {\n \/\/ Do this so that the search input does not get focus by default. This allows for a user\n \/\/ experience where the user scrolls through the apps in the category.\n appView.requestFocus();\n }\n\n getSupportLoaderManager().initLoader(0, null, this);\n }\n\n private CharSequence getSearchText(@Nullable String category, @Nullable String searchTerms) {\n StringBuilder string = new StringBuilder();\n if (category != null) {\n string.append(category).append(\":\");\n }\n\n if (searchTerms != null) {\n string.append(searchTerms);\n }\n\n return string.toString();\n }\n\n @Override\n public Loader onCreateLoader(int id, Bundle args) {\n return new CursorLoader(\n this,\n AppProvider.getSearchUri(searchTerms, category),\n Schema.AppMetadataTable.Cols.ALL,\n null,\n null,\n sortClauseSelected\n );\n }\n\n @Override\n public void onLoadFinished(Loader loader, Cursor cursor) {\n appAdapter.setAppCursor(cursor);\n if (cursor.getCount() > 0) {\n emptyState.setVisibility(View.GONE);\n appView.setVisibility(View.VISIBLE);\n } else {\n emptyState.setVisibility(View.VISIBLE);\n appView.setVisibility(View.GONE);\n }\n }\n\n @Override\n public void onLoaderReset(Loader loader) {\n appAdapter.setAppCursor(null);\n }\n\n @Override\n public void onSearchTermsChanged(@Nullable String category, @NonNull String searchTerms) {\n this.category = category;\n this.searchTerms = searchTerms;\n getSupportLoaderManager().restartLoader(0, null, this);\n }\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid.views.apps;\n\nimport android.content.Intent;\nimport android.database.Cursor;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.v4.app.LoaderManager;\nimport android.support.v4.content.CursorLoader;\nimport android.support.v4.content.Loader;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.KeyEvent;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.view.inputmethod.InputMethodManager;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport org.fdroid.fdroid.FDroidApp;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.data.AppProvider;\nimport org.fdroid.fdroid.data.Schema;\n\npublic class AppListActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks,\n CategoryTextWatcher.SearchTermsChangedListener {\n\n public static final String EXTRA_CATEGORY\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_CATEGORY\";\n public static final String EXTRA_SEARCH_TERMS\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_SEARCH_TERMS\";\n\n private RecyclerView appView;\n private AppListAdapter appAdapter;\n private String category;\n private String searchTerms;\n private String sortClauseSelected = SortClause.LAST_UPDATED;\n private TextView emptyState;\n private EditText searchInput;\n private ImageView sortImage;\n\n private interface SortClause {\n String NAME = Schema.AppMetadataTable.NAME + \".\" + Schema.AppMetadataTable.Cols.NAME + \" asc\";\n String LAST_UPDATED = Schema.AppMetadataTable.NAME + \".\"\n + Schema.AppMetadataTable.Cols.LAST_UPDATED + \" desc\";\n }\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n ((FDroidApp) getApplication()).applyTheme(this);\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.activity_app_list);\n\n searchInput = (EditText) findViewById(R.id.search);\n searchInput.addTextChangedListener(new CategoryTextWatcher(this, searchInput, this));\n searchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_SEARCH) {\n \/\/ Hide the keyboard (http:\/\/stackoverflow.com\/a\/1109108 (when pressing search)\n InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);\n inputManager.hideSoftInputFromWindow(searchInput.getWindowToken(), 0);\n\n \/\/ Change focus from the search input to the app list.\n appView.requestFocus();\n return true;\n }\n return false;\n }\n });\n\n sortImage = (ImageView) findViewById(R.id.sort);\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n sortImage.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n if (sortClauseSelected.equalsIgnoreCase(SortClause.LAST_UPDATED)) {\n sortClauseSelected = SortClause.NAME;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_az_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_az_white);\n }\n } else {\n sortClauseSelected = SortClause.LAST_UPDATED;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n }\n getSupportLoaderManager().restartLoader(0, null, AppListActivity.this);\n appView.scrollToPosition(0);\n }\n });\n\n emptyState = (TextView) findViewById(R.id.empty_state);\n\n View backButton = findViewById(R.id.back);\n backButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n finish();\n }\n });\n\n View clearButton = findViewById(R.id.clear);\n clearButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n searchInput.setText(\"\");\n }\n });\n\n appAdapter = new AppListAdapter(this);\n\n appView = (RecyclerView) findViewById(R.id.app_list);\n appView.setHasFixedSize(true);\n appView.setLayoutManager(new LinearLayoutManager(this));\n appView.setAdapter(appAdapter);\n\n parseIntentForSearchQuery();\n }\n\n private void parseIntentForSearchQuery() {\n Intent intent = getIntent();\n category = intent.hasExtra(EXTRA_CATEGORY) ? intent.getStringExtra(EXTRA_CATEGORY) : null;\n searchTerms = intent.hasExtra(EXTRA_SEARCH_TERMS) ? intent.getStringExtra(EXTRA_SEARCH_TERMS) : null;\n\n searchInput.setText(getSearchText(category, searchTerms));\n searchInput.setSelection(searchInput.getText().length());\n\n if (category != null) {\n \/\/ Do this so that the search input does not get focus by default. This allows for a user\n \/\/ experience where the user scrolls through the apps in the category.\n appView.requestFocus();\n }\n\n getSupportLoaderManager().initLoader(0, null, this);\n }\n\n private CharSequence getSearchText(@Nullable String category, @Nullable String searchTerms) {\n StringBuilder string = new StringBuilder();\n if (category != null) {\n string.append(category).append(\":\");\n }\n\n if (searchTerms != null) {\n string.append(searchTerms);\n }\n\n return string.toString();\n }\n\n @Override\n public Loader onCreateLoader(int id, Bundle args) {\n return new CursorLoader(\n this,\n AppProvider.getSearchUri(searchTerms, category),\n Schema.AppMetadataTable.Cols.ALL,\n null,\n null,\n sortClauseSelected\n );\n }\n\n @Override\n public void onLoadFinished(Loader loader, Cursor cursor) {\n appAdapter.setAppCursor(cursor);\n if (cursor.getCount() > 0) {\n emptyState.setVisibility(View.GONE);\n appView.setVisibility(View.VISIBLE);\n } else {\n emptyState.setVisibility(View.VISIBLE);\n appView.setVisibility(View.GONE);\n }\n }\n\n @Override\n public void onLoaderReset(Loader loader) {\n appAdapter.setAppCursor(null);\n }\n\n @Override\n public void onSearchTermsChanged(@Nullable String category, @NonNull String searchTerms) {\n this.category = category;\n this.searchTerms = searchTerms;\n getSupportLoaderManager().restartLoader(0, null, this);\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid.views.apps;\n\nimport android.content.Intent;\nimport android.database.Cursor;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.v4.app.LoaderManager;\nimport android.support.v4.content.CursorLoader;\nimport android.support.v4.content.Loader;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.KeyEvent;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.view.inputmethod.InputMethodManager;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport org.fdroid.fdroid.FDroidApp;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.data.AppProvider;\nimport org.fdroid.fdroid.data.Schema;\n\npublic class AppListActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks,\n CategoryTextWatcher.SearchTermsChangedListener {\n\n public static final String EXTRA_CATEGORY\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_CATEGORY\";\n public static final String EXTRA_SEARCH_TERMS\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_SEARCH_TERMS\";\n\n private RecyclerView appView;\n private AppListAdapter appAdapter;\n private String category;\n private String searchTerms;\n private String sortClauseSelected = SortClause.LAST_UPDATED;\n private TextView emptyState;\n private EditText searchInput;\n private ImageView sortImage;\n\n private interface SortClause {\n String NAME = Schema.AppMetadataTable.NAME + \".\" + Schema.AppMetadataTable.Cols.NAME + \" asc\";\n String LAST_UPDATED = Schema.AppMetadataTable.NAME + \".\"\n + Schema.AppMetadataTable.Cols.LAST_UPDATED + \" desc\";\n }\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n ((FDroidApp) getApplication()).applyTheme(this);\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.activity_app_list);\n\n searchInput = (EditText) findViewById(R.id.search);\n searchInput.addTextChangedListener(new CategoryTextWatcher(this, searchInput, this));\n searchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_SEARCH) {\n \/\/ Hide the keyboard (http:\/\/stackoverflow.com\/a\/1109108 (when pressing search)\n InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);\n inputManager.hideSoftInputFromWindow(searchInput.getWindowToken(), 0);\n\n \/\/ Change focus from the search input to the app list.\n appView.requestFocus();\n return true;\n }\n return false;\n }\n });\n\n sortImage = (ImageView) findViewById(R.id.sort);\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n sortImage.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n if (sortClauseSelected.equalsIgnoreCase(SortClause.LAST_UPDATED)) {\n sortClauseSelected = SortClause.NAME;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_az_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_az_white);\n }\n } else {\n sortClauseSelected = SortClause.LAST_UPDATED;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n }\n getSupportLoaderManager().restartLoader(0, null, AppListActivity.this);\n appView.scrollToPosition(0);\n }\n });\n\n emptyState = (TextView) findViewById(R.id.empty_state);\n\n View backButton = findViewById(R.id.back);\n backButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n finish();\n }\n });\n\n View clearButton = findViewById(R.id.clear);\n clearButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n searchInput.setText(\"\");\n }\n });\n\n appAdapter = new AppListAdapter(this);\n\n appView = (RecyclerView) findViewById(R.id.app_list);\n appView.setHasFixedSize(true);\n appView.setLayoutManager(new LinearLayoutManager(this));\n appView.setAdapter(appAdapter);\n\n parseIntentForSearchQuery();\n }\n\n private void parseIntentForSearchQuery() {\n Intent intent = getIntent();\n category = intent.hasExtra(EXTRA_CATEGORY) ? intent.getStringExtra(EXTRA_CATEGORY) : null;\n searchTerms = intent.hasExtra(EXTRA_SEARCH_TERMS) ? intent.getStringExtra(EXTRA_SEARCH_TERMS) : null;\n\n searchInput.setText(getSearchText(category, searchTerms));\n searchInput.setSelection(searchInput.getText().length());\n\n if (category != null) {\n \/\/ Do this so that the search input does not get focus by default. This allows for a user\n \/\/ experience where the user scrolls through the apps in the category.\n appView.requestFocus();\n }\n\n getSupportLoaderManager().initLoader(0, null, this);\n }\n\n private CharSequence getSearchText(@Nullable String category, @Nullable String searchTerms) {\n StringBuilder string = new StringBuilder();\n if (category != null) {\n string.append(category).append(\":\");\n }\n\n if (searchTerms != null) {\n string.append(searchTerms);\n }\n\n return string.toString();\n }\n\n @Override\n public Loader onCreateLoader(int id, Bundle args) {\n return new CursorLoader(\n this,\n AppProvider.getSearchUri(searchTerms, category),\n Schema.AppMetadataTable.Cols.ALL,\n null,\n null,\n sortClauseSelected\n );\n }\n\n @Override\n public void onLoadFinished(Loader loader, Cursor cursor) {\n appAdapter.setAppCursor(cursor);\n if (cursor.getCount() > 0) {\n emptyState.setVisibility(View.GONE);\n appView.setVisibility(View.VISIBLE);\n } else {\n emptyState.setVisibility(View.VISIBLE);\n appView.setVisibility(View.GONE);\n }\n }\n\n @Override\n public void onLoaderReset(Loader loader) {\n appAdapter.setAppCursor(null);\n }\n\n @Override\n public void onSearchTermsChanged(@Nullable String category, @NonNull String searchTerms) {\n this.category = category;\n this.searchTerms = searchTerms;\n getSupportLoaderManager().restartLoader(0, null, this);\n }\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid.views.apps;\n\nimport android.content.Intent;\nimport android.database.Cursor;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.v4.app.LoaderManager;\nimport android.support.v4.content.CursorLoader;\nimport android.support.v4.content.Loader;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.KeyEvent;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.view.inputmethod.InputMethodManager;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport org.fdroid.fdroid.FDroidApp;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.data.AppProvider;\nimport org.fdroid.fdroid.data.Schema;\n\npublic class AppListActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks,\n CategoryTextWatcher.SearchTermsChangedListener {\n\n public static final String EXTRA_CATEGORY\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_CATEGORY\";\n public static final String EXTRA_SEARCH_TERMS\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_SEARCH_TERMS\";\n\n private RecyclerView appView;\n private AppListAdapter appAdapter;\n private String category;\n private String searchTerms;\n private String sortClauseSelected = SortClause.LAST_UPDATED;\n private TextView emptyState;\n private EditText searchInput;\n private ImageView sortImage;\n\n private interface SortClause {\n String NAME = Schema.AppMetadataTable.NAME + \".\" + Schema.AppMetadataTable.Cols.NAME + \" asc\";\n String LAST_UPDATED = Schema.AppMetadataTable.NAME + \".\"\n + Schema.AppMetadataTable.Cols.LAST_UPDATED + \" desc\";\n }\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n ((FDroidApp) getApplication()).applyTheme(this);\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.activity_app_list);\n\n searchInput = (EditText) findViewById(R.id.search);\n searchInput.addTextChangedListener(new CategoryTextWatcher(this, searchInput, this));\n searchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_SEARCH) {\n \/\/ Hide the keyboard (http:\/\/stackoverflow.com\/a\/1109108 (when pressing search)\n InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);\n inputManager.hideSoftInputFromWindow(searchInput.getWindowToken(), 0);\n\n \/\/ Change focus from the search input to the app list.\n appView.requestFocus();\n return true;\n }\n return false;\n }\n });\n\n sortImage = (ImageView) findViewById(R.id.sort);\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n sortImage.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n if (sortClauseSelected.equalsIgnoreCase(SortClause.LAST_UPDATED)) {\n sortClauseSelected = SortClause.NAME;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_az_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_az_white);\n }\n } else {\n sortClauseSelected = SortClause.LAST_UPDATED;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n }\n getSupportLoaderManager().restartLoader(0, null, AppListActivity.this);\n appView.scrollToPosition(0);\n }\n });\n\n emptyState = (TextView) findViewById(R.id.empty_state);\n\n View backButton = findViewById(R.id.back);\n backButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n finish();\n }\n });\n\n View clearButton = findViewById(R.id.clear);\n clearButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n searchInput.setText(\"\");\n }\n });\n\n appAdapter = new AppListAdapter(this);\n\n appView = (RecyclerView) findViewById(R.id.app_list);\n appView.setHasFixedSize(true);\n appView.setLayoutManager(new LinearLayoutManager(this));\n appView.setAdapter(appAdapter);\n\n parseIntentForSearchQuery();\n }\n\n private void parseIntentForSearchQuery() {\n Intent intent = getIntent();\n category = intent.hasExtra(EXTRA_CATEGORY) ? intent.getStringExtra(EXTRA_CATEGORY) : null;\n searchTerms = intent.hasExtra(EXTRA_SEARCH_TERMS) ? intent.getStringExtra(EXTRA_SEARCH_TERMS) : null;\n\n searchInput.setText(getSearchText(category, searchTerms));\n searchInput.setSelection(searchInput.getText().length());\n\n if (category != null) {\n \/\/ Do this so that the search input does not get focus by default. This allows for a user\n \/\/ experience where the user scrolls through the apps in the category.\n appView.requestFocus();\n }\n\n getSupportLoaderManager().initLoader(0, null, this);\n }\n\n private CharSequence getSearchText(@Nullable String category, @Nullable String searchTerms) {\n StringBuilder string = new StringBuilder();\n if (category != null) {\n string.append(category).append(\":\");\n }\n\n if (searchTerms != null) {\n string.append(searchTerms);\n }\n\n return string.toString();\n }\n\n @Override\n public Loader onCreateLoader(int id, Bundle args) {\n return new CursorLoader(\n this,\n AppProvider.getSearchUri(searchTerms, category),\n Schema.AppMetadataTable.Cols.ALL,\n null,\n null,\n sortClauseSelected\n );\n }\n\n @Override\n public void onLoadFinished(Loader loader, Cursor cursor) {\n appAdapter.setAppCursor(cursor);\n if (cursor.getCount() > 0) {\n emptyState.setVisibility(View.GONE);\n appView.setVisibility(View.VISIBLE);\n } else {\n emptyState.setVisibility(View.VISIBLE);\n appView.setVisibility(View.GONE);\n }\n }\n\n @Override\n public void onLoaderReset(Loader loader) {\n appAdapter.setAppCursor(null);\n }\n\n @Override\n public void onSearchTermsChanged(@Nullable String category, @NonNull String searchTerms) {\n this.category = category;\n this.searchTerms = searchTerms;\n getSupportLoaderManager().restartLoader(0, null, this);\n }\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nDisable UIL image handling while scrolling to improve execution time. Write the entire code and no other text in the response.\n\n### Concepts:\n[+] com.nostra13.universalimageloader.core.ImageLoader\n[+] appView.addOnScrollListener\n[+] RecyclerView.OnScrollListener\n[in] onCreate function\n[override] onScrollStateChanged(RecyclerView recyclerView, int newState)\n\n### Given program:\n```java\npackage org.fdroid.fdroid.views.apps;\n\nimport android.content.Intent;\nimport android.database.Cursor;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.v4.app.LoaderManager;\nimport android.support.v4.content.CursorLoader;\nimport android.support.v4.content.Loader;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.KeyEvent;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.view.inputmethod.InputMethodManager;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport org.fdroid.fdroid.FDroidApp;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.data.AppProvider;\nimport org.fdroid.fdroid.data.Schema;\n\npublic class AppListActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks,\n CategoryTextWatcher.SearchTermsChangedListener {\n\n public static final String EXTRA_CATEGORY\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_CATEGORY\";\n public static final String EXTRA_SEARCH_TERMS\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_SEARCH_TERMS\";\n\n private RecyclerView appView;\n private AppListAdapter appAdapter;\n private String category;\n private String searchTerms;\n private String sortClauseSelected = SortClause.LAST_UPDATED;\n private TextView emptyState;\n private EditText searchInput;\n private ImageView sortImage;\n\n private interface SortClause {\n String NAME = Schema.AppMetadataTable.NAME + \".\" + Schema.AppMetadataTable.Cols.NAME + \" asc\";\n String LAST_UPDATED = Schema.AppMetadataTable.NAME + \".\"\n + Schema.AppMetadataTable.Cols.LAST_UPDATED + \" desc\";\n }\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n ((FDroidApp) getApplication()).applyTheme(this);\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.activity_app_list);\n\n searchInput = (EditText) findViewById(R.id.search);\n searchInput.addTextChangedListener(new CategoryTextWatcher(this, searchInput, this));\n searchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_SEARCH) {\n \/\/ Hide the keyboard (http:\/\/stackoverflow.com\/a\/1109108 (when pressing search)\n InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);\n inputManager.hideSoftInputFromWindow(searchInput.getWindowToken(), 0);\n\n \/\/ Change focus from the search input to the app list.\n appView.requestFocus();\n return true;\n }\n return false;\n }\n });\n\n sortImage = (ImageView) findViewById(R.id.sort);\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n sortImage.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n if (sortClauseSelected.equalsIgnoreCase(SortClause.LAST_UPDATED)) {\n sortClauseSelected = SortClause.NAME;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_az_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_az_white);\n }\n } else {\n sortClauseSelected = SortClause.LAST_UPDATED;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n }\n getSupportLoaderManager().restartLoader(0, null, AppListActivity.this);\n appView.scrollToPosition(0);\n }\n });\n\n emptyState = (TextView) findViewById(R.id.empty_state);\n\n View backButton = findViewById(R.id.back);\n backButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n finish();\n }\n });\n\n View clearButton = findViewById(R.id.clear);\n clearButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n searchInput.setText(\"\");\n }\n });\n\n appAdapter = new AppListAdapter(this);\n\n appView = (RecyclerView) findViewById(R.id.app_list);\n appView.setHasFixedSize(true);\n appView.setLayoutManager(new LinearLayoutManager(this));\n appView.setAdapter(appAdapter);\n\n parseIntentForSearchQuery();\n }\n\n private void parseIntentForSearchQuery() {\n Intent intent = getIntent();\n category = intent.hasExtra(EXTRA_CATEGORY) ? intent.getStringExtra(EXTRA_CATEGORY) : null;\n searchTerms = intent.hasExtra(EXTRA_SEARCH_TERMS) ? intent.getStringExtra(EXTRA_SEARCH_TERMS) : null;\n\n searchInput.setText(getSearchText(category, searchTerms));\n searchInput.setSelection(searchInput.getText().length());\n\n if (category != null) {\n \/\/ Do this so that the search input does not get focus by default. This allows for a user\n \/\/ experience where the user scrolls through the apps in the category.\n appView.requestFocus();\n }\n\n getSupportLoaderManager().initLoader(0, null, this);\n }\n\n private CharSequence getSearchText(@Nullable String category, @Nullable String searchTerms) {\n StringBuilder string = new StringBuilder();\n if (category != null) {\n string.append(category).append(\":\");\n }\n\n if (searchTerms != null) {\n string.append(searchTerms);\n }\n\n return string.toString();\n }\n\n @Override\n public Loader onCreateLoader(int id, Bundle args) {\n return new CursorLoader(\n this,\n AppProvider.getSearchUri(searchTerms, category),\n Schema.AppMetadataTable.Cols.ALL,\n null,\n null,\n sortClauseSelected\n );\n }\n\n @Override\n public void onLoadFinished(Loader loader, Cursor cursor) {\n appAdapter.setAppCursor(cursor);\n if (cursor.getCount() > 0) {\n emptyState.setVisibility(View.GONE);\n appView.setVisibility(View.VISIBLE);\n } else {\n emptyState.setVisibility(View.VISIBLE);\n appView.setVisibility(View.GONE);\n }\n }\n\n @Override\n public void onLoaderReset(Loader loader) {\n appAdapter.setAppCursor(null);\n }\n\n @Override\n public void onSearchTermsChanged(@Nullable String category, @NonNull String searchTerms) {\n this.category = category;\n this.searchTerms = searchTerms;\n getSupportLoaderManager().restartLoader(0, null, this);\n }\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage acr.browser.lightning.utils;\n\nimport android.content.Context;\nimport android.content.res.AssetManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.util.Log;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.inject.Inject;\nimport javax.inject.Singleton;\n\nimport acr.browser.lightning.app.BrowserApp;\nimport acr.browser.lightning.constant.Constants;\nimport acr.browser.lightning.preference.PreferenceManager;\n\n@Singleton\npublic class AdBlock {\n\n private static final String TAG = \"AdBlock\";\n private static final String BLOCKED_DOMAINS_LIST_FILE_NAME = \"hosts.txt\";\n private static final String LOCAL_IP_V4 = \"127.0.0.1\";\n private static final String LOCAL_IP_V4_ALT = \"0.0.0.0\";\n private static final String LOCAL_IP_V6 = \"::1\";\n private static final String LOCALHOST = \"localhost\";\n private static final String COMMENT = \"#\";\n private static final String TAB = \"\\t\";\n private static final String SPACE = \" \";\n private static final String EMPTY = \"\";\n private final Set mBlockedDomainsList = new HashSet<>();\n private boolean mBlockAds;\n\n @Inject PreferenceManager mPreferenceManager;\n\n @Inject\n public AdBlock(@NonNull Context context) {\n BrowserApp.getAppComponent().inject(this);\n if (mBlockedDomainsList.isEmpty() && Constants.FULL_VERSION) {\n loadHostsFile(context);\n }\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n public void updatePreference() {\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n private void loadBlockedDomainsList(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n String line;\n while ((line = reader.readLine()) != null) {\n mBlockedDomainsList.add(line.trim());\n }\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n\n \/**\n * a method that determines if the given URL is an ad or not. It performs\n * a search of the URL's domain on the blocked domain hash set.\n *\n * @param url the URL to check for being an ad\n * @return true if it is an ad, false if it is not an ad\n *\/\n public boolean isAd(@Nullable String url) {\n if (!mBlockAds || url == null) {\n return false;\n }\n\n String domain;\n try {\n domain = getDomainName(url);\n } catch (URISyntaxException e) {\n Log.d(TAG, \"URL '\" + url + \"' is invalid\", e);\n return false;\n }\n\n boolean isOnBlacklist = mBlockedDomainsList.contains(domain);\n if (isOnBlacklist) {\n Log.d(TAG, \"URL '\" + url + \"' is an ad\");\n }\n return isOnBlacklist;\n }\n\n \/**\n * Returns the probable domain name for a given URL\n *\n * @param url the url to parse\n * @return returns the domain\n * @throws URISyntaxException throws an exception if the string cannot form a URI\n *\/\n @NonNull\n private static String getDomainName(@NonNull String url) throws URISyntaxException {\n int index = url.indexOf('\/', 8);\n if (index != -1) {\n url = url.substring(0, index);\n }\n\n URI uri = new URI(url);\n String domain = uri.getHost();\n if (domain == null) {\n return url;\n }\n\n return domain.startsWith(\"www.\") ? domain.substring(4) : domain;\n }\n\n \/**\n * This method reads through a hosts file and extracts the domains that should\n * be redirected to localhost (a.k.a. IP address 127.0.0.1). It can handle files that\n * simply have a list of hostnames to block, or it can handle a full blown hosts file.\n * It will strip out comments, references to the base IP address and just extract the\n * domains to be used\n *\n * @param context the context needed to read the file\n *\/\n private void loadHostsFile(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n StringBuilder lineBuilder = new StringBuilder();\n String line;\n long time = System.currentTimeMillis();\n \/\/ TODO: 4\/23\/17 Improve performance by reading in on IO thread and then processing on worker thread\n while ((line = reader.readLine()) != null) {\n lineBuilder.append(line);\n\n if (!isEmpty(lineBuilder) && !startsWith(lineBuilder, COMMENT)) {\n replace(lineBuilder, LOCAL_IP_V4, EMPTY);\n replace(lineBuilder, LOCAL_IP_V4_ALT, EMPTY);\n replace(lineBuilder, LOCAL_IP_V6, EMPTY);\n replace(lineBuilder, TAB, EMPTY);\n\n int comment = lineBuilder.indexOf(COMMENT);\n if (comment >= 0) {\n lineBuilder.replace(comment, lineBuilder.length(), EMPTY);\n }\n\n trim(lineBuilder);\n\n if (!isEmpty(lineBuilder) && !AdBlock.equals(lineBuilder, LOCALHOST)) {\n while (contains(lineBuilder, SPACE)) {\n int space = lineBuilder.indexOf(SPACE);\n String host = lineBuilder.substring(0, space);\n replace(lineBuilder, host, EMPTY);\n mBlockedDomainsList.add(host.trim());\n }\n if (lineBuilder.length() > 0) {\n mBlockedDomainsList.add(lineBuilder.toString());\n }\n }\n }\n lineBuilder.setLength(0);\n }\n Log.d(TAG, \"Loaded ad list in: \" + (System.currentTimeMillis() - time) + \" ms\");\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n\n \/\/ TODO: 4\/23\/17 Move all these methods to a StringUtils class\n private static void replace(@NonNull StringBuilder stringBuilder,\n @NonNull String toReplace,\n @NonNull String replacement) {\n int index = stringBuilder.indexOf(toReplace);\n if (index >= 0) {\n stringBuilder.replace(index, index + toReplace.length(), replacement);\n }\n }\n\n private static void trim(@NonNull StringBuilder stringBuilder) {\n while (stringBuilder.indexOf(SPACE) == 0) {\n stringBuilder.replace(0, 1, EMPTY);\n }\n\n while (stringBuilder.lastIndexOf(SPACE) == (stringBuilder.length() - 1)) {\n stringBuilder.replace(stringBuilder.length() - 1, stringBuilder.length(), EMPTY);\n }\n }\n\n private static boolean isEmpty(@NonNull StringBuilder stringBuilder) {\n return stringBuilder.length() == 0;\n }\n\n private static boolean startsWith(@NonNull StringBuilder stringBuilder, @NonNull String start) {\n return stringBuilder.indexOf(start) == 0;\n }\n\n private static boolean contains(@NonNull StringBuilder stringBuilder, @NonNull String contains) {\n return stringBuilder.indexOf(contains) >= 0;\n }\n\n private static boolean equals(@NonNull StringBuilder stringBuilder, @NonNull String equal) {\n int index = stringBuilder.indexOf(equal);\n return index >= 0 && stringBuilder.length() == equal.length();\n }\n}\n\n\nCode-B:\npackage acr.browser.lightning.utils;\n\nimport android.content.Context;\nimport android.content.res.AssetManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.util.Log;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.inject.Inject;\nimport javax.inject.Singleton;\n\nimport acr.browser.lightning.app.BrowserApp;\nimport acr.browser.lightning.constant.Constants;\nimport acr.browser.lightning.preference.PreferenceManager;\n\n@Singleton\npublic class AdBlock {\n\n private static final String TAG = \"AdBlock\";\n private static final String BLOCKED_DOMAINS_LIST_FILE_NAME = \"hosts.txt\";\n private static final String LOCAL_IP_V4 = \"127.0.0.1\";\n private static final String LOCAL_IP_V4_ALT = \"0.0.0.0\";\n private static final String LOCAL_IP_V6 = \"::1\";\n private static final String LOCALHOST = \"localhost\";\n private static final String COMMENT = \"#\";\n private static final String TAB = \"\\t\";\n private static final String SPACE = \" \";\n private static final String EMPTY = \"\";\n private final Set mBlockedDomainsList = new HashSet<>();\n private boolean mBlockAds;\n\n @Inject PreferenceManager mPreferenceManager;\n\n @Inject\n public AdBlock(@NonNull Context context) {\n BrowserApp.getAppComponent().inject(this);\n if (mBlockedDomainsList.isEmpty() && Constants.FULL_VERSION) {\n loadHostsFile(context);\n }\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n public void updatePreference() {\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n private void loadBlockedDomainsList(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n String line;\n while ((line = reader.readLine()) != null) {\n mBlockedDomainsList.add(line.trim());\n }\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n\n \/**\n * a method that determines if the given URL is an ad or not. It performs\n * a search of the URL's domain on the blocked domain hash set.\n *\n * @param url the URL to check for being an ad\n * @return true if it is an ad, false if it is not an ad\n *\/\n public boolean isAd(@Nullable String url) {\n if (!mBlockAds || url == null) {\n return false;\n }\n\n String domain;\n try {\n domain = getDomainName(url);\n } catch (URISyntaxException e) {\n Log.d(TAG, \"URL '\" + url + \"' is invalid\", e);\n return false;\n }\n\n boolean isOnBlacklist = mBlockedDomainsList.contains(domain);\n if (isOnBlacklist) {\n Log.d(TAG, \"URL '\" + url + \"' is an ad\");\n }\n return isOnBlacklist;\n }\n\n \/**\n * Returns the probable domain name for a given URL\n *\n * @param url the url to parse\n * @return returns the domain\n * @throws URISyntaxException throws an exception if the string cannot form a URI\n *\/\n @NonNull\n private static String getDomainName(@NonNull String url) throws URISyntaxException {\n int index = url.indexOf('\/', 8);\n if (index != -1) {\n url = url.substring(0, index);\n }\n\n URI uri = new URI(url);\n String domain = uri.getHost();\n if (domain == null) {\n return url;\n }\n\n return domain.startsWith(\"www.\") ? domain.substring(4) : domain;\n }\n\n \/**\n * This method reads through a hosts file and extracts the domains that should\n * be redirected to localhost (a.k.a. IP address 127.0.0.1). It can handle files that\n * simply have a list of hostnames to block, or it can handle a full blown hosts file.\n * It will strip out comments, references to the base IP address and just extract the\n * domains to be used\n *\n * @param context the context needed to read the file\n *\/\n private void loadHostsFile(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n String line;\n while ((line = reader.readLine()) != null) {\n if (!line.isEmpty() && !line.startsWith(COMMENT)) {\n line = line.replace(LOCAL_IP_V4, EMPTY)\n .replace(LOCAL_IP_V4_ALT, EMPTY)\n .replace(LOCAL_IP_V6, EMPTY)\n .replace(TAB, EMPTY);\n int comment = line.indexOf(COMMENT);\n if (comment >= 0) {\n line = line.substring(0, comment);\n }\n line = line.trim();\n if (!line.isEmpty() && !line.equals(LOCALHOST)) {\n while (line.contains(SPACE)) {\n int space = line.indexOf(SPACE);\n String host = line.substring(0, space);\n mBlockedDomainsList.add(host.trim());\n line = line.substring(space, line.length()).trim();\n }\n mBlockedDomainsList.add(line.trim());\n }\n }\n }\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage acr.browser.lightning.utils;\n\nimport android.content.Context;\nimport android.content.res.AssetManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.util.Log;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.inject.Inject;\nimport javax.inject.Singleton;\n\nimport acr.browser.lightning.app.BrowserApp;\nimport acr.browser.lightning.constant.Constants;\nimport acr.browser.lightning.preference.PreferenceManager;\n\n@Singleton\npublic class AdBlock {\n\n private static final String TAG = \"AdBlock\";\n private static final String BLOCKED_DOMAINS_LIST_FILE_NAME = \"hosts.txt\";\n private static final String LOCAL_IP_V4 = \"127.0.0.1\";\n private static final String LOCAL_IP_V4_ALT = \"0.0.0.0\";\n private static final String LOCAL_IP_V6 = \"::1\";\n private static final String LOCALHOST = \"localhost\";\n private static final String COMMENT = \"#\";\n private static final String TAB = \"\\t\";\n private static final String SPACE = \" \";\n private static final String EMPTY = \"\";\n private final Set mBlockedDomainsList = new HashSet<>();\n private boolean mBlockAds;\n\n @Inject PreferenceManager mPreferenceManager;\n\n @Inject\n public AdBlock(@NonNull Context context) {\n BrowserApp.getAppComponent().inject(this);\n if (mBlockedDomainsList.isEmpty() && Constants.FULL_VERSION) {\n loadHostsFile(context);\n }\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n public void updatePreference() {\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n private void loadBlockedDomainsList(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n String line;\n while ((line = reader.readLine()) != null) {\n mBlockedDomainsList.add(line.trim());\n }\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n\n \/**\n * a method that determines if the given URL is an ad or not. It performs\n * a search of the URL's domain on the blocked domain hash set.\n *\n * @param url the URL to check for being an ad\n * @return true if it is an ad, false if it is not an ad\n *\/\n public boolean isAd(@Nullable String url) {\n if (!mBlockAds || url == null) {\n return false;\n }\n\n String domain;\n try {\n domain = getDomainName(url);\n } catch (URISyntaxException e) {\n Log.d(TAG, \"URL '\" + url + \"' is invalid\", e);\n return false;\n }\n\n boolean isOnBlacklist = mBlockedDomainsList.contains(domain);\n if (isOnBlacklist) {\n Log.d(TAG, \"URL '\" + url + \"' is an ad\");\n }\n return isOnBlacklist;\n }\n\n \/**\n * Returns the probable domain name for a given URL\n *\n * @param url the url to parse\n * @return returns the domain\n * @throws URISyntaxException throws an exception if the string cannot form a URI\n *\/\n @NonNull\n private static String getDomainName(@NonNull String url) throws URISyntaxException {\n int index = url.indexOf('\/', 8);\n if (index != -1) {\n url = url.substring(0, index);\n }\n\n URI uri = new URI(url);\n String domain = uri.getHost();\n if (domain == null) {\n return url;\n }\n\n return domain.startsWith(\"www.\") ? domain.substring(4) : domain;\n }\n\n \/**\n * This method reads through a hosts file and extracts the domains that should\n * be redirected to localhost (a.k.a. IP address 127.0.0.1). It can handle files that\n * simply have a list of hostnames to block, or it can handle a full blown hosts file.\n * It will strip out comments, references to the base IP address and just extract the\n * domains to be used\n *\n * @param context the context needed to read the file\n *\/\n private void loadHostsFile(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n String line;\n while ((line = reader.readLine()) != null) {\n if (!line.isEmpty() && !line.startsWith(COMMENT)) {\n line = line.replace(LOCAL_IP_V4, EMPTY)\n .replace(LOCAL_IP_V4_ALT, EMPTY)\n .replace(LOCAL_IP_V6, EMPTY)\n .replace(TAB, EMPTY);\n int comment = line.indexOf(COMMENT);\n if (comment >= 0) {\n line = line.substring(0, comment);\n }\n line = line.trim();\n if (!line.isEmpty() && !line.equals(LOCALHOST)) {\n while (line.contains(SPACE)) {\n int space = line.indexOf(SPACE);\n String host = line.substring(0, space);\n mBlockedDomainsList.add(host.trim());\n line = line.substring(space, line.length()).trim();\n }\n mBlockedDomainsList.add(line.trim());\n }\n }\n }\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n}\n\n\nCode-B:\npackage acr.browser.lightning.utils;\n\nimport android.content.Context;\nimport android.content.res.AssetManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.util.Log;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.inject.Inject;\nimport javax.inject.Singleton;\n\nimport acr.browser.lightning.app.BrowserApp;\nimport acr.browser.lightning.constant.Constants;\nimport acr.browser.lightning.preference.PreferenceManager;\n\n@Singleton\npublic class AdBlock {\n\n private static final String TAG = \"AdBlock\";\n private static final String BLOCKED_DOMAINS_LIST_FILE_NAME = \"hosts.txt\";\n private static final String LOCAL_IP_V4 = \"127.0.0.1\";\n private static final String LOCAL_IP_V4_ALT = \"0.0.0.0\";\n private static final String LOCAL_IP_V6 = \"::1\";\n private static final String LOCALHOST = \"localhost\";\n private static final String COMMENT = \"#\";\n private static final String TAB = \"\\t\";\n private static final String SPACE = \" \";\n private static final String EMPTY = \"\";\n private final Set mBlockedDomainsList = new HashSet<>();\n private boolean mBlockAds;\n\n @Inject PreferenceManager mPreferenceManager;\n\n @Inject\n public AdBlock(@NonNull Context context) {\n BrowserApp.getAppComponent().inject(this);\n if (mBlockedDomainsList.isEmpty() && Constants.FULL_VERSION) {\n loadHostsFile(context);\n }\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n public void updatePreference() {\n mBlockAds = mPreferenceManager.getAdBlockEnabled();\n }\n\n private void loadBlockedDomainsList(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n String line;\n while ((line = reader.readLine()) != null) {\n mBlockedDomainsList.add(line.trim());\n }\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n\n \/**\n * a method that determines if the given URL is an ad or not. It performs\n * a search of the URL's domain on the blocked domain hash set.\n *\n * @param url the URL to check for being an ad\n * @return true if it is an ad, false if it is not an ad\n *\/\n public boolean isAd(@Nullable String url) {\n if (!mBlockAds || url == null) {\n return false;\n }\n\n String domain;\n try {\n domain = getDomainName(url);\n } catch (URISyntaxException e) {\n Log.d(TAG, \"URL '\" + url + \"' is invalid\", e);\n return false;\n }\n\n boolean isOnBlacklist = mBlockedDomainsList.contains(domain);\n if (isOnBlacklist) {\n Log.d(TAG, \"URL '\" + url + \"' is an ad\");\n }\n return isOnBlacklist;\n }\n\n \/**\n * Returns the probable domain name for a given URL\n *\n * @param url the url to parse\n * @return returns the domain\n * @throws URISyntaxException throws an exception if the string cannot form a URI\n *\/\n @NonNull\n private static String getDomainName(@NonNull String url) throws URISyntaxException {\n int index = url.indexOf('\/', 8);\n if (index != -1) {\n url = url.substring(0, index);\n }\n\n URI uri = new URI(url);\n String domain = uri.getHost();\n if (domain == null) {\n return url;\n }\n\n return domain.startsWith(\"www.\") ? domain.substring(4) : domain;\n }\n\n \/**\n * This method reads through a hosts file and extracts the domains that should\n * be redirected to localhost (a.k.a. IP address 127.0.0.1). It can handle files that\n * simply have a list of hostnames to block, or it can handle a full blown hosts file.\n * It will strip out comments, references to the base IP address and just extract the\n * domains to be used\n *\n * @param context the context needed to read the file\n *\/\n private void loadHostsFile(@NonNull final Context context) {\n BrowserApp.getIOThread().execute(new Runnable() {\n\n @Override\n public void run() {\n AssetManager asset = context.getAssets();\n BufferedReader reader = null;\n try {\n \/\/noinspection IOResourceOpenedButNotSafelyClosed\n reader = new BufferedReader(new InputStreamReader(\n asset.open(BLOCKED_DOMAINS_LIST_FILE_NAME)));\n StringBuilder lineBuilder = new StringBuilder();\n String line;\n long time = System.currentTimeMillis();\n \/\/ TODO: 4\/23\/17 Improve performance by reading in on IO thread and then processing on worker thread\n while ((line = reader.readLine()) != null) {\n lineBuilder.append(line);\n\n if (!isEmpty(lineBuilder) && !startsWith(lineBuilder, COMMENT)) {\n replace(lineBuilder, LOCAL_IP_V4, EMPTY);\n replace(lineBuilder, LOCAL_IP_V4_ALT, EMPTY);\n replace(lineBuilder, LOCAL_IP_V6, EMPTY);\n replace(lineBuilder, TAB, EMPTY);\n\n int comment = lineBuilder.indexOf(COMMENT);\n if (comment >= 0) {\n lineBuilder.replace(comment, lineBuilder.length(), EMPTY);\n }\n\n trim(lineBuilder);\n\n if (!isEmpty(lineBuilder) && !AdBlock.equals(lineBuilder, LOCALHOST)) {\n while (contains(lineBuilder, SPACE)) {\n int space = lineBuilder.indexOf(SPACE);\n String host = lineBuilder.substring(0, space);\n replace(lineBuilder, host, EMPTY);\n mBlockedDomainsList.add(host.trim());\n }\n if (lineBuilder.length() > 0) {\n mBlockedDomainsList.add(lineBuilder.toString());\n }\n }\n }\n lineBuilder.setLength(0);\n }\n Log.d(TAG, \"Loaded ad list in: \" + (System.currentTimeMillis() - time) + \" ms\");\n } catch (IOException e) {\n Log.wtf(TAG, \"Reading blocked domains list from file '\"\n + BLOCKED_DOMAINS_LIST_FILE_NAME + \"' failed.\", e);\n } finally {\n Utils.close(reader);\n }\n }\n });\n }\n\n \/\/ TODO: 4\/23\/17 Move all these methods to a StringUtils class\n private static void replace(@NonNull StringBuilder stringBuilder,\n @NonNull String toReplace,\n @NonNull String replacement) {\n int index = stringBuilder.indexOf(toReplace);\n if (index >= 0) {\n stringBuilder.replace(index, index + toReplace.length(), replacement);\n }\n }\n\n private static void trim(@NonNull StringBuilder stringBuilder) {\n while (stringBuilder.indexOf(SPACE) == 0) {\n stringBuilder.replace(0, 1, EMPTY);\n }\n\n while (stringBuilder.lastIndexOf(SPACE) == (stringBuilder.length() - 1)) {\n stringBuilder.replace(stringBuilder.length() - 1, stringBuilder.length(), EMPTY);\n }\n }\n\n private static boolean isEmpty(@NonNull StringBuilder stringBuilder) {\n return stringBuilder.length() == 0;\n }\n\n private static boolean startsWith(@NonNull StringBuilder stringBuilder, @NonNull String start) {\n return stringBuilder.indexOf(start) == 0;\n }\n\n private static boolean contains(@NonNull StringBuilder stringBuilder, @NonNull String contains) {\n return stringBuilder.indexOf(contains) >= 0;\n }\n\n private static boolean equals(@NonNull StringBuilder stringBuilder, @NonNull String equal) {\n int index = stringBuilder.indexOf(equal);\n return index >= 0 && stringBuilder.length() == equal.length();\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/erikusaj\/fdroidTvClient\/commit\/fc9459d6c5b48423a726e37be5caf93e3a75bae8","commit_message":"'\\\\\"send Downloader progress on a 100 ms timer\\\\n\\\\nNo need to flood receivers with progress events since they are basically\\\\nalways going to the UI","source_code":"package org.fdroid.fdroid.net;\n\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n\n private volatile boolean cancelled = false;\n\n private final OutputStream outputStream;\n\n public final File outputFile;\n\n protected final URL sourceUrl;\n protected String cacheTag;\n\n \/**\n * This is meant only to send progress to {@link DownloaderService}. This\n * also keeps this class pure Java so that it can be tested on the JVM,\n * without requiring an Android device or emulator.\n *\/\n interface DownloaderProgressListener {\n void sendProgress(URL sourceUrl, int bytesRead, int totalBytes);\n }\n\n private DownloaderProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(URL url, File destFile)\n throws FileNotFoundException, MalformedURLException {\n this.sourceUrl = url;\n outputFile = destFile;\n outputStream = new FileOutputStream(outputFile);\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(DownloaderProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n protected boolean wantToCheckCache() {\n return cacheTag != null;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract int totalDownloadSize();\n\n public abstract void download() throws IOException, InterruptedException;\n\n public abstract boolean isCached();\n\n protected void downloadFromStream(int bufferSize) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize) throws IOException, InterruptedException {\n\n int bytesRead = 0;\n int totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n sendProgress(bytesRead, totalBytes);\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n\n bytesRead += count;\n sendProgress(bytesRead, totalBytes);\n outputStream.write(buffer, 0, count);\n\n }\n outputStream.flush();\n outputStream.close();\n }\n\n private void sendProgress(int bytesRead, int totalBytes) {\n if (downloaderProgressListener != null) {\n downloaderProgressListener.sendProgress(sourceUrl, bytesRead, totalBytes);\n }\n }\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n","target_code":"package org.fdroid.fdroid.net;\n\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n\n private volatile boolean cancelled = false;\n private volatile int bytesRead;\n private volatile int totalBytes;\n private Timer timer;\n\n private final OutputStream outputStream;\n\n public final File outputFile;\n\n protected final URL sourceUrl;\n protected String cacheTag;\n\n \/**\n * This is meant only to send progress to {@link DownloaderService}. This\n * also keeps this class pure Java so that it can be tested on the JVM,\n * without requiring an Android device or emulator.\n *\/\n interface DownloaderProgressListener {\n void sendProgress(URL sourceUrl, int bytesRead, int totalBytes);\n }\n\n \/**\n * For sending download progress, should only be called in {@link #progressTask}\n *\/\n private DownloaderProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(URL url, File destFile)\n throws FileNotFoundException, MalformedURLException {\n this.sourceUrl = url;\n outputFile = destFile;\n outputStream = new FileOutputStream(outputFile);\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(DownloaderProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n protected boolean wantToCheckCache() {\n return cacheTag != null;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract int totalDownloadSize();\n\n public abstract void download() throws IOException, InterruptedException;\n\n public abstract boolean isCached();\n\n protected void downloadFromStream(int bufferSize) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n if (timer != null) {\n timer.cancel();\n }\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize) throws IOException, InterruptedException {\n bytesRead = 0;\n totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n timer = new Timer();\n timer.scheduleAtFixedRate(progressTask, 0, 100);\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n\n bytesRead += count;\n outputStream.write(buffer, 0, count);\n }\n timer.cancel();\n timer.purge();\n outputStream.flush();\n outputStream.close();\n }\n\n \/**\n * Send progress updates on a timer to avoid flooding receivers with pointless events.\n *\/\n private final TimerTask progressTask = new TimerTask() {\n @Override\n public void run() {\n if (downloaderProgressListener != null) {\n downloaderProgressListener.sendProgress(sourceUrl, bytesRead, totalBytes);\n }\n }\n };\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid.net;\n\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n\n private volatile boolean cancelled = false;\n\n private final OutputStream outputStream;\n\n public final File outputFile;\n\n protected final URL sourceUrl;\n protected String cacheTag;\n\n \/**\n * This is meant only to send progress to {@link DownloaderService}. This\n * also keeps this class pure Java so that it can be tested on the JVM,\n * without requiring an Android device or emulator.\n *\/\n interface DownloaderProgressListener {\n void sendProgress(URL sourceUrl, int bytesRead, int totalBytes);\n }\n\n private DownloaderProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(URL url, File destFile)\n throws FileNotFoundException, MalformedURLException {\n this.sourceUrl = url;\n outputFile = destFile;\n outputStream = new FileOutputStream(outputFile);\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(DownloaderProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n protected boolean wantToCheckCache() {\n return cacheTag != null;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract int totalDownloadSize();\n\n public abstract void download() throws IOException, InterruptedException;\n\n public abstract boolean isCached();\n\n protected void downloadFromStream(int bufferSize) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize) throws IOException, InterruptedException {\n\n int bytesRead = 0;\n int totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n sendProgress(bytesRead, totalBytes);\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n\n bytesRead += count;\n sendProgress(bytesRead, totalBytes);\n outputStream.write(buffer, 0, count);\n\n }\n outputStream.flush();\n outputStream.close();\n }\n\n private void sendProgress(int bytesRead, int totalBytes) {\n if (downloaderProgressListener != null) {\n downloaderProgressListener.sendProgress(sourceUrl, bytesRead, totalBytes);\n }\n }\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid.net;\n\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n\n private volatile boolean cancelled = false;\n\n private final OutputStream outputStream;\n\n public final File outputFile;\n\n protected final URL sourceUrl;\n protected String cacheTag;\n\n \/**\n * This is meant only to send progress to {@link DownloaderService}. This\n * also keeps this class pure Java so that it can be tested on the JVM,\n * without requiring an Android device or emulator.\n *\/\n interface DownloaderProgressListener {\n void sendProgress(URL sourceUrl, int bytesRead, int totalBytes);\n }\n\n private DownloaderProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(URL url, File destFile)\n throws FileNotFoundException, MalformedURLException {\n this.sourceUrl = url;\n outputFile = destFile;\n outputStream = new FileOutputStream(outputFile);\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(DownloaderProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n protected boolean wantToCheckCache() {\n return cacheTag != null;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract int totalDownloadSize();\n\n public abstract void download() throws IOException, InterruptedException;\n\n public abstract boolean isCached();\n\n protected void downloadFromStream(int bufferSize) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize) throws IOException, InterruptedException {\n\n int bytesRead = 0;\n int totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n sendProgress(bytesRead, totalBytes);\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n\n bytesRead += count;\n sendProgress(bytesRead, totalBytes);\n outputStream.write(buffer, 0, count);\n\n }\n outputStream.flush();\n outputStream.close();\n }\n\n private void sendProgress(int bytesRead, int totalBytes) {\n if (downloaderProgressListener != null) {\n downloaderProgressListener.sendProgress(sourceUrl, bytesRead, totalBytes);\n }\n }\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid.net;\n\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n\n private volatile boolean cancelled = false;\n\n private final OutputStream outputStream;\n\n public final File outputFile;\n\n protected final URL sourceUrl;\n protected String cacheTag;\n\n \/**\n * This is meant only to send progress to {@link DownloaderService}. This\n * also keeps this class pure Java so that it can be tested on the JVM,\n * without requiring an Android device or emulator.\n *\/\n interface DownloaderProgressListener {\n void sendProgress(URL sourceUrl, int bytesRead, int totalBytes);\n }\n\n private DownloaderProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(URL url, File destFile)\n throws FileNotFoundException, MalformedURLException {\n this.sourceUrl = url;\n outputFile = destFile;\n outputStream = new FileOutputStream(outputFile);\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(DownloaderProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n protected boolean wantToCheckCache() {\n return cacheTag != null;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract int totalDownloadSize();\n\n public abstract void download() throws IOException, InterruptedException;\n\n public abstract boolean isCached();\n\n protected void downloadFromStream(int bufferSize) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize) throws IOException, InterruptedException {\n\n int bytesRead = 0;\n int totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n sendProgress(bytesRead, totalBytes);\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n\n bytesRead += count;\n sendProgress(bytesRead, totalBytes);\n outputStream.write(buffer, 0, count);\n\n }\n outputStream.flush();\n outputStream.close();\n }\n\n private void sendProgress(int bytesRead, int totalBytes) {\n if (downloaderProgressListener != null) {\n downloaderProgressListener.sendProgress(sourceUrl, bytesRead, totalBytes);\n }\n }\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the code to send Downloader progress on a 100 ms timer to improve performance of the android application. Write the entire code and no other text in the response.\n\n### Concepts:\n[+] java.util.Timer\n[+] java.util.Timer\n[in] throwExceptionIfInterrupted function\n[in] Downloader class\n[in] copyInputToOutputStream function\n[-] sendProgress(int bytesRead, int totalBytes) function\n[implement] TimerTask progressTask\n[hint] No need to flood receivers with progress events since they are basically always going to the UI, and the UI will only refresh every so often. If the refresh rate is 50Hz, then that's every 20ms. 100ms seems to make a smooth enough progress bar, and saves some CPU time. This becomes more important if there are multiple downloads happening in the background.\n\n### Given program:\n```java\npackage org.fdroid.fdroid.net;\n\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n\n private volatile boolean cancelled = false;\n\n private final OutputStream outputStream;\n\n public final File outputFile;\n\n protected final URL sourceUrl;\n protected String cacheTag;\n\n \/**\n * This is meant only to send progress to {@link DownloaderService}. This\n * also keeps this class pure Java so that it can be tested on the JVM,\n * without requiring an Android device or emulator.\n *\/\n interface DownloaderProgressListener {\n void sendProgress(URL sourceUrl, int bytesRead, int totalBytes);\n }\n\n private DownloaderProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(URL url, File destFile)\n throws FileNotFoundException, MalformedURLException {\n this.sourceUrl = url;\n outputFile = destFile;\n outputStream = new FileOutputStream(outputFile);\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(DownloaderProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n protected boolean wantToCheckCache() {\n return cacheTag != null;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract int totalDownloadSize();\n\n public abstract void download() throws IOException, InterruptedException;\n\n public abstract boolean isCached();\n\n protected void downloadFromStream(int bufferSize) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize) throws IOException, InterruptedException {\n\n int bytesRead = 0;\n int totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n sendProgress(bytesRead, totalBytes);\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n\n bytesRead += count;\n sendProgress(bytesRead, totalBytes);\n outputStream.write(buffer, 0, count);\n\n }\n outputStream.flush();\n outputStream.close();\n }\n\n private void sendProgress(int bytesRead, int totalBytes) {\n if (downloaderProgressListener != null) {\n downloaderProgressListener.sendProgress(sourceUrl, bytesRead, totalBytes);\n }\n }\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/*\nCopyright (c) 2012, Apps4Av Inc. (apps4av.com) \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\npackage com.ds.avare.shapes;\n\nimport java.util.LinkedList;\n\nimport com.ds.avare.place.Plan;\nimport com.ds.avare.position.Coordinate;\nimport com.ds.avare.position.Movement;\nimport com.ds.avare.position.Origin;\nimport com.ds.avare.position.Scale;\nimport com.sromku.polygon.Point;\nimport com.sromku.polygon.Polygon;\nimport com.sromku.polygon.Polygon.Builder;\n\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.Typeface;\n\n\/**\n * @author zkhan\n * @author plinel\n *\n *\/\npublic abstract class Shape {\n\n protected LinkedList mCoords;\n protected double mLonMin;\n protected double mLonMax;\n protected double mLatMin;\n protected double mLatMax;\n \n protected String mText;\n \n private Builder mPolyBuilder;\n private Polygon mPoly;\n \n \/**\n * \n *\/\n public Shape(String label) {\n mCoords = new LinkedList();\n mLonMin = 180;\n mLonMax = -180;\n mLatMin = 180;\n mLatMax = -180;\n mText = label;\n mPolyBuilder = Polygon.Builder(); \n }\n\n \/**\n * \n * @param coords\n *\/\n public void add(double lon, double lat, boolean issep) {\n \tadd(lon,lat,issep, 0);\n }\n \n public void add(double lon, double lat, boolean issep, int segment) {\n Coordinate c = new Coordinate(lon, lat);\n if(issep) {\n c.makeSeparate();\n }\n c.setSegment(segment);\n \n mCoords.add(c);\n mPolyBuilder.addVertex(new Point((float)lon, (float)lat));\n \n \/*\n * Calculate start points\n *\/\n if(lon < mLonMin) {\n mLonMin = lon;\n }\n if(lon >= mLonMax) {\n mLonMax = lon;\n }\n if(lat < mLatMin) {\n mLatMin = lat;\n }\n if(lat >= mLatMax) {\n mLatMax = lat;\n }\n }\n\n public void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack) {\n \tdrawShape(c, origin, scale,movement,paint,night, drawTrack, null);\n }\n \n \/**\n * This will draw the closed shape in canvas with given screen params\n * @param c\n * @param origin\n * @param scale\n * @param movement\n * @param paint\n *\/\n\tpublic void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack, Plan plan) {\n\n \/*\n * Do a tab on top of shape\n *\/\n \/*\n * Draw pivots at end of track\n *\/\n float width = paint.getStrokeWidth();\n int color = paint.getColor();\n \n \/\/ TrackShape type is used for a flight plan destination\n if (this instanceof TrackShape) {\n \n \/*\n * Draw background on track shapes, so draw twice\n *\/\n \tint cMax = getNumCoords();\n for(int coord = 0; coord < (cMax - 1); coord++) {\n float x1 = (float)origin.getOffsetX(mCoords.get(coord).getLongitude());\n float x2 = (float)origin.getOffsetX(mCoords.get(coord + 1).getLongitude());\n float y1 = (float)origin.getOffsetY(mCoords.get(coord).getLatitude());\n float y2 = (float)origin.getOffsetY(mCoords.get(coord + 1).getLatitude());;\n\n if(drawTrack) {\n\t paint.setStrokeWidth(width + 4);\n\t paint.setColor(night? Color.WHITE : Color.BLACK);\n\t c.drawLine(x1, y1, x2, y2, paint);\n\t paint.setStrokeWidth(width);\n\n\t if(null == plan) {\n\t \tpaint.setColor(color);\n\t } else {\n\t \tpaint.setColor(TrackShape.getLegColor(plan.findNextNotPassed(), mCoords.get(coord).getLeg()));\n\t }\n\n\t c.drawLine(x1, y1, x2, y2, paint);\n }\n\n\t\t\t\tif(mCoords.get(coord + 1).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x2, y2, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x2, y2, 8, paint);\n paint.setColor(color);\n }\n if(mCoords.get(coord).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x1, y1, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x1, y1, 8, paint);\n paint.setColor(color);\n }\n }\n } else {\n \/*\n * Draw the shape segment by segment\n *\/\n if(getNumCoords()>0) {\n float pts[] = new float[(getNumCoords()) * 4];\n int i = 0;\n int coord = 0;\n float x1 = (float) origin.getOffsetX(mCoords.get(coord).getLongitude());\n float y1 = (float) origin.getOffsetY(mCoords.get(coord).getLatitude());\n float x2;\n float y2;\n\n for (coord = 1; coord < getNumCoords(); coord++) {\n x2 = (float) origin.getOffsetX(mCoords.get(coord).getLongitude());\n y2 = (float) origin.getOffsetY(mCoords.get(coord).getLatitude());\n\n pts[i++] = x1;\n pts[i++] = y1;\n pts[i++] = x2;\n pts[i++] = y2;\n\n x1 = x2;\n y1 = y2;\n }\n c.drawLines(pts, paint);\n }\n }\n }\n \n \/**\n * \n * @return\n *\/\n public int getNumCoords() {\n return mCoords.size();\n }\n\n \/**\n * \n * @return\n *\/\n public double getLatitudeMinimum() {\n return mLatMin;\n }\n \n \/**\n * \n * @param lon\n * @param lat\n * @return\n *\/\n public String getTextIfTouched(double lon, double lat) {\n if(null == mPoly) {\n return null;\n }\n if(mPoly.contains(new Point((float)lon, (float)lat))) {\n return mText;\n }\n return null;\n }\n \n \/**\n * \n *\/\n public void makePolygon() {\n if(getNumCoords() > 2) {\n mPoly = mPolyBuilder.build();\n }\n } \n}\n\n\nCode-B:\n\/*\nCopyright (c) 2012, Apps4Av Inc. (apps4av.com) \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\npackage com.ds.avare.shapes;\n\nimport java.util.LinkedList;\n\nimport com.ds.avare.place.Plan;\nimport com.ds.avare.position.Coordinate;\nimport com.ds.avare.position.Movement;\nimport com.ds.avare.position.Origin;\nimport com.ds.avare.position.Scale;\nimport com.sromku.polygon.Point;\nimport com.sromku.polygon.Polygon;\nimport com.sromku.polygon.Polygon.Builder;\n\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.Typeface;\n\n\/**\n * @author zkhan\n *\n *\/\npublic abstract class Shape {\n\n protected LinkedList mCoords;\n protected double mLonMin;\n protected double mLonMax;\n protected double mLatMin;\n protected double mLatMax;\n \n protected String mText;\n \n private Builder mPolyBuilder;\n private Polygon mPoly;\n \n \/**\n * \n *\/\n public Shape(String label) {\n mCoords = new LinkedList();\n mLonMin = 180;\n mLonMax = -180;\n mLatMin = 180;\n mLatMax = -180;\n mText = label;\n mPolyBuilder = Polygon.Builder(); \n }\n\n \/**\n * \n * @param coords\n *\/\n public void add(double lon, double lat, boolean issep) {\n \tadd(lon,lat,issep, 0);\n }\n \n public void add(double lon, double lat, boolean issep, int segment) {\n Coordinate c = new Coordinate(lon, lat);\n if(issep) {\n c.makeSeparate();\n }\n c.setSegment(segment);\n \n mCoords.add(c);\n mPolyBuilder.addVertex(new Point((float)lon, (float)lat));\n \n \/*\n * Calculate start points\n *\/\n if(lon < mLonMin) {\n mLonMin = lon;\n }\n if(lon >= mLonMax) {\n mLonMax = lon;\n }\n if(lat < mLatMin) {\n mLatMin = lat;\n }\n if(lat >= mLatMax) {\n mLatMax = lat;\n }\n }\n\n public void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack) {\n \tdrawShape(c, origin, scale,movement,paint,night, drawTrack, null);\n }\n \n \/**\n * This will draw the closed shape in canvas with given screen params\n * @param c\n * @param origin\n * @param scale\n * @param movement\n * @param paint\n *\/\n\tpublic void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack, Plan plan) {\n\n \/*\n * Do a tab on top of shape\n *\/\n \/*\n * Draw pivots at end of track\n *\/\n float width = paint.getStrokeWidth();\n int color = paint.getColor();\n \n \/\/ TrackShape type is used for a flight plan destination\n if (this instanceof TrackShape) {\n \n \/*\n * Draw background on track shapes, so draw twice\n *\/\n \tint cMax = getNumCoords();\n for(int coord = 0; coord < (cMax - 1); coord++) {\n float x1 = (float)origin.getOffsetX(mCoords.get(coord).getLongitude());\n float x2 = (float)origin.getOffsetX(mCoords.get(coord + 1).getLongitude());\n float y1 = (float)origin.getOffsetY(mCoords.get(coord).getLatitude());\n float y2 = (float)origin.getOffsetY(mCoords.get(coord + 1).getLatitude());;\n\n if(drawTrack) {\n\t paint.setStrokeWidth(width + 4);\n\t paint.setColor(night? Color.WHITE : Color.BLACK);\n\t c.drawLine(x1, y1, x2, y2, paint);\n\t paint.setStrokeWidth(width);\n\n\t if(null == plan) {\n\t \tpaint.setColor(color);\n\t } else {\n\t \tpaint.setColor(TrackShape.getLegColor(plan.findNextNotPassed(), mCoords.get(coord).getLeg()));\n\t }\n\n\t c.drawLine(x1, y1, x2, y2, paint);\n }\n\n\t\t\t\tif(mCoords.get(coord + 1).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x2, y2, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x2, y2, 8, paint);\n paint.setColor(color);\n }\n if(mCoords.get(coord).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x1, y1, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x1, y1, 8, paint);\n paint.setColor(color);\n }\n }\n } else {\n \/*\n * Draw the shape segment by segment\n *\/\n for(int coord = 0; coord < (getNumCoords() - 1); coord++) {\n float x1 = (float)origin.getOffsetX(mCoords.get(coord).getLongitude());\n float x2 = (float)origin.getOffsetX(mCoords.get(coord + 1).getLongitude());\n float y1 = (float)origin.getOffsetY(mCoords.get(coord).getLatitude());\n float y2 = (float)origin.getOffsetY(mCoords.get(coord + 1).getLatitude());;\n c.drawLine(x1, y1, x2, y2, paint);\n }\n }\n }\n \n \/**\n * \n * @return\n *\/\n public int getNumCoords() {\n return mCoords.size();\n }\n\n \/**\n * \n * @return\n *\/\n public double getLatitudeMinimum() {\n return mLatMin;\n }\n \n \/**\n * \n * @param lon\n * @param lat\n * @return\n *\/\n public String getTextIfTouched(double lon, double lat) {\n if(null == mPoly) {\n return null;\n }\n if(mPoly.contains(new Point((float)lon, (float)lat))) {\n return mText;\n }\n return null;\n }\n \n \/**\n * \n *\/\n public void makePolygon() {\n if(getNumCoords() > 2) {\n mPoly = mPolyBuilder.build();\n }\n } \n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/*\nCopyright (c) 2012, Apps4Av Inc. (apps4av.com) \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\npackage com.ds.avare.shapes;\n\nimport java.util.LinkedList;\n\nimport com.ds.avare.place.Plan;\nimport com.ds.avare.position.Coordinate;\nimport com.ds.avare.position.Movement;\nimport com.ds.avare.position.Origin;\nimport com.ds.avare.position.Scale;\nimport com.sromku.polygon.Point;\nimport com.sromku.polygon.Polygon;\nimport com.sromku.polygon.Polygon.Builder;\n\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.Typeface;\n\n\/**\n * @author zkhan\n *\n *\/\npublic abstract class Shape {\n\n protected LinkedList mCoords;\n protected double mLonMin;\n protected double mLonMax;\n protected double mLatMin;\n protected double mLatMax;\n \n protected String mText;\n \n private Builder mPolyBuilder;\n private Polygon mPoly;\n \n \/**\n * \n *\/\n public Shape(String label) {\n mCoords = new LinkedList();\n mLonMin = 180;\n mLonMax = -180;\n mLatMin = 180;\n mLatMax = -180;\n mText = label;\n mPolyBuilder = Polygon.Builder(); \n }\n\n \/**\n * \n * @param coords\n *\/\n public void add(double lon, double lat, boolean issep) {\n \tadd(lon,lat,issep, 0);\n }\n \n public void add(double lon, double lat, boolean issep, int segment) {\n Coordinate c = new Coordinate(lon, lat);\n if(issep) {\n c.makeSeparate();\n }\n c.setSegment(segment);\n \n mCoords.add(c);\n mPolyBuilder.addVertex(new Point((float)lon, (float)lat));\n \n \/*\n * Calculate start points\n *\/\n if(lon < mLonMin) {\n mLonMin = lon;\n }\n if(lon >= mLonMax) {\n mLonMax = lon;\n }\n if(lat < mLatMin) {\n mLatMin = lat;\n }\n if(lat >= mLatMax) {\n mLatMax = lat;\n }\n }\n\n public void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack) {\n \tdrawShape(c, origin, scale,movement,paint,night, drawTrack, null);\n }\n \n \/**\n * This will draw the closed shape in canvas with given screen params\n * @param c\n * @param origin\n * @param scale\n * @param movement\n * @param paint\n *\/\n\tpublic void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack, Plan plan) {\n\n \/*\n * Do a tab on top of shape\n *\/\n \/*\n * Draw pivots at end of track\n *\/\n float width = paint.getStrokeWidth();\n int color = paint.getColor();\n \n \/\/ TrackShape type is used for a flight plan destination\n if (this instanceof TrackShape) {\n \n \/*\n * Draw background on track shapes, so draw twice\n *\/\n \tint cMax = getNumCoords();\n for(int coord = 0; coord < (cMax - 1); coord++) {\n float x1 = (float)origin.getOffsetX(mCoords.get(coord).getLongitude());\n float x2 = (float)origin.getOffsetX(mCoords.get(coord + 1).getLongitude());\n float y1 = (float)origin.getOffsetY(mCoords.get(coord).getLatitude());\n float y2 = (float)origin.getOffsetY(mCoords.get(coord + 1).getLatitude());;\n\n if(drawTrack) {\n\t paint.setStrokeWidth(width + 4);\n\t paint.setColor(night? Color.WHITE : Color.BLACK);\n\t c.drawLine(x1, y1, x2, y2, paint);\n\t paint.setStrokeWidth(width);\n\n\t if(null == plan) {\n\t \tpaint.setColor(color);\n\t } else {\n\t \tpaint.setColor(TrackShape.getLegColor(plan.findNextNotPassed(), mCoords.get(coord).getLeg()));\n\t }\n\n\t c.drawLine(x1, y1, x2, y2, paint);\n }\n\n\t\t\t\tif(mCoords.get(coord + 1).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x2, y2, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x2, y2, 8, paint);\n paint.setColor(color);\n }\n if(mCoords.get(coord).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x1, y1, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x1, y1, 8, paint);\n paint.setColor(color);\n }\n }\n } else {\n \/*\n * Draw the shape segment by segment\n *\/\n for(int coord = 0; coord < (getNumCoords() - 1); coord++) {\n float x1 = (float)origin.getOffsetX(mCoords.get(coord).getLongitude());\n float x2 = (float)origin.getOffsetX(mCoords.get(coord + 1).getLongitude());\n float y1 = (float)origin.getOffsetY(mCoords.get(coord).getLatitude());\n float y2 = (float)origin.getOffsetY(mCoords.get(coord + 1).getLatitude());;\n c.drawLine(x1, y1, x2, y2, paint);\n }\n }\n }\n \n \/**\n * \n * @return\n *\/\n public int getNumCoords() {\n return mCoords.size();\n }\n\n \/**\n * \n * @return\n *\/\n public double getLatitudeMinimum() {\n return mLatMin;\n }\n \n \/**\n * \n * @param lon\n * @param lat\n * @return\n *\/\n public String getTextIfTouched(double lon, double lat) {\n if(null == mPoly) {\n return null;\n }\n if(mPoly.contains(new Point((float)lon, (float)lat))) {\n return mText;\n }\n return null;\n }\n \n \/**\n * \n *\/\n public void makePolygon() {\n if(getNumCoords() > 2) {\n mPoly = mPolyBuilder.build();\n }\n } \n}\n\n\nCode-B:\n\/*\nCopyright (c) 2012, Apps4Av Inc. (apps4av.com) \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\npackage com.ds.avare.shapes;\n\nimport java.util.LinkedList;\n\nimport com.ds.avare.place.Plan;\nimport com.ds.avare.position.Coordinate;\nimport com.ds.avare.position.Movement;\nimport com.ds.avare.position.Origin;\nimport com.ds.avare.position.Scale;\nimport com.sromku.polygon.Point;\nimport com.sromku.polygon.Polygon;\nimport com.sromku.polygon.Polygon.Builder;\n\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.Typeface;\n\n\/**\n * @author zkhan\n * @author plinel\n *\n *\/\npublic abstract class Shape {\n\n protected LinkedList mCoords;\n protected double mLonMin;\n protected double mLonMax;\n protected double mLatMin;\n protected double mLatMax;\n \n protected String mText;\n \n private Builder mPolyBuilder;\n private Polygon mPoly;\n \n \/**\n * \n *\/\n public Shape(String label) {\n mCoords = new LinkedList();\n mLonMin = 180;\n mLonMax = -180;\n mLatMin = 180;\n mLatMax = -180;\n mText = label;\n mPolyBuilder = Polygon.Builder(); \n }\n\n \/**\n * \n * @param coords\n *\/\n public void add(double lon, double lat, boolean issep) {\n \tadd(lon,lat,issep, 0);\n }\n \n public void add(double lon, double lat, boolean issep, int segment) {\n Coordinate c = new Coordinate(lon, lat);\n if(issep) {\n c.makeSeparate();\n }\n c.setSegment(segment);\n \n mCoords.add(c);\n mPolyBuilder.addVertex(new Point((float)lon, (float)lat));\n \n \/*\n * Calculate start points\n *\/\n if(lon < mLonMin) {\n mLonMin = lon;\n }\n if(lon >= mLonMax) {\n mLonMax = lon;\n }\n if(lat < mLatMin) {\n mLatMin = lat;\n }\n if(lat >= mLatMax) {\n mLatMax = lat;\n }\n }\n\n public void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack) {\n \tdrawShape(c, origin, scale,movement,paint,night, drawTrack, null);\n }\n \n \/**\n * This will draw the closed shape in canvas with given screen params\n * @param c\n * @param origin\n * @param scale\n * @param movement\n * @param paint\n *\/\n\tpublic void drawShape(Canvas c, Origin origin, Scale scale, Movement movement, Paint paint, boolean night, boolean drawTrack, Plan plan) {\n\n \/*\n * Do a tab on top of shape\n *\/\n \/*\n * Draw pivots at end of track\n *\/\n float width = paint.getStrokeWidth();\n int color = paint.getColor();\n \n \/\/ TrackShape type is used for a flight plan destination\n if (this instanceof TrackShape) {\n \n \/*\n * Draw background on track shapes, so draw twice\n *\/\n \tint cMax = getNumCoords();\n for(int coord = 0; coord < (cMax - 1); coord++) {\n float x1 = (float)origin.getOffsetX(mCoords.get(coord).getLongitude());\n float x2 = (float)origin.getOffsetX(mCoords.get(coord + 1).getLongitude());\n float y1 = (float)origin.getOffsetY(mCoords.get(coord).getLatitude());\n float y2 = (float)origin.getOffsetY(mCoords.get(coord + 1).getLatitude());;\n\n if(drawTrack) {\n\t paint.setStrokeWidth(width + 4);\n\t paint.setColor(night? Color.WHITE : Color.BLACK);\n\t c.drawLine(x1, y1, x2, y2, paint);\n\t paint.setStrokeWidth(width);\n\n\t if(null == plan) {\n\t \tpaint.setColor(color);\n\t } else {\n\t \tpaint.setColor(TrackShape.getLegColor(plan.findNextNotPassed(), mCoords.get(coord).getLeg()));\n\t }\n\n\t c.drawLine(x1, y1, x2, y2, paint);\n }\n\n\t\t\t\tif(mCoords.get(coord + 1).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x2, y2, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x2, y2, 8, paint);\n paint.setColor(color);\n }\n if(mCoords.get(coord).isSeparate()) {\n paint.setColor(night? Color.WHITE : Color.BLACK);\n c.drawCircle(x1, y1, 10, paint);\n paint.setColor(Color.GREEN);\n c.drawCircle(x1, y1, 8, paint);\n paint.setColor(color);\n }\n }\n } else {\n \/*\n * Draw the shape segment by segment\n *\/\n if(getNumCoords()>0) {\n float pts[] = new float[(getNumCoords()) * 4];\n int i = 0;\n int coord = 0;\n float x1 = (float) origin.getOffsetX(mCoords.get(coord).getLongitude());\n float y1 = (float) origin.getOffsetY(mCoords.get(coord).getLatitude());\n float x2;\n float y2;\n\n for (coord = 1; coord < getNumCoords(); coord++) {\n x2 = (float) origin.getOffsetX(mCoords.get(coord).getLongitude());\n y2 = (float) origin.getOffsetY(mCoords.get(coord).getLatitude());\n\n pts[i++] = x1;\n pts[i++] = y1;\n pts[i++] = x2;\n pts[i++] = y2;\n\n x1 = x2;\n y1 = y2;\n }\n c.drawLines(pts, paint);\n }\n }\n }\n \n \/**\n * \n * @return\n *\/\n public int getNumCoords() {\n return mCoords.size();\n }\n\n \/**\n * \n * @return\n *\/\n public double getLatitudeMinimum() {\n return mLatMin;\n }\n \n \/**\n * \n * @param lon\n * @param lat\n * @return\n *\/\n public String getTextIfTouched(double lon, double lat) {\n if(null == mPoly) {\n return null;\n }\n if(mPoly.contains(new Point((float)lon, (float)lat))) {\n return mText;\n }\n return null;\n }\n \n \/**\n * \n *\/\n public void makePolygon() {\n if(getNumCoords() > 2) {\n mPoly = mPolyBuilder.build();\n }\n } \n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/alpenf\/fdroid-alpha\/commit\/6c9afd823e8da9393a167a89345301782ef3483b","commit_message":"'\\\\\"speed up repo searchs by using \\\\\"depth last\\\\\"\\\\n\\\\nRecursively search for index-v1.jar starting from the given directory","source_code":"\/*\n * Copyright (C) 2018 Hans-Christoph Steiner \n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.nearby;\n\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.app.IntentService;\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Process;\nimport android.support.v4.provider.DocumentFile;\nimport android.util.Log;\nimport android.widget.Toast;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.IOUtils;\nimport org.fdroid.fdroid.AddRepoIntentService;\nimport org.fdroid.fdroid.IndexUpdater;\nimport org.fdroid.fdroid.IndexV1Updater;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Repo;\nimport org.fdroid.fdroid.data.RepoProvider;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.security.cert.Certificate;\nimport java.util.jar.JarEntry;\nimport java.util.jar.JarFile;\nimport java.util.jar.JarInputStream;\n\n\/**\n * An {@link IntentService} subclass for handling asynchronous scanning of a\n * removable storage device like an SD Card or USB OTG thumb drive using the\n * Storage Access Framework. Permission must first be granted by the user\n * {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} or\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)}request,\n * then F-Droid will have permanent access to that{@link Uri}.\n *

\n * Even though the Storage Access Framework was introduced in\n * {@link android.os.Build.VERSION_CODES#KITKAT android-19}, this approach is only\n * workable if {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} is available.\n * It was added in {@link android.os.Build.VERSION_CODES#LOLLIPOP android-21}.\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)} is also\n * necessary to do this with any kind of rational UX.\n *\n * @see The Storage Situation: Removable Storage <\/a>\n * @see Be Careful with Scoped Directory Access<\/a>\n * @see Using Scoped Directory Access<\/a>\n * @see Open Files using Storage Access Framework<\/a>\n *\/\n@TargetApi(21)\npublic class TreeUriScannerIntentService extends IntentService {\n public static final String TAG = \"TreeUriScannerIntentSer\";\n\n private static final String ACTION_SCAN_TREE_URI = \"org.fdroid.fdroid.nearby.action.SCAN_TREE_URI\";\n\n public TreeUriScannerIntentService() {\n super(\"TreeUriScannerIntentService\");\n }\n\n public static void scan(Context context, Uri data) {\n if (Preferences.get().isScanRemovableStorageEnabled()) {\n Intent intent = new Intent(context, TreeUriScannerIntentService.class);\n intent.setAction(ACTION_SCAN_TREE_URI);\n intent.setData(data);\n context.startService(intent);\n }\n }\n\n \/**\n * Now determine if it is External Storage that must be handled by the\n * {@link TreeUriScannerIntentService} or whether it is External Storage\n * like an SD Card that can be directly accessed via the file system.\n *\/\n public static void onActivityResult(Activity activity, Intent intent) {\n Uri uri = intent.getData();\n if (uri != null) {\n if (Build.VERSION.SDK_INT >= 19) {\n ContentResolver contentResolver = activity.getContentResolver();\n int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;\n contentResolver.takePersistableUriPermission(uri, perms);\n }\n String msg = String.format(activity.getString(R.string.swap_toast_using_path), uri.toString());\n Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();\n scan(activity, uri);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n if (intent == null || !ACTION_SCAN_TREE_URI.equals(intent.getAction())) {\n return;\n }\n Uri treeUri = intent.getData();\n if (treeUri == null) {\n return;\n }\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n DocumentFile treeFile = DocumentFile.fromTreeUri(this, treeUri);\n searchDirectory(treeFile);\n }\n\n private void searchDirectory(DocumentFile documentFileDir) {\n DocumentFile[] documentFiles = documentFileDir.listFiles();\n if (documentFiles == null) {\n return;\n }\n for (DocumentFile documentFile : documentFiles) {\n if (documentFile.isDirectory()) {\n searchDirectory(documentFile);\n } else {\n if (IndexV1Updater.SIGNED_FILE_NAME.equals(documentFile.getName())) {\n registerRepo(documentFile);\n }\n }\n }\n }\n\n \/**\n * For all files called {@link IndexV1Updater#SIGNED_FILE_NAME} found, check\n * the JAR signature and read the fingerprint of the signing certificate.\n * The fingerprint is then used to find whether this local repo is a mirror\n * of an existing repo, or a totally new repo. In order to verify the\n * signatures in the JAR, the whole file needs to be read in first.\n *\n * @see JarInputStream#JarInputStream(InputStream, boolean)\n *\/\n private void registerRepo(DocumentFile index) {\n InputStream inputStream = null;\n try {\n inputStream = getContentResolver().openInputStream(index.getUri());\n registerRepo(this, inputStream, index.getParentFile().getUri());\n } catch (IOException | IndexUpdater.SigningException e) {\n e.printStackTrace();\n } finally {\n Utils.closeQuietly(inputStream);\n }\n }\n\n public static void registerRepo(Context context, InputStream inputStream, Uri repoUri)\n throws IOException, IndexUpdater.SigningException {\n if (inputStream == null) {\n return;\n }\n File destFile = File.createTempFile(\"dl-\", IndexV1Updater.SIGNED_FILE_NAME, context.getCacheDir());\n FileUtils.copyInputStreamToFile(inputStream, destFile);\n JarFile jarFile = new JarFile(destFile, true);\n JarEntry indexEntry = (JarEntry) jarFile.getEntry(IndexV1Updater.DATA_FILE_NAME);\n IOUtils.readLines(jarFile.getInputStream(indexEntry));\n Certificate certificate = IndexUpdater.getSigningCertFromJar(indexEntry);\n String fingerprint = Utils.calcFingerprint(certificate);\n Log.i(TAG, \"Got fingerprint: \" + fingerprint);\n destFile.delete();\n\n Log.i(TAG, \"Found a valid, signed index-v1.json\");\n for (Repo repo : RepoProvider.Helper.all(context)) {\n if (fingerprint.equals(repo.fingerprint)) {\n Log.i(TAG, repo.address + \" has the SAME fingerprint: \" + fingerprint);\n } else {\n Log.i(TAG, repo.address + \" different fingerprint\");\n }\n }\n\n AddRepoIntentService.addRepo(context, repoUri, fingerprint);\n \/\/ TODO rework IndexUpdater.getSigningCertFromJar to work for here\n }\n}\n","target_code":"\/*\n * Copyright (C) 2018 Hans-Christoph Steiner \n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.nearby;\n\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.app.IntentService;\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Process;\nimport android.support.v4.provider.DocumentFile;\nimport android.util.Log;\nimport android.widget.Toast;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.IOUtils;\nimport org.fdroid.fdroid.AddRepoIntentService;\nimport org.fdroid.fdroid.IndexUpdater;\nimport org.fdroid.fdroid.IndexV1Updater;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Repo;\nimport org.fdroid.fdroid.data.RepoProvider;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.security.cert.Certificate;\nimport java.util.ArrayList;\nimport java.util.jar.JarEntry;\nimport java.util.jar.JarFile;\nimport java.util.jar.JarInputStream;\n\n\/**\n * An {@link IntentService} subclass for handling asynchronous scanning of a\n * removable storage device like an SD Card or USB OTG thumb drive using the\n * Storage Access Framework. Permission must first be granted by the user\n * {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} or\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)}request,\n * then F-Droid will have permanent access to that{@link Uri}.\n *

\n * Even though the Storage Access Framework was introduced in\n * {@link android.os.Build.VERSION_CODES#KITKAT android-19}, this approach is only\n * workable if {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} is available.\n * It was added in {@link android.os.Build.VERSION_CODES#LOLLIPOP android-21}.\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)} is also\n * necessary to do this with any kind of rational UX.\n *\n * @see The Storage Situation: Removable Storage <\/a>\n * @see Be Careful with Scoped Directory Access<\/a>\n * @see Using Scoped Directory Access<\/a>\n * @see Open Files using Storage Access Framework<\/a>\n *\/\n@TargetApi(21)\npublic class TreeUriScannerIntentService extends IntentService {\n public static final String TAG = \"TreeUriScannerIntentSer\";\n\n private static final String ACTION_SCAN_TREE_URI = \"org.fdroid.fdroid.nearby.action.SCAN_TREE_URI\";\n\n public TreeUriScannerIntentService() {\n super(\"TreeUriScannerIntentService\");\n }\n\n public static void scan(Context context, Uri data) {\n if (Preferences.get().isScanRemovableStorageEnabled()) {\n Intent intent = new Intent(context, TreeUriScannerIntentService.class);\n intent.setAction(ACTION_SCAN_TREE_URI);\n intent.setData(data);\n context.startService(intent);\n }\n }\n\n \/**\n * Now determine if it is External Storage that must be handled by the\n * {@link TreeUriScannerIntentService} or whether it is External Storage\n * like an SD Card that can be directly accessed via the file system.\n *\/\n public static void onActivityResult(Activity activity, Intent intent) {\n Uri uri = intent.getData();\n if (uri != null) {\n if (Build.VERSION.SDK_INT >= 19) {\n ContentResolver contentResolver = activity.getContentResolver();\n int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;\n contentResolver.takePersistableUriPermission(uri, perms);\n }\n String msg = String.format(activity.getString(R.string.swap_toast_using_path), uri.toString());\n Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();\n scan(activity, uri);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n if (intent == null || !ACTION_SCAN_TREE_URI.equals(intent.getAction())) {\n return;\n }\n Uri treeUri = intent.getData();\n if (treeUri == null) {\n return;\n }\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n DocumentFile treeFile = DocumentFile.fromTreeUri(this, treeUri);\n searchDirectory(treeFile);\n }\n\n \/**\n * Recursively search for {@link IndexV1Updater#SIGNED_FILE_NAME} starting\n * from the given directory, looking at files first before recursing into\n * directories. This is \"depth last\" since the index file is much more\n * likely to be shallow than deep, and there can be a lot of files to\n * search through starting at 4 or more levels deep, like the fdroid\n * icons dirs and the per-app \"external storage\" dirs.\n *\/\n private void searchDirectory(DocumentFile documentFileDir) {\n DocumentFile[] documentFiles = documentFileDir.listFiles();\n if (documentFiles == null) {\n return;\n }\n boolean foundIndex = false;\n ArrayList dirs = new ArrayList<>();\n for (DocumentFile documentFile : documentFiles) {\n if (documentFile.isDirectory()) {\n dirs.add(documentFile);\n } else if (!foundIndex) {\n if (IndexV1Updater.SIGNED_FILE_NAME.equals(documentFile.getName())) {\n registerRepo(documentFile);\n foundIndex = true;\n }\n }\n }\n for (DocumentFile dir : dirs) {\n searchDirectory(dir);\n }\n }\n\n \/**\n * For all files called {@link IndexV1Updater#SIGNED_FILE_NAME} found, check\n * the JAR signature and read the fingerprint of the signing certificate.\n * The fingerprint is then used to find whether this local repo is a mirror\n * of an existing repo, or a totally new repo. In order to verify the\n * signatures in the JAR, the whole file needs to be read in first.\n *\n * @see JarInputStream#JarInputStream(InputStream, boolean)\n *\/\n private void registerRepo(DocumentFile index) {\n InputStream inputStream = null;\n try {\n inputStream = getContentResolver().openInputStream(index.getUri());\n registerRepo(this, inputStream, index.getParentFile().getUri());\n } catch (IOException | IndexUpdater.SigningException e) {\n e.printStackTrace();\n } finally {\n Utils.closeQuietly(inputStream);\n }\n }\n\n public static void registerRepo(Context context, InputStream inputStream, Uri repoUri)\n throws IOException, IndexUpdater.SigningException {\n if (inputStream == null) {\n return;\n }\n File destFile = File.createTempFile(\"dl-\", IndexV1Updater.SIGNED_FILE_NAME, context.getCacheDir());\n FileUtils.copyInputStreamToFile(inputStream, destFile);\n JarFile jarFile = new JarFile(destFile, true);\n JarEntry indexEntry = (JarEntry) jarFile.getEntry(IndexV1Updater.DATA_FILE_NAME);\n IOUtils.readLines(jarFile.getInputStream(indexEntry));\n Certificate certificate = IndexUpdater.getSigningCertFromJar(indexEntry);\n String fingerprint = Utils.calcFingerprint(certificate);\n Log.i(TAG, \"Got fingerprint: \" + fingerprint);\n destFile.delete();\n\n Log.i(TAG, \"Found a valid, signed index-v1.json\");\n for (Repo repo : RepoProvider.Helper.all(context)) {\n if (fingerprint.equals(repo.fingerprint)) {\n Log.i(TAG, repo.address + \" has the SAME fingerprint: \" + fingerprint);\n } else {\n Log.i(TAG, repo.address + \" different fingerprint\");\n }\n }\n\n AddRepoIntentService.addRepo(context, repoUri, fingerprint);\n \/\/ TODO rework IndexUpdater.getSigningCertFromJar to work for here\n }\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright (C) 2018 Hans-Christoph Steiner \n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.nearby;\n\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.app.IntentService;\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Process;\nimport android.support.v4.provider.DocumentFile;\nimport android.util.Log;\nimport android.widget.Toast;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.IOUtils;\nimport org.fdroid.fdroid.AddRepoIntentService;\nimport org.fdroid.fdroid.IndexUpdater;\nimport org.fdroid.fdroid.IndexV1Updater;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Repo;\nimport org.fdroid.fdroid.data.RepoProvider;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.security.cert.Certificate;\nimport java.util.jar.JarEntry;\nimport java.util.jar.JarFile;\nimport java.util.jar.JarInputStream;\n\n\/**\n * An {@link IntentService} subclass for handling asynchronous scanning of a\n * removable storage device like an SD Card or USB OTG thumb drive using the\n * Storage Access Framework. Permission must first be granted by the user\n * {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} or\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)}request,\n * then F-Droid will have permanent access to that{@link Uri}.\n *

\n * Even though the Storage Access Framework was introduced in\n * {@link android.os.Build.VERSION_CODES#KITKAT android-19}, this approach is only\n * workable if {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} is available.\n * It was added in {@link android.os.Build.VERSION_CODES#LOLLIPOP android-21}.\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)} is also\n * necessary to do this with any kind of rational UX.\n *\n * @see The Storage Situation: Removable Storage <\/a>\n * @see Be Careful with Scoped Directory Access<\/a>\n * @see Using Scoped Directory Access<\/a>\n * @see Open Files using Storage Access Framework<\/a>\n *\/\n@TargetApi(21)\npublic class TreeUriScannerIntentService extends IntentService {\n public static final String TAG = \"TreeUriScannerIntentSer\";\n\n private static final String ACTION_SCAN_TREE_URI = \"org.fdroid.fdroid.nearby.action.SCAN_TREE_URI\";\n\n public TreeUriScannerIntentService() {\n super(\"TreeUriScannerIntentService\");\n }\n\n public static void scan(Context context, Uri data) {\n if (Preferences.get().isScanRemovableStorageEnabled()) {\n Intent intent = new Intent(context, TreeUriScannerIntentService.class);\n intent.setAction(ACTION_SCAN_TREE_URI);\n intent.setData(data);\n context.startService(intent);\n }\n }\n\n \/**\n * Now determine if it is External Storage that must be handled by the\n * {@link TreeUriScannerIntentService} or whether it is External Storage\n * like an SD Card that can be directly accessed via the file system.\n *\/\n public static void onActivityResult(Activity activity, Intent intent) {\n Uri uri = intent.getData();\n if (uri != null) {\n if (Build.VERSION.SDK_INT >= 19) {\n ContentResolver contentResolver = activity.getContentResolver();\n int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;\n contentResolver.takePersistableUriPermission(uri, perms);\n }\n String msg = String.format(activity.getString(R.string.swap_toast_using_path), uri.toString());\n Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();\n scan(activity, uri);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n if (intent == null || !ACTION_SCAN_TREE_URI.equals(intent.getAction())) {\n return;\n }\n Uri treeUri = intent.getData();\n if (treeUri == null) {\n return;\n }\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n DocumentFile treeFile = DocumentFile.fromTreeUri(this, treeUri);\n searchDirectory(treeFile);\n }\n\n private void searchDirectory(DocumentFile documentFileDir) {\n DocumentFile[] documentFiles = documentFileDir.listFiles();\n if (documentFiles == null) {\n return;\n }\n for (DocumentFile documentFile : documentFiles) {\n if (documentFile.isDirectory()) {\n searchDirectory(documentFile);\n } else {\n if (IndexV1Updater.SIGNED_FILE_NAME.equals(documentFile.getName())) {\n registerRepo(documentFile);\n }\n }\n }\n }\n\n \/**\n * For all files called {@link IndexV1Updater#SIGNED_FILE_NAME} found, check\n * the JAR signature and read the fingerprint of the signing certificate.\n * The fingerprint is then used to find whether this local repo is a mirror\n * of an existing repo, or a totally new repo. In order to verify the\n * signatures in the JAR, the whole file needs to be read in first.\n *\n * @see JarInputStream#JarInputStream(InputStream, boolean)\n *\/\n private void registerRepo(DocumentFile index) {\n InputStream inputStream = null;\n try {\n inputStream = getContentResolver().openInputStream(index.getUri());\n registerRepo(this, inputStream, index.getParentFile().getUri());\n } catch (IOException | IndexUpdater.SigningException e) {\n e.printStackTrace();\n } finally {\n Utils.closeQuietly(inputStream);\n }\n }\n\n public static void registerRepo(Context context, InputStream inputStream, Uri repoUri)\n throws IOException, IndexUpdater.SigningException {\n if (inputStream == null) {\n return;\n }\n File destFile = File.createTempFile(\"dl-\", IndexV1Updater.SIGNED_FILE_NAME, context.getCacheDir());\n FileUtils.copyInputStreamToFile(inputStream, destFile);\n JarFile jarFile = new JarFile(destFile, true);\n JarEntry indexEntry = (JarEntry) jarFile.getEntry(IndexV1Updater.DATA_FILE_NAME);\n IOUtils.readLines(jarFile.getInputStream(indexEntry));\n Certificate certificate = IndexUpdater.getSigningCertFromJar(indexEntry);\n String fingerprint = Utils.calcFingerprint(certificate);\n Log.i(TAG, \"Got fingerprint: \" + fingerprint);\n destFile.delete();\n\n Log.i(TAG, \"Found a valid, signed index-v1.json\");\n for (Repo repo : RepoProvider.Helper.all(context)) {\n if (fingerprint.equals(repo.fingerprint)) {\n Log.i(TAG, repo.address + \" has the SAME fingerprint: \" + fingerprint);\n } else {\n Log.i(TAG, repo.address + \" different fingerprint\");\n }\n }\n\n AddRepoIntentService.addRepo(context, repoUri, fingerprint);\n \/\/ TODO rework IndexUpdater.getSigningCertFromJar to work for here\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright (C) 2018 Hans-Christoph Steiner \n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.nearby;\n\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.app.IntentService;\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Process;\nimport android.support.v4.provider.DocumentFile;\nimport android.util.Log;\nimport android.widget.Toast;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.IOUtils;\nimport org.fdroid.fdroid.AddRepoIntentService;\nimport org.fdroid.fdroid.IndexUpdater;\nimport org.fdroid.fdroid.IndexV1Updater;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Repo;\nimport org.fdroid.fdroid.data.RepoProvider;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.security.cert.Certificate;\nimport java.util.jar.JarEntry;\nimport java.util.jar.JarFile;\nimport java.util.jar.JarInputStream;\n\n\/**\n * An {@link IntentService} subclass for handling asynchronous scanning of a\n * removable storage device like an SD Card or USB OTG thumb drive using the\n * Storage Access Framework. Permission must first be granted by the user\n * {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} or\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)}request,\n * then F-Droid will have permanent access to that{@link Uri}.\n *

\n * Even though the Storage Access Framework was introduced in\n * {@link android.os.Build.VERSION_CODES#KITKAT android-19}, this approach is only\n * workable if {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} is available.\n * It was added in {@link android.os.Build.VERSION_CODES#LOLLIPOP android-21}.\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)} is also\n * necessary to do this with any kind of rational UX.\n *\n * @see The Storage Situation: Removable Storage <\/a>\n * @see Be Careful with Scoped Directory Access<\/a>\n * @see Using Scoped Directory Access<\/a>\n * @see Open Files using Storage Access Framework<\/a>\n *\/\n@TargetApi(21)\npublic class TreeUriScannerIntentService extends IntentService {\n public static final String TAG = \"TreeUriScannerIntentSer\";\n\n private static final String ACTION_SCAN_TREE_URI = \"org.fdroid.fdroid.nearby.action.SCAN_TREE_URI\";\n\n public TreeUriScannerIntentService() {\n super(\"TreeUriScannerIntentService\");\n }\n\n public static void scan(Context context, Uri data) {\n if (Preferences.get().isScanRemovableStorageEnabled()) {\n Intent intent = new Intent(context, TreeUriScannerIntentService.class);\n intent.setAction(ACTION_SCAN_TREE_URI);\n intent.setData(data);\n context.startService(intent);\n }\n }\n\n \/**\n * Now determine if it is External Storage that must be handled by the\n * {@link TreeUriScannerIntentService} or whether it is External Storage\n * like an SD Card that can be directly accessed via the file system.\n *\/\n public static void onActivityResult(Activity activity, Intent intent) {\n Uri uri = intent.getData();\n if (uri != null) {\n if (Build.VERSION.SDK_INT >= 19) {\n ContentResolver contentResolver = activity.getContentResolver();\n int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;\n contentResolver.takePersistableUriPermission(uri, perms);\n }\n String msg = String.format(activity.getString(R.string.swap_toast_using_path), uri.toString());\n Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();\n scan(activity, uri);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n if (intent == null || !ACTION_SCAN_TREE_URI.equals(intent.getAction())) {\n return;\n }\n Uri treeUri = intent.getData();\n if (treeUri == null) {\n return;\n }\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n DocumentFile treeFile = DocumentFile.fromTreeUri(this, treeUri);\n searchDirectory(treeFile);\n }\n\n private void searchDirectory(DocumentFile documentFileDir) {\n DocumentFile[] documentFiles = documentFileDir.listFiles();\n if (documentFiles == null) {\n return;\n }\n for (DocumentFile documentFile : documentFiles) {\n if (documentFile.isDirectory()) {\n searchDirectory(documentFile);\n } else {\n if (IndexV1Updater.SIGNED_FILE_NAME.equals(documentFile.getName())) {\n registerRepo(documentFile);\n }\n }\n }\n }\n\n \/**\n * For all files called {@link IndexV1Updater#SIGNED_FILE_NAME} found, check\n * the JAR signature and read the fingerprint of the signing certificate.\n * The fingerprint is then used to find whether this local repo is a mirror\n * of an existing repo, or a totally new repo. In order to verify the\n * signatures in the JAR, the whole file needs to be read in first.\n *\n * @see JarInputStream#JarInputStream(InputStream, boolean)\n *\/\n private void registerRepo(DocumentFile index) {\n InputStream inputStream = null;\n try {\n inputStream = getContentResolver().openInputStream(index.getUri());\n registerRepo(this, inputStream, index.getParentFile().getUri());\n } catch (IOException | IndexUpdater.SigningException e) {\n e.printStackTrace();\n } finally {\n Utils.closeQuietly(inputStream);\n }\n }\n\n public static void registerRepo(Context context, InputStream inputStream, Uri repoUri)\n throws IOException, IndexUpdater.SigningException {\n if (inputStream == null) {\n return;\n }\n File destFile = File.createTempFile(\"dl-\", IndexV1Updater.SIGNED_FILE_NAME, context.getCacheDir());\n FileUtils.copyInputStreamToFile(inputStream, destFile);\n JarFile jarFile = new JarFile(destFile, true);\n JarEntry indexEntry = (JarEntry) jarFile.getEntry(IndexV1Updater.DATA_FILE_NAME);\n IOUtils.readLines(jarFile.getInputStream(indexEntry));\n Certificate certificate = IndexUpdater.getSigningCertFromJar(indexEntry);\n String fingerprint = Utils.calcFingerprint(certificate);\n Log.i(TAG, \"Got fingerprint: \" + fingerprint);\n destFile.delete();\n\n Log.i(TAG, \"Found a valid, signed index-v1.json\");\n for (Repo repo : RepoProvider.Helper.all(context)) {\n if (fingerprint.equals(repo.fingerprint)) {\n Log.i(TAG, repo.address + \" has the SAME fingerprint: \" + fingerprint);\n } else {\n Log.i(TAG, repo.address + \" different fingerprint\");\n }\n }\n\n AddRepoIntentService.addRepo(context, repoUri, fingerprint);\n \/\/ TODO rework IndexUpdater.getSigningCertFromJar to work for here\n }\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright (C) 2018 Hans-Christoph Steiner \n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.nearby;\n\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.app.IntentService;\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Process;\nimport android.support.v4.provider.DocumentFile;\nimport android.util.Log;\nimport android.widget.Toast;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.IOUtils;\nimport org.fdroid.fdroid.AddRepoIntentService;\nimport org.fdroid.fdroid.IndexUpdater;\nimport org.fdroid.fdroid.IndexV1Updater;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Repo;\nimport org.fdroid.fdroid.data.RepoProvider;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.security.cert.Certificate;\nimport java.util.jar.JarEntry;\nimport java.util.jar.JarFile;\nimport java.util.jar.JarInputStream;\n\n\/**\n * An {@link IntentService} subclass for handling asynchronous scanning of a\n * removable storage device like an SD Card or USB OTG thumb drive using the\n * Storage Access Framework. Permission must first be granted by the user\n * {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} or\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)}request,\n * then F-Droid will have permanent access to that{@link Uri}.\n *

\n * Even though the Storage Access Framework was introduced in\n * {@link android.os.Build.VERSION_CODES#KITKAT android-19}, this approach is only\n * workable if {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} is available.\n * It was added in {@link android.os.Build.VERSION_CODES#LOLLIPOP android-21}.\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)} is also\n * necessary to do this with any kind of rational UX.\n *\n * @see The Storage Situation: Removable Storage <\/a>\n * @see Be Careful with Scoped Directory Access<\/a>\n * @see Using Scoped Directory Access<\/a>\n * @see Open Files using Storage Access Framework<\/a>\n *\/\n@TargetApi(21)\npublic class TreeUriScannerIntentService extends IntentService {\n public static final String TAG = \"TreeUriScannerIntentSer\";\n\n private static final String ACTION_SCAN_TREE_URI = \"org.fdroid.fdroid.nearby.action.SCAN_TREE_URI\";\n\n public TreeUriScannerIntentService() {\n super(\"TreeUriScannerIntentService\");\n }\n\n public static void scan(Context context, Uri data) {\n if (Preferences.get().isScanRemovableStorageEnabled()) {\n Intent intent = new Intent(context, TreeUriScannerIntentService.class);\n intent.setAction(ACTION_SCAN_TREE_URI);\n intent.setData(data);\n context.startService(intent);\n }\n }\n\n \/**\n * Now determine if it is External Storage that must be handled by the\n * {@link TreeUriScannerIntentService} or whether it is External Storage\n * like an SD Card that can be directly accessed via the file system.\n *\/\n public static void onActivityResult(Activity activity, Intent intent) {\n Uri uri = intent.getData();\n if (uri != null) {\n if (Build.VERSION.SDK_INT >= 19) {\n ContentResolver contentResolver = activity.getContentResolver();\n int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;\n contentResolver.takePersistableUriPermission(uri, perms);\n }\n String msg = String.format(activity.getString(R.string.swap_toast_using_path), uri.toString());\n Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();\n scan(activity, uri);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n if (intent == null || !ACTION_SCAN_TREE_URI.equals(intent.getAction())) {\n return;\n }\n Uri treeUri = intent.getData();\n if (treeUri == null) {\n return;\n }\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n DocumentFile treeFile = DocumentFile.fromTreeUri(this, treeUri);\n searchDirectory(treeFile);\n }\n\n private void searchDirectory(DocumentFile documentFileDir) {\n DocumentFile[] documentFiles = documentFileDir.listFiles();\n if (documentFiles == null) {\n return;\n }\n for (DocumentFile documentFile : documentFiles) {\n if (documentFile.isDirectory()) {\n searchDirectory(documentFile);\n } else {\n if (IndexV1Updater.SIGNED_FILE_NAME.equals(documentFile.getName())) {\n registerRepo(documentFile);\n }\n }\n }\n }\n\n \/**\n * For all files called {@link IndexV1Updater#SIGNED_FILE_NAME} found, check\n * the JAR signature and read the fingerprint of the signing certificate.\n * The fingerprint is then used to find whether this local repo is a mirror\n * of an existing repo, or a totally new repo. In order to verify the\n * signatures in the JAR, the whole file needs to be read in first.\n *\n * @see JarInputStream#JarInputStream(InputStream, boolean)\n *\/\n private void registerRepo(DocumentFile index) {\n InputStream inputStream = null;\n try {\n inputStream = getContentResolver().openInputStream(index.getUri());\n registerRepo(this, inputStream, index.getParentFile().getUri());\n } catch (IOException | IndexUpdater.SigningException e) {\n e.printStackTrace();\n } finally {\n Utils.closeQuietly(inputStream);\n }\n }\n\n public static void registerRepo(Context context, InputStream inputStream, Uri repoUri)\n throws IOException, IndexUpdater.SigningException {\n if (inputStream == null) {\n return;\n }\n File destFile = File.createTempFile(\"dl-\", IndexV1Updater.SIGNED_FILE_NAME, context.getCacheDir());\n FileUtils.copyInputStreamToFile(inputStream, destFile);\n JarFile jarFile = new JarFile(destFile, true);\n JarEntry indexEntry = (JarEntry) jarFile.getEntry(IndexV1Updater.DATA_FILE_NAME);\n IOUtils.readLines(jarFile.getInputStream(indexEntry));\n Certificate certificate = IndexUpdater.getSigningCertFromJar(indexEntry);\n String fingerprint = Utils.calcFingerprint(certificate);\n Log.i(TAG, \"Got fingerprint: \" + fingerprint);\n destFile.delete();\n\n Log.i(TAG, \"Found a valid, signed index-v1.json\");\n for (Repo repo : RepoProvider.Helper.all(context)) {\n if (fingerprint.equals(repo.fingerprint)) {\n Log.i(TAG, repo.address + \" has the SAME fingerprint: \" + fingerprint);\n } else {\n Log.i(TAG, repo.address + \" different fingerprint\");\n }\n }\n\n AddRepoIntentService.addRepo(context, repoUri, fingerprint);\n \/\/ TODO rework IndexUpdater.getSigningCertFromJar to work for here\n }\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the code to speed up repo searches using 'depth last'. Write the entire code and no other text in the response.\n\n### Concepts:\n[+] import java.util.ArrayList\n[in] searchDirectory function\n[hint] Recursively search for index-v1.jar starting from the given directory, looking at files first before recursing into directories. This is 'depth last' since the index file is much more likely to be shallow than deep, and there can be a lot of files to search through starting at 4 or more levels deep.\n\n### Given program:\n```java\n\/*\n * Copyright (C) 2018 Hans-Christoph Steiner \n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.nearby;\n\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.app.IntentService;\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Process;\nimport android.support.v4.provider.DocumentFile;\nimport android.util.Log;\nimport android.widget.Toast;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.IOUtils;\nimport org.fdroid.fdroid.AddRepoIntentService;\nimport org.fdroid.fdroid.IndexUpdater;\nimport org.fdroid.fdroid.IndexV1Updater;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Repo;\nimport org.fdroid.fdroid.data.RepoProvider;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.security.cert.Certificate;\nimport java.util.jar.JarEntry;\nimport java.util.jar.JarFile;\nimport java.util.jar.JarInputStream;\n\n\/**\n * An {@link IntentService} subclass for handling asynchronous scanning of a\n * removable storage device like an SD Card or USB OTG thumb drive using the\n * Storage Access Framework. Permission must first be granted by the user\n * {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} or\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)}request,\n * then F-Droid will have permanent access to that{@link Uri}.\n *

\n * Even though the Storage Access Framework was introduced in\n * {@link android.os.Build.VERSION_CODES#KITKAT android-19}, this approach is only\n * workable if {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} is available.\n * It was added in {@link android.os.Build.VERSION_CODES#LOLLIPOP android-21}.\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)} is also\n * necessary to do this with any kind of rational UX.\n *\n * @see The Storage Situation: Removable Storage <\/a>\n * @see Be Careful with Scoped Directory Access<\/a>\n * @see Using Scoped Directory Access<\/a>\n * @see Open Files using Storage Access Framework<\/a>\n *\/\n@TargetApi(21)\npublic class TreeUriScannerIntentService extends IntentService {\n public static final String TAG = \"TreeUriScannerIntentSer\";\n\n private static final String ACTION_SCAN_TREE_URI = \"org.fdroid.fdroid.nearby.action.SCAN_TREE_URI\";\n\n public TreeUriScannerIntentService() {\n super(\"TreeUriScannerIntentService\");\n }\n\n public static void scan(Context context, Uri data) {\n if (Preferences.get().isScanRemovableStorageEnabled()) {\n Intent intent = new Intent(context, TreeUriScannerIntentService.class);\n intent.setAction(ACTION_SCAN_TREE_URI);\n intent.setData(data);\n context.startService(intent);\n }\n }\n\n \/**\n * Now determine if it is External Storage that must be handled by the\n * {@link TreeUriScannerIntentService} or whether it is External Storage\n * like an SD Card that can be directly accessed via the file system.\n *\/\n public static void onActivityResult(Activity activity, Intent intent) {\n Uri uri = intent.getData();\n if (uri != null) {\n if (Build.VERSION.SDK_INT >= 19) {\n ContentResolver contentResolver = activity.getContentResolver();\n int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;\n contentResolver.takePersistableUriPermission(uri, perms);\n }\n String msg = String.format(activity.getString(R.string.swap_toast_using_path), uri.toString());\n Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();\n scan(activity, uri);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n if (intent == null || !ACTION_SCAN_TREE_URI.equals(intent.getAction())) {\n return;\n }\n Uri treeUri = intent.getData();\n if (treeUri == null) {\n return;\n }\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n DocumentFile treeFile = DocumentFile.fromTreeUri(this, treeUri);\n searchDirectory(treeFile);\n }\n\n private void searchDirectory(DocumentFile documentFileDir) {\n DocumentFile[] documentFiles = documentFileDir.listFiles();\n if (documentFiles == null) {\n return;\n }\n for (DocumentFile documentFile : documentFiles) {\n if (documentFile.isDirectory()) {\n searchDirectory(documentFile);\n } else {\n if (IndexV1Updater.SIGNED_FILE_NAME.equals(documentFile.getName())) {\n registerRepo(documentFile);\n }\n }\n }\n }\n\n \/**\n * For all files called {@link IndexV1Updater#SIGNED_FILE_NAME} found, check\n * the JAR signature and read the fingerprint of the signing certificate.\n * The fingerprint is then used to find whether this local repo is a mirror\n * of an existing repo, or a totally new repo. In order to verify the\n * signatures in the JAR, the whole file needs to be read in first.\n *\n * @see JarInputStream#JarInputStream(InputStream, boolean)\n *\/\n private void registerRepo(DocumentFile index) {\n InputStream inputStream = null;\n try {\n inputStream = getContentResolver().openInputStream(index.getUri());\n registerRepo(this, inputStream, index.getParentFile().getUri());\n } catch (IOException | IndexUpdater.SigningException e) {\n e.printStackTrace();\n } finally {\n Utils.closeQuietly(inputStream);\n }\n }\n\n public static void registerRepo(Context context, InputStream inputStream, Uri repoUri)\n throws IOException, IndexUpdater.SigningException {\n if (inputStream == null) {\n return;\n }\n File destFile = File.createTempFile(\"dl-\", IndexV1Updater.SIGNED_FILE_NAME, context.getCacheDir());\n FileUtils.copyInputStreamToFile(inputStream, destFile);\n JarFile jarFile = new JarFile(destFile, true);\n JarEntry indexEntry = (JarEntry) jarFile.getEntry(IndexV1Updater.DATA_FILE_NAME);\n IOUtils.readLines(jarFile.getInputStream(indexEntry));\n Certificate certificate = IndexUpdater.getSigningCertFromJar(indexEntry);\n String fingerprint = Utils.calcFingerprint(certificate);\n Log.i(TAG, \"Got fingerprint: \" + fingerprint);\n destFile.delete();\n\n Log.i(TAG, \"Found a valid, signed index-v1.json\");\n for (Repo repo : RepoProvider.Helper.all(context)) {\n if (fingerprint.equals(repo.fingerprint)) {\n Log.i(TAG, repo.address + \" has the SAME fingerprint: \" + fingerprint);\n } else {\n Log.i(TAG, repo.address + \" different fingerprint\");\n }\n }\n\n AddRepoIntentService.addRepo(context, repoUri, fingerprint);\n \/\/ TODO rework IndexUpdater.getSigningCertFromJar to work for here\n }\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage org.fdroid.fdroid.views.apps;\n\nimport android.content.Intent;\nimport android.database.Cursor;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.v4.app.LoaderManager;\nimport android.support.v4.content.CursorLoader;\nimport android.support.v4.content.Loader;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.KeyEvent;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.view.inputmethod.InputMethodManager;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport com.nostra13.universalimageloader.core.ImageLoader;\nimport org.fdroid.fdroid.FDroidApp;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.data.AppProvider;\nimport org.fdroid.fdroid.data.Schema;\n\npublic class AppListActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks,\n CategoryTextWatcher.SearchTermsChangedListener {\n\n public static final String EXTRA_CATEGORY\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_CATEGORY\";\n public static final String EXTRA_SEARCH_TERMS\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_SEARCH_TERMS\";\n\n private RecyclerView appView;\n private AppListAdapter appAdapter;\n private String category;\n private String searchTerms;\n private String sortClauseSelected = SortClause.LAST_UPDATED;\n private TextView emptyState;\n private EditText searchInput;\n private ImageView sortImage;\n\n private interface SortClause {\n String NAME = Schema.AppMetadataTable.NAME + \".\" + Schema.AppMetadataTable.Cols.NAME + \" asc\";\n String LAST_UPDATED = Schema.AppMetadataTable.NAME + \".\"\n + Schema.AppMetadataTable.Cols.LAST_UPDATED + \" desc\";\n }\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n ((FDroidApp) getApplication()).applyTheme(this);\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.activity_app_list);\n\n searchInput = (EditText) findViewById(R.id.search);\n searchInput.addTextChangedListener(new CategoryTextWatcher(this, searchInput, this));\n searchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_SEARCH) {\n \/\/ Hide the keyboard (http:\/\/stackoverflow.com\/a\/1109108 (when pressing search)\n InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);\n inputManager.hideSoftInputFromWindow(searchInput.getWindowToken(), 0);\n\n \/\/ Change focus from the search input to the app list.\n appView.requestFocus();\n return true;\n }\n return false;\n }\n });\n\n sortImage = (ImageView) findViewById(R.id.sort);\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n sortImage.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n if (sortClauseSelected.equalsIgnoreCase(SortClause.LAST_UPDATED)) {\n sortClauseSelected = SortClause.NAME;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_az_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_az_white);\n }\n } else {\n sortClauseSelected = SortClause.LAST_UPDATED;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n }\n getSupportLoaderManager().restartLoader(0, null, AppListActivity.this);\n appView.scrollToPosition(0);\n }\n });\n\n emptyState = (TextView) findViewById(R.id.empty_state);\n\n View backButton = findViewById(R.id.back);\n backButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n finish();\n }\n });\n\n View clearButton = findViewById(R.id.clear);\n clearButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n searchInput.setText(\"\");\n }\n });\n\n appAdapter = new AppListAdapter(this);\n\n appView = (RecyclerView) findViewById(R.id.app_list);\n appView.setHasFixedSize(true);\n appView.setLayoutManager(new LinearLayoutManager(this));\n appView.setAdapter(appAdapter);\n appView.addOnScrollListener(new RecyclerView.OnScrollListener() {\n private final ImageLoader imageLoader = ImageLoader.getInstance();\n\n @Override\n public void onScrollStateChanged(RecyclerView recyclerView, int newState) {\n switch (newState) {\n case RecyclerView.SCROLL_STATE_DRAGGING:\n imageLoader.pause();\n break;\n case RecyclerView.SCROLL_STATE_IDLE:\n imageLoader.resume();\n break;\n }\n super.onScrollStateChanged(recyclerView, newState);\n }\n });\n\n parseIntentForSearchQuery();\n }\n\n private void parseIntentForSearchQuery() {\n Intent intent = getIntent();\n category = intent.hasExtra(EXTRA_CATEGORY) ? intent.getStringExtra(EXTRA_CATEGORY) : null;\n searchTerms = intent.hasExtra(EXTRA_SEARCH_TERMS) ? intent.getStringExtra(EXTRA_SEARCH_TERMS) : null;\n\n searchInput.setText(getSearchText(category, searchTerms));\n searchInput.setSelection(searchInput.getText().length());\n\n if (category != null) {\n \/\/ Do this so that the search input does not get focus by default. This allows for a user\n \/\/ experience where the user scrolls through the apps in the category.\n appView.requestFocus();\n }\n\n getSupportLoaderManager().initLoader(0, null, this);\n }\n\n private CharSequence getSearchText(@Nullable String category, @Nullable String searchTerms) {\n StringBuilder string = new StringBuilder();\n if (category != null) {\n string.append(category).append(\":\");\n }\n\n if (searchTerms != null) {\n string.append(searchTerms);\n }\n\n return string.toString();\n }\n\n @Override\n public Loader onCreateLoader(int id, Bundle args) {\n return new CursorLoader(\n this,\n AppProvider.getSearchUri(searchTerms, category),\n Schema.AppMetadataTable.Cols.ALL,\n null,\n null,\n sortClauseSelected\n );\n }\n\n @Override\n public void onLoadFinished(Loader loader, Cursor cursor) {\n appAdapter.setAppCursor(cursor);\n if (cursor.getCount() > 0) {\n emptyState.setVisibility(View.GONE);\n appView.setVisibility(View.VISIBLE);\n } else {\n emptyState.setVisibility(View.VISIBLE);\n appView.setVisibility(View.GONE);\n }\n }\n\n @Override\n public void onLoaderReset(Loader loader) {\n appAdapter.setAppCursor(null);\n }\n\n @Override\n public void onSearchTermsChanged(@Nullable String category, @NonNull String searchTerms) {\n this.category = category;\n this.searchTerms = searchTerms;\n getSupportLoaderManager().restartLoader(0, null, this);\n }\n}\n\n\nCode-B:\npackage org.fdroid.fdroid.views.apps;\n\nimport android.content.Intent;\nimport android.database.Cursor;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.v4.app.LoaderManager;\nimport android.support.v4.content.CursorLoader;\nimport android.support.v4.content.Loader;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.KeyEvent;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.view.inputmethod.InputMethodManager;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport org.fdroid.fdroid.FDroidApp;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.data.AppProvider;\nimport org.fdroid.fdroid.data.Schema;\n\npublic class AppListActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks,\n CategoryTextWatcher.SearchTermsChangedListener {\n\n public static final String EXTRA_CATEGORY\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_CATEGORY\";\n public static final String EXTRA_SEARCH_TERMS\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_SEARCH_TERMS\";\n\n private RecyclerView appView;\n private AppListAdapter appAdapter;\n private String category;\n private String searchTerms;\n private String sortClauseSelected = SortClause.LAST_UPDATED;\n private TextView emptyState;\n private EditText searchInput;\n private ImageView sortImage;\n\n private interface SortClause {\n String NAME = Schema.AppMetadataTable.NAME + \".\" + Schema.AppMetadataTable.Cols.NAME + \" asc\";\n String LAST_UPDATED = Schema.AppMetadataTable.NAME + \".\"\n + Schema.AppMetadataTable.Cols.LAST_UPDATED + \" desc\";\n }\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n ((FDroidApp) getApplication()).applyTheme(this);\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.activity_app_list);\n\n searchInput = (EditText) findViewById(R.id.search);\n searchInput.addTextChangedListener(new CategoryTextWatcher(this, searchInput, this));\n searchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_SEARCH) {\n \/\/ Hide the keyboard (http:\/\/stackoverflow.com\/a\/1109108 (when pressing search)\n InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);\n inputManager.hideSoftInputFromWindow(searchInput.getWindowToken(), 0);\n\n \/\/ Change focus from the search input to the app list.\n appView.requestFocus();\n return true;\n }\n return false;\n }\n });\n\n sortImage = (ImageView) findViewById(R.id.sort);\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n sortImage.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n if (sortClauseSelected.equalsIgnoreCase(SortClause.LAST_UPDATED)) {\n sortClauseSelected = SortClause.NAME;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_az_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_az_white);\n }\n } else {\n sortClauseSelected = SortClause.LAST_UPDATED;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n }\n getSupportLoaderManager().restartLoader(0, null, AppListActivity.this);\n appView.scrollToPosition(0);\n }\n });\n\n emptyState = (TextView) findViewById(R.id.empty_state);\n\n View backButton = findViewById(R.id.back);\n backButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n finish();\n }\n });\n\n View clearButton = findViewById(R.id.clear);\n clearButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n searchInput.setText(\"\");\n }\n });\n\n appAdapter = new AppListAdapter(this);\n\n appView = (RecyclerView) findViewById(R.id.app_list);\n appView.setHasFixedSize(true);\n appView.setLayoutManager(new LinearLayoutManager(this));\n appView.setAdapter(appAdapter);\n\n parseIntentForSearchQuery();\n }\n\n private void parseIntentForSearchQuery() {\n Intent intent = getIntent();\n category = intent.hasExtra(EXTRA_CATEGORY) ? intent.getStringExtra(EXTRA_CATEGORY) : null;\n searchTerms = intent.hasExtra(EXTRA_SEARCH_TERMS) ? intent.getStringExtra(EXTRA_SEARCH_TERMS) : null;\n\n searchInput.setText(getSearchText(category, searchTerms));\n searchInput.setSelection(searchInput.getText().length());\n\n if (category != null) {\n \/\/ Do this so that the search input does not get focus by default. This allows for a user\n \/\/ experience where the user scrolls through the apps in the category.\n appView.requestFocus();\n }\n\n getSupportLoaderManager().initLoader(0, null, this);\n }\n\n private CharSequence getSearchText(@Nullable String category, @Nullable String searchTerms) {\n StringBuilder string = new StringBuilder();\n if (category != null) {\n string.append(category).append(\":\");\n }\n\n if (searchTerms != null) {\n string.append(searchTerms);\n }\n\n return string.toString();\n }\n\n @Override\n public Loader onCreateLoader(int id, Bundle args) {\n return new CursorLoader(\n this,\n AppProvider.getSearchUri(searchTerms, category),\n Schema.AppMetadataTable.Cols.ALL,\n null,\n null,\n sortClauseSelected\n );\n }\n\n @Override\n public void onLoadFinished(Loader loader, Cursor cursor) {\n appAdapter.setAppCursor(cursor);\n if (cursor.getCount() > 0) {\n emptyState.setVisibility(View.GONE);\n appView.setVisibility(View.VISIBLE);\n } else {\n emptyState.setVisibility(View.VISIBLE);\n appView.setVisibility(View.GONE);\n }\n }\n\n @Override\n public void onLoaderReset(Loader loader) {\n appAdapter.setAppCursor(null);\n }\n\n @Override\n public void onSearchTermsChanged(@Nullable String category, @NonNull String searchTerms) {\n this.category = category;\n this.searchTerms = searchTerms;\n getSupportLoaderManager().restartLoader(0, null, this);\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage org.fdroid.fdroid.views.apps;\n\nimport android.content.Intent;\nimport android.database.Cursor;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.v4.app.LoaderManager;\nimport android.support.v4.content.CursorLoader;\nimport android.support.v4.content.Loader;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.KeyEvent;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.view.inputmethod.InputMethodManager;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport org.fdroid.fdroid.FDroidApp;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.data.AppProvider;\nimport org.fdroid.fdroid.data.Schema;\n\npublic class AppListActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks,\n CategoryTextWatcher.SearchTermsChangedListener {\n\n public static final String EXTRA_CATEGORY\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_CATEGORY\";\n public static final String EXTRA_SEARCH_TERMS\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_SEARCH_TERMS\";\n\n private RecyclerView appView;\n private AppListAdapter appAdapter;\n private String category;\n private String searchTerms;\n private String sortClauseSelected = SortClause.LAST_UPDATED;\n private TextView emptyState;\n private EditText searchInput;\n private ImageView sortImage;\n\n private interface SortClause {\n String NAME = Schema.AppMetadataTable.NAME + \".\" + Schema.AppMetadataTable.Cols.NAME + \" asc\";\n String LAST_UPDATED = Schema.AppMetadataTable.NAME + \".\"\n + Schema.AppMetadataTable.Cols.LAST_UPDATED + \" desc\";\n }\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n ((FDroidApp) getApplication()).applyTheme(this);\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.activity_app_list);\n\n searchInput = (EditText) findViewById(R.id.search);\n searchInput.addTextChangedListener(new CategoryTextWatcher(this, searchInput, this));\n searchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_SEARCH) {\n \/\/ Hide the keyboard (http:\/\/stackoverflow.com\/a\/1109108 (when pressing search)\n InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);\n inputManager.hideSoftInputFromWindow(searchInput.getWindowToken(), 0);\n\n \/\/ Change focus from the search input to the app list.\n appView.requestFocus();\n return true;\n }\n return false;\n }\n });\n\n sortImage = (ImageView) findViewById(R.id.sort);\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n sortImage.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n if (sortClauseSelected.equalsIgnoreCase(SortClause.LAST_UPDATED)) {\n sortClauseSelected = SortClause.NAME;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_az_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_az_white);\n }\n } else {\n sortClauseSelected = SortClause.LAST_UPDATED;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n }\n getSupportLoaderManager().restartLoader(0, null, AppListActivity.this);\n appView.scrollToPosition(0);\n }\n });\n\n emptyState = (TextView) findViewById(R.id.empty_state);\n\n View backButton = findViewById(R.id.back);\n backButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n finish();\n }\n });\n\n View clearButton = findViewById(R.id.clear);\n clearButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n searchInput.setText(\"\");\n }\n });\n\n appAdapter = new AppListAdapter(this);\n\n appView = (RecyclerView) findViewById(R.id.app_list);\n appView.setHasFixedSize(true);\n appView.setLayoutManager(new LinearLayoutManager(this));\n appView.setAdapter(appAdapter);\n\n parseIntentForSearchQuery();\n }\n\n private void parseIntentForSearchQuery() {\n Intent intent = getIntent();\n category = intent.hasExtra(EXTRA_CATEGORY) ? intent.getStringExtra(EXTRA_CATEGORY) : null;\n searchTerms = intent.hasExtra(EXTRA_SEARCH_TERMS) ? intent.getStringExtra(EXTRA_SEARCH_TERMS) : null;\n\n searchInput.setText(getSearchText(category, searchTerms));\n searchInput.setSelection(searchInput.getText().length());\n\n if (category != null) {\n \/\/ Do this so that the search input does not get focus by default. This allows for a user\n \/\/ experience where the user scrolls through the apps in the category.\n appView.requestFocus();\n }\n\n getSupportLoaderManager().initLoader(0, null, this);\n }\n\n private CharSequence getSearchText(@Nullable String category, @Nullable String searchTerms) {\n StringBuilder string = new StringBuilder();\n if (category != null) {\n string.append(category).append(\":\");\n }\n\n if (searchTerms != null) {\n string.append(searchTerms);\n }\n\n return string.toString();\n }\n\n @Override\n public Loader onCreateLoader(int id, Bundle args) {\n return new CursorLoader(\n this,\n AppProvider.getSearchUri(searchTerms, category),\n Schema.AppMetadataTable.Cols.ALL,\n null,\n null,\n sortClauseSelected\n );\n }\n\n @Override\n public void onLoadFinished(Loader loader, Cursor cursor) {\n appAdapter.setAppCursor(cursor);\n if (cursor.getCount() > 0) {\n emptyState.setVisibility(View.GONE);\n appView.setVisibility(View.VISIBLE);\n } else {\n emptyState.setVisibility(View.VISIBLE);\n appView.setVisibility(View.GONE);\n }\n }\n\n @Override\n public void onLoaderReset(Loader loader) {\n appAdapter.setAppCursor(null);\n }\n\n @Override\n public void onSearchTermsChanged(@Nullable String category, @NonNull String searchTerms) {\n this.category = category;\n this.searchTerms = searchTerms;\n getSupportLoaderManager().restartLoader(0, null, this);\n }\n}\n\n\nCode-B:\npackage org.fdroid.fdroid.views.apps;\n\nimport android.content.Intent;\nimport android.database.Cursor;\nimport android.os.Bundle;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.v4.app.LoaderManager;\nimport android.support.v4.content.CursorLoader;\nimport android.support.v4.content.Loader;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.KeyEvent;\nimport android.view.View;\nimport android.view.inputmethod.EditorInfo;\nimport android.view.inputmethod.InputMethodManager;\nimport android.widget.EditText;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport com.nostra13.universalimageloader.core.ImageLoader;\nimport org.fdroid.fdroid.FDroidApp;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.data.AppProvider;\nimport org.fdroid.fdroid.data.Schema;\n\npublic class AppListActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks,\n CategoryTextWatcher.SearchTermsChangedListener {\n\n public static final String EXTRA_CATEGORY\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_CATEGORY\";\n public static final String EXTRA_SEARCH_TERMS\n = \"org.fdroid.fdroid.views.apps.AppListActivity.EXTRA_SEARCH_TERMS\";\n\n private RecyclerView appView;\n private AppListAdapter appAdapter;\n private String category;\n private String searchTerms;\n private String sortClauseSelected = SortClause.LAST_UPDATED;\n private TextView emptyState;\n private EditText searchInput;\n private ImageView sortImage;\n\n private interface SortClause {\n String NAME = Schema.AppMetadataTable.NAME + \".\" + Schema.AppMetadataTable.Cols.NAME + \" asc\";\n String LAST_UPDATED = Schema.AppMetadataTable.NAME + \".\"\n + Schema.AppMetadataTable.Cols.LAST_UPDATED + \" desc\";\n }\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n ((FDroidApp) getApplication()).applyTheme(this);\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.activity_app_list);\n\n searchInput = (EditText) findViewById(R.id.search);\n searchInput.addTextChangedListener(new CategoryTextWatcher(this, searchInput, this));\n searchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_SEARCH) {\n \/\/ Hide the keyboard (http:\/\/stackoverflow.com\/a\/1109108 (when pressing search)\n InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);\n inputManager.hideSoftInputFromWindow(searchInput.getWindowToken(), 0);\n\n \/\/ Change focus from the search input to the app list.\n appView.requestFocus();\n return true;\n }\n return false;\n }\n });\n\n sortImage = (ImageView) findViewById(R.id.sort);\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n sortImage.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n if (sortClauseSelected.equalsIgnoreCase(SortClause.LAST_UPDATED)) {\n sortClauseSelected = SortClause.NAME;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_az_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_az_white);\n }\n } else {\n sortClauseSelected = SortClause.LAST_UPDATED;\n if (FDroidApp.isAppThemeLight()) {\n sortImage.setImageResource(R.drawable.ic_last_updated_black);\n } else {\n sortImage.setImageResource(R.drawable.ic_last_updated_white);\n }\n }\n getSupportLoaderManager().restartLoader(0, null, AppListActivity.this);\n appView.scrollToPosition(0);\n }\n });\n\n emptyState = (TextView) findViewById(R.id.empty_state);\n\n View backButton = findViewById(R.id.back);\n backButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n finish();\n }\n });\n\n View clearButton = findViewById(R.id.clear);\n clearButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n searchInput.setText(\"\");\n }\n });\n\n appAdapter = new AppListAdapter(this);\n\n appView = (RecyclerView) findViewById(R.id.app_list);\n appView.setHasFixedSize(true);\n appView.setLayoutManager(new LinearLayoutManager(this));\n appView.setAdapter(appAdapter);\n appView.addOnScrollListener(new RecyclerView.OnScrollListener() {\n private final ImageLoader imageLoader = ImageLoader.getInstance();\n\n @Override\n public void onScrollStateChanged(RecyclerView recyclerView, int newState) {\n switch (newState) {\n case RecyclerView.SCROLL_STATE_DRAGGING:\n imageLoader.pause();\n break;\n case RecyclerView.SCROLL_STATE_IDLE:\n imageLoader.resume();\n break;\n }\n super.onScrollStateChanged(recyclerView, newState);\n }\n });\n\n parseIntentForSearchQuery();\n }\n\n private void parseIntentForSearchQuery() {\n Intent intent = getIntent();\n category = intent.hasExtra(EXTRA_CATEGORY) ? intent.getStringExtra(EXTRA_CATEGORY) : null;\n searchTerms = intent.hasExtra(EXTRA_SEARCH_TERMS) ? intent.getStringExtra(EXTRA_SEARCH_TERMS) : null;\n\n searchInput.setText(getSearchText(category, searchTerms));\n searchInput.setSelection(searchInput.getText().length());\n\n if (category != null) {\n \/\/ Do this so that the search input does not get focus by default. This allows for a user\n \/\/ experience where the user scrolls through the apps in the category.\n appView.requestFocus();\n }\n\n getSupportLoaderManager().initLoader(0, null, this);\n }\n\n private CharSequence getSearchText(@Nullable String category, @Nullable String searchTerms) {\n StringBuilder string = new StringBuilder();\n if (category != null) {\n string.append(category).append(\":\");\n }\n\n if (searchTerms != null) {\n string.append(searchTerms);\n }\n\n return string.toString();\n }\n\n @Override\n public Loader onCreateLoader(int id, Bundle args) {\n return new CursorLoader(\n this,\n AppProvider.getSearchUri(searchTerms, category),\n Schema.AppMetadataTable.Cols.ALL,\n null,\n null,\n sortClauseSelected\n );\n }\n\n @Override\n public void onLoadFinished(Loader loader, Cursor cursor) {\n appAdapter.setAppCursor(cursor);\n if (cursor.getCount() > 0) {\n emptyState.setVisibility(View.GONE);\n appView.setVisibility(View.VISIBLE);\n } else {\n emptyState.setVisibility(View.VISIBLE);\n appView.setVisibility(View.GONE);\n }\n }\n\n @Override\n public void onLoaderReset(Loader loader) {\n appAdapter.setAppCursor(null);\n }\n\n @Override\n public void onSearchTermsChanged(@Nullable String category, @NonNull String searchTerms) {\n this.category = category;\n this.searchTerms = searchTerms;\n getSupportLoaderManager().restartLoader(0, null, this);\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/yellowbluesky\/PixivforMuzei3\/commit\/2be406a6edb888b0bc17eba1d7ae44b0eb8a92fd","commit_message":"'\\\\\"experimental change to more cleanly clear cache\\\\n\\\\\"'","source_code":"package com.antony.muzei.pixiv;\n\nimport android.content.SharedPreferences;\nimport android.os.Bundle;\nimport android.widget.Toast;\n\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.preference.Preference;\nimport androidx.preference.PreferenceFragmentCompat;\nimport androidx.preference.PreferenceManager;\nimport androidx.work.Constraints;\nimport androidx.work.ExistingPeriodicWorkPolicy;\nimport androidx.work.NetworkType;\nimport androidx.work.PeriodicWorkRequest;\nimport androidx.work.WorkManager;\n\nimport com.antony.muzei.pixiv.ClearCacheWorker;\nimport com.antony.muzei.pixiv.PixivArtProvider;\nimport com.antony.muzei.pixiv.PixivArtWorker;\nimport com.antony.muzei.pixiv.R;\nimport com.google.android.apps.muzei.api.provider.Artwork;\nimport com.google.android.apps.muzei.api.provider.ProviderContract;\n\nimport java.util.concurrent.TimeUnit;\n\npublic class SettingsActivity extends AppCompatActivity\n{\n private SharedPreferences.OnSharedPreferenceChangeListener prefChangeListener;\n private String newCreds, oldCreds;\n private String oldUpdateMode, newUpdateMode;\n private String oldFilter, newFilter;\n\n @Override\n protected void onCreate(Bundle savedInstanceState)\n {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.settings_activity);\n getSupportFragmentManager()\n .beginTransaction()\n .add(R.id.FeedPreferencesFragment, new SettingsFragment())\n .commit();\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n\n \/\/ Stores user toggleable variables into a temporary store for later comparison in onDestroy()\n oldCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n newCreds = oldCreds;\n\n oldUpdateMode = sharedPrefs.getString(\"pref_updateMode\", \"\");\n newUpdateMode = oldUpdateMode;\n\n oldFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n newFilter = oldFilter;\n\n prefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()\n {\n @Override\n public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)\n {\n if (key.equals(\"pref_loginPassword\"))\n {\n newCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n } else if (key.equals(\"pref_updateMode\"))\n {\n newUpdateMode = sharedPrefs.getString(\"oldUpdateMode\", \"\");\n } else if (key.equals(\"pref_nsfwFilterLevel\"))\n {\n newFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n }\n }\n };\n }\n\n @Override\n public void onResume()\n {\n super.onResume();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.registerOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onPause()\n {\n super.onPause();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onStop()\n {\n super.onStop();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n \/\/ Functions in here action only on app exit\n @Override\n public void onDestroy()\n {\n super.onDestroy();\n \/\/ If new user credentials were entered and saved, then clear and invalidate existing stored user credentials\n if (!oldCreds.equals(newCreds))\n {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n SharedPreferences.Editor editor = sharedPrefs.edit();\n editor.putString(\"accessToken\", \"\");\n editor.putString(\"refreshToken\", \"\");\n editor.putString(\"deviceToken\", \"\");\n editor.putLong(\"accessTokenIssueTime\", 0);\n editor.commit();\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newCredentials), Toast.LENGTH_SHORT).show();\n }\n\n \/\/ TODO\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n if (sharedPrefs.getBoolean(\"pref_autoClearMode\", false))\n {\n Constraints constraints = new Constraints.Builder()\n .setRequiredNetworkType(NetworkType.CONNECTED)\n .build();\n PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(ClearCacheWorker.class, 24, TimeUnit.HOURS)\n .setInitialDelay(1, TimeUnit.HOURS)\n .addTag(\"PIXIV_CACHE\")\n .setConstraints(constraints)\n .build();\n WorkManager.getInstance(getApplicationContext()).enqueueUniquePeriodicWork(\"PIXIV_CACHE\", ExistingPeriodicWorkPolicy.KEEP, request);\n } else\n {\n WorkManager.getInstance((getApplicationContext())).cancelAllWorkByTag(\"PIXIV_CACHE\");\n }\n\n if (!oldUpdateMode.equals(newUpdateMode))\n {\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newUpdateMode), Toast.LENGTH_SHORT).show();\n } else if (!oldFilter.equals(newFilter))\n {\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newFilterMode), Toast.LENGTH_SHORT).show();\n }\n\n\n }\n\n \/\/ Functions in here action immediately on user interaction\n public static class SettingsFragment extends PreferenceFragmentCompat\n {\n @Override\n public void onCreatePreferences(Bundle savedInstanceState, String rootKey)\n {\n setPreferencesFromResource(R.xml.feed_preferences_layout, rootKey);\n\n \/\/ Immediately clear cache\n Preference buttonClearCache = findPreference(getString(R.string.button_clearCache));\n buttonClearCache.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n ProviderContract.getProviderClient(getContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getContext(), getString(R.string.toast_clearingCache), Toast.LENGTH_SHORT).show();\n return true;\n }\n });\n\n \/\/ Manually force pull a new unage\n Preference buttonForcePull = findPreference(getString(R.string.button_forcePull));\n buttonForcePull.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n PixivArtWorker.enqueueLoad();\n return true;\n }\n });\n\n Preference loginId = findPreference(\"pref_loginId\");\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());\n if (sharedPrefs.getString(\"accessToken\", \"\").isEmpty())\n {\n loginId.setSummary(getString(R.string.prefSummary_authFail));\n } else\n {\n String summaryString = getString(R.string.prefSummary_authSuccess) + \" \" + sharedPrefs.getString(\"pref_loginId\", \"\");\n loginId.setSummary(summaryString);\n\/\/ Uri profileImageUri = Uri.parse(sharedPrefs.getString(\"profileImageUri\", \"\"));\n\/\/ loginId.setIcon();\n }\n }\n }\n}","target_code":"package com.antony.muzei.pixiv;\n\nimport android.content.SharedPreferences;\nimport android.os.Bundle;\nimport android.widget.Toast;\n\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.preference.Preference;\nimport androidx.preference.PreferenceFragmentCompat;\nimport androidx.preference.PreferenceManager;\nimport androidx.work.Constraints;\nimport androidx.work.ExistingPeriodicWorkPolicy;\nimport androidx.work.NetworkType;\nimport androidx.work.PeriodicWorkRequest;\nimport androidx.work.WorkManager;\n\nimport com.antony.muzei.pixiv.ClearCacheWorker;\nimport com.antony.muzei.pixiv.PixivArtProvider;\nimport com.antony.muzei.pixiv.PixivArtWorker;\nimport com.antony.muzei.pixiv.R;\nimport com.google.android.apps.muzei.api.provider.Artwork;\nimport com.google.android.apps.muzei.api.provider.ProviderContract;\n\nimport java.util.concurrent.TimeUnit;\n\npublic class SettingsActivity extends AppCompatActivity\n{\n private SharedPreferences.OnSharedPreferenceChangeListener prefChangeListener;\n private String newCreds, oldCreds;\n private String oldUpdateMode, newUpdateMode;\n private String oldFilter, newFilter;\n\n @Override\n protected void onCreate(Bundle savedInstanceState)\n {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.settings_activity);\n getSupportFragmentManager()\n .beginTransaction()\n .add(R.id.FeedPreferencesFragment, new SettingsFragment())\n .commit();\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n\n \/\/ Stores user toggleable variables into a temporary store for later comparison in onDestroy()\n oldCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n newCreds = oldCreds;\n\n oldUpdateMode = sharedPrefs.getString(\"pref_updateMode\", \"\");\n newUpdateMode = oldUpdateMode;\n\n oldFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n newFilter = oldFilter;\n\n prefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()\n {\n @Override\n public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)\n {\n if (key.equals(\"pref_loginPassword\"))\n {\n newCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n } else if (key.equals(\"pref_updateMode\"))\n {\n newUpdateMode = sharedPrefs.getString(\"oldUpdateMode\", \"\");\n } else if (key.equals(\"pref_nsfwFilterLevel\"))\n {\n newFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n }\n }\n };\n }\n\n @Override\n public void onResume()\n {\n super.onResume();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.registerOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onPause()\n {\n super.onPause();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onStop()\n {\n super.onStop();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n \/\/ Functions in here action only on app exit\n @Override\n public void onDestroy()\n {\n super.onDestroy();\n \/\/ If new user credentials were entered and saved, then clear and invalidate existing stored user credentials\n if (!oldCreds.equals(newCreds))\n {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n SharedPreferences.Editor editor = sharedPrefs.edit();\n editor.putString(\"accessToken\", \"\");\n editor.putString(\"refreshToken\", \"\");\n editor.putString(\"deviceToken\", \"\");\n editor.putLong(\"accessTokenIssueTime\", 0);\n editor.commit();\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newCredentials), Toast.LENGTH_SHORT).show();\n }\n\n \/\/ TODO\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n if (sharedPrefs.getBoolean(\"pref_autoClearMode\", false))\n {\n Constraints constraints = new Constraints.Builder()\n .setRequiredNetworkType(NetworkType.CONNECTED)\n .build();\n PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(ClearCacheWorker.class, 24, TimeUnit.HOURS)\n .setInitialDelay(1, TimeUnit.HOURS)\n .addTag(\"PIXIV_CACHE\")\n .setConstraints(constraints)\n .build();\n WorkManager.getInstance(getApplicationContext()).enqueueUniquePeriodicWork(\"PIXIV_CACHE\", ExistingPeriodicWorkPolicy.KEEP, request);\n } else\n {\n WorkManager.getInstance((getApplicationContext())).cancelAllWorkByTag(\"PIXIV_CACHE\");\n }\n\n if (!oldUpdateMode.equals(newUpdateMode))\n {\n WorkManager.getInstance().cancelAllWorkByTag(\"PIXIV\");\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newUpdateMode), Toast.LENGTH_SHORT).show();\n } else if (!oldFilter.equals(newFilter))\n {\n WorkManager.getInstance().cancelAllWorkByTag(\"PIXIV\");\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newFilterMode), Toast.LENGTH_SHORT).show();\n }\n\n\n }\n\n \/\/ Functions in here action immediately on user interaction\n public static class SettingsFragment extends PreferenceFragmentCompat\n {\n @Override\n public void onCreatePreferences(Bundle savedInstanceState, String rootKey)\n {\n setPreferencesFromResource(R.xml.feed_preferences_layout, rootKey);\n\n \/\/ Immediately clear cache\n Preference buttonClearCache = findPreference(getString(R.string.button_clearCache));\n buttonClearCache.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n ProviderContract.getProviderClient(getContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getContext(), getString(R.string.toast_clearingCache), Toast.LENGTH_SHORT).show();\n return true;\n }\n });\n\n \/\/ Manually force pull a new unage\n Preference buttonForcePull = findPreference(getString(R.string.button_forcePull));\n buttonForcePull.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n PixivArtWorker.enqueueLoad();\n return true;\n }\n });\n\n Preference loginId = findPreference(\"pref_loginId\");\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());\n if (sharedPrefs.getString(\"accessToken\", \"\").isEmpty())\n {\n loginId.setSummary(getString(R.string.prefSummary_authFail));\n } else\n {\n String summaryString = getString(R.string.prefSummary_authSuccess) + \" \" + sharedPrefs.getString(\"pref_loginId\", \"\");\n loginId.setSummary(summaryString);\n\/\/ Uri profileImageUri = Uri.parse(sharedPrefs.getString(\"profileImageUri\", \"\"));\n\/\/ loginId.setIcon();\n }\n }\n }\n}","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.antony.muzei.pixiv;\n\nimport android.content.SharedPreferences;\nimport android.os.Bundle;\nimport android.widget.Toast;\n\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.preference.Preference;\nimport androidx.preference.PreferenceFragmentCompat;\nimport androidx.preference.PreferenceManager;\nimport androidx.work.Constraints;\nimport androidx.work.ExistingPeriodicWorkPolicy;\nimport androidx.work.NetworkType;\nimport androidx.work.PeriodicWorkRequest;\nimport androidx.work.WorkManager;\n\nimport com.antony.muzei.pixiv.ClearCacheWorker;\nimport com.antony.muzei.pixiv.PixivArtProvider;\nimport com.antony.muzei.pixiv.PixivArtWorker;\nimport com.antony.muzei.pixiv.R;\nimport com.google.android.apps.muzei.api.provider.Artwork;\nimport com.google.android.apps.muzei.api.provider.ProviderContract;\n\nimport java.util.concurrent.TimeUnit;\n\npublic class SettingsActivity extends AppCompatActivity\n{\n private SharedPreferences.OnSharedPreferenceChangeListener prefChangeListener;\n private String newCreds, oldCreds;\n private String oldUpdateMode, newUpdateMode;\n private String oldFilter, newFilter;\n\n @Override\n protected void onCreate(Bundle savedInstanceState)\n {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.settings_activity);\n getSupportFragmentManager()\n .beginTransaction()\n .add(R.id.FeedPreferencesFragment, new SettingsFragment())\n .commit();\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n\n \/\/ Stores user toggleable variables into a temporary store for later comparison in onDestroy()\n oldCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n newCreds = oldCreds;\n\n oldUpdateMode = sharedPrefs.getString(\"pref_updateMode\", \"\");\n newUpdateMode = oldUpdateMode;\n\n oldFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n newFilter = oldFilter;\n\n prefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()\n {\n @Override\n public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)\n {\n if (key.equals(\"pref_loginPassword\"))\n {\n newCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n } else if (key.equals(\"pref_updateMode\"))\n {\n newUpdateMode = sharedPrefs.getString(\"oldUpdateMode\", \"\");\n } else if (key.equals(\"pref_nsfwFilterLevel\"))\n {\n newFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n }\n }\n };\n }\n\n @Override\n public void onResume()\n {\n super.onResume();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.registerOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onPause()\n {\n super.onPause();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onStop()\n {\n super.onStop();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n \/\/ Functions in here action only on app exit\n @Override\n public void onDestroy()\n {\n super.onDestroy();\n \/\/ If new user credentials were entered and saved, then clear and invalidate existing stored user credentials\n if (!oldCreds.equals(newCreds))\n {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n SharedPreferences.Editor editor = sharedPrefs.edit();\n editor.putString(\"accessToken\", \"\");\n editor.putString(\"refreshToken\", \"\");\n editor.putString(\"deviceToken\", \"\");\n editor.putLong(\"accessTokenIssueTime\", 0);\n editor.commit();\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newCredentials), Toast.LENGTH_SHORT).show();\n }\n\n \/\/ TODO\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n if (sharedPrefs.getBoolean(\"pref_autoClearMode\", false))\n {\n Constraints constraints = new Constraints.Builder()\n .setRequiredNetworkType(NetworkType.CONNECTED)\n .build();\n PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(ClearCacheWorker.class, 24, TimeUnit.HOURS)\n .setInitialDelay(1, TimeUnit.HOURS)\n .addTag(\"PIXIV_CACHE\")\n .setConstraints(constraints)\n .build();\n WorkManager.getInstance(getApplicationContext()).enqueueUniquePeriodicWork(\"PIXIV_CACHE\", ExistingPeriodicWorkPolicy.KEEP, request);\n } else\n {\n WorkManager.getInstance((getApplicationContext())).cancelAllWorkByTag(\"PIXIV_CACHE\");\n }\n\n if (!oldUpdateMode.equals(newUpdateMode))\n {\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newUpdateMode), Toast.LENGTH_SHORT).show();\n } else if (!oldFilter.equals(newFilter))\n {\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newFilterMode), Toast.LENGTH_SHORT).show();\n }\n\n\n }\n\n \/\/ Functions in here action immediately on user interaction\n public static class SettingsFragment extends PreferenceFragmentCompat\n {\n @Override\n public void onCreatePreferences(Bundle savedInstanceState, String rootKey)\n {\n setPreferencesFromResource(R.xml.feed_preferences_layout, rootKey);\n\n \/\/ Immediately clear cache\n Preference buttonClearCache = findPreference(getString(R.string.button_clearCache));\n buttonClearCache.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n ProviderContract.getProviderClient(getContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getContext(), getString(R.string.toast_clearingCache), Toast.LENGTH_SHORT).show();\n return true;\n }\n });\n\n \/\/ Manually force pull a new unage\n Preference buttonForcePull = findPreference(getString(R.string.button_forcePull));\n buttonForcePull.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n PixivArtWorker.enqueueLoad();\n return true;\n }\n });\n\n Preference loginId = findPreference(\"pref_loginId\");\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());\n if (sharedPrefs.getString(\"accessToken\", \"\").isEmpty())\n {\n loginId.setSummary(getString(R.string.prefSummary_authFail));\n } else\n {\n String summaryString = getString(R.string.prefSummary_authSuccess) + \" \" + sharedPrefs.getString(\"pref_loginId\", \"\");\n loginId.setSummary(summaryString);\n\/\/ Uri profileImageUri = Uri.parse(sharedPrefs.getString(\"profileImageUri\", \"\"));\n\/\/ loginId.setIcon();\n }\n }\n }\n}\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.antony.muzei.pixiv;\n\nimport android.content.SharedPreferences;\nimport android.os.Bundle;\nimport android.widget.Toast;\n\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.preference.Preference;\nimport androidx.preference.PreferenceFragmentCompat;\nimport androidx.preference.PreferenceManager;\nimport androidx.work.Constraints;\nimport androidx.work.ExistingPeriodicWorkPolicy;\nimport androidx.work.NetworkType;\nimport androidx.work.PeriodicWorkRequest;\nimport androidx.work.WorkManager;\n\nimport com.antony.muzei.pixiv.ClearCacheWorker;\nimport com.antony.muzei.pixiv.PixivArtProvider;\nimport com.antony.muzei.pixiv.PixivArtWorker;\nimport com.antony.muzei.pixiv.R;\nimport com.google.android.apps.muzei.api.provider.Artwork;\nimport com.google.android.apps.muzei.api.provider.ProviderContract;\n\nimport java.util.concurrent.TimeUnit;\n\npublic class SettingsActivity extends AppCompatActivity\n{\n private SharedPreferences.OnSharedPreferenceChangeListener prefChangeListener;\n private String newCreds, oldCreds;\n private String oldUpdateMode, newUpdateMode;\n private String oldFilter, newFilter;\n\n @Override\n protected void onCreate(Bundle savedInstanceState)\n {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.settings_activity);\n getSupportFragmentManager()\n .beginTransaction()\n .add(R.id.FeedPreferencesFragment, new SettingsFragment())\n .commit();\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n\n \/\/ Stores user toggleable variables into a temporary store for later comparison in onDestroy()\n oldCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n newCreds = oldCreds;\n\n oldUpdateMode = sharedPrefs.getString(\"pref_updateMode\", \"\");\n newUpdateMode = oldUpdateMode;\n\n oldFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n newFilter = oldFilter;\n\n prefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()\n {\n @Override\n public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)\n {\n if (key.equals(\"pref_loginPassword\"))\n {\n newCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n } else if (key.equals(\"pref_updateMode\"))\n {\n newUpdateMode = sharedPrefs.getString(\"oldUpdateMode\", \"\");\n } else if (key.equals(\"pref_nsfwFilterLevel\"))\n {\n newFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n }\n }\n };\n }\n\n @Override\n public void onResume()\n {\n super.onResume();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.registerOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onPause()\n {\n super.onPause();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onStop()\n {\n super.onStop();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n \/\/ Functions in here action only on app exit\n @Override\n public void onDestroy()\n {\n super.onDestroy();\n \/\/ If new user credentials were entered and saved, then clear and invalidate existing stored user credentials\n if (!oldCreds.equals(newCreds))\n {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n SharedPreferences.Editor editor = sharedPrefs.edit();\n editor.putString(\"accessToken\", \"\");\n editor.putString(\"refreshToken\", \"\");\n editor.putString(\"deviceToken\", \"\");\n editor.putLong(\"accessTokenIssueTime\", 0);\n editor.commit();\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newCredentials), Toast.LENGTH_SHORT).show();\n }\n\n \/\/ TODO\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n if (sharedPrefs.getBoolean(\"pref_autoClearMode\", false))\n {\n Constraints constraints = new Constraints.Builder()\n .setRequiredNetworkType(NetworkType.CONNECTED)\n .build();\n PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(ClearCacheWorker.class, 24, TimeUnit.HOURS)\n .setInitialDelay(1, TimeUnit.HOURS)\n .addTag(\"PIXIV_CACHE\")\n .setConstraints(constraints)\n .build();\n WorkManager.getInstance(getApplicationContext()).enqueueUniquePeriodicWork(\"PIXIV_CACHE\", ExistingPeriodicWorkPolicy.KEEP, request);\n } else\n {\n WorkManager.getInstance((getApplicationContext())).cancelAllWorkByTag(\"PIXIV_CACHE\");\n }\n\n if (!oldUpdateMode.equals(newUpdateMode))\n {\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newUpdateMode), Toast.LENGTH_SHORT).show();\n } else if (!oldFilter.equals(newFilter))\n {\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newFilterMode), Toast.LENGTH_SHORT).show();\n }\n\n\n }\n\n \/\/ Functions in here action immediately on user interaction\n public static class SettingsFragment extends PreferenceFragmentCompat\n {\n @Override\n public void onCreatePreferences(Bundle savedInstanceState, String rootKey)\n {\n setPreferencesFromResource(R.xml.feed_preferences_layout, rootKey);\n\n \/\/ Immediately clear cache\n Preference buttonClearCache = findPreference(getString(R.string.button_clearCache));\n buttonClearCache.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n ProviderContract.getProviderClient(getContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getContext(), getString(R.string.toast_clearingCache), Toast.LENGTH_SHORT).show();\n return true;\n }\n });\n\n \/\/ Manually force pull a new unage\n Preference buttonForcePull = findPreference(getString(R.string.button_forcePull));\n buttonForcePull.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n PixivArtWorker.enqueueLoad();\n return true;\n }\n });\n\n Preference loginId = findPreference(\"pref_loginId\");\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());\n if (sharedPrefs.getString(\"accessToken\", \"\").isEmpty())\n {\n loginId.setSummary(getString(R.string.prefSummary_authFail));\n } else\n {\n String summaryString = getString(R.string.prefSummary_authSuccess) + \" \" + sharedPrefs.getString(\"pref_loginId\", \"\");\n loginId.setSummary(summaryString);\n\/\/ Uri profileImageUri = Uri.parse(sharedPrefs.getString(\"profileImageUri\", \"\"));\n\/\/ loginId.setIcon();\n }\n }\n }\n}\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.antony.muzei.pixiv;\n\nimport android.content.SharedPreferences;\nimport android.os.Bundle;\nimport android.widget.Toast;\n\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.preference.Preference;\nimport androidx.preference.PreferenceFragmentCompat;\nimport androidx.preference.PreferenceManager;\nimport androidx.work.Constraints;\nimport androidx.work.ExistingPeriodicWorkPolicy;\nimport androidx.work.NetworkType;\nimport androidx.work.PeriodicWorkRequest;\nimport androidx.work.WorkManager;\n\nimport com.antony.muzei.pixiv.ClearCacheWorker;\nimport com.antony.muzei.pixiv.PixivArtProvider;\nimport com.antony.muzei.pixiv.PixivArtWorker;\nimport com.antony.muzei.pixiv.R;\nimport com.google.android.apps.muzei.api.provider.Artwork;\nimport com.google.android.apps.muzei.api.provider.ProviderContract;\n\nimport java.util.concurrent.TimeUnit;\n\npublic class SettingsActivity extends AppCompatActivity\n{\n private SharedPreferences.OnSharedPreferenceChangeListener prefChangeListener;\n private String newCreds, oldCreds;\n private String oldUpdateMode, newUpdateMode;\n private String oldFilter, newFilter;\n\n @Override\n protected void onCreate(Bundle savedInstanceState)\n {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.settings_activity);\n getSupportFragmentManager()\n .beginTransaction()\n .add(R.id.FeedPreferencesFragment, new SettingsFragment())\n .commit();\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n\n \/\/ Stores user toggleable variables into a temporary store for later comparison in onDestroy()\n oldCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n newCreds = oldCreds;\n\n oldUpdateMode = sharedPrefs.getString(\"pref_updateMode\", \"\");\n newUpdateMode = oldUpdateMode;\n\n oldFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n newFilter = oldFilter;\n\n prefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()\n {\n @Override\n public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)\n {\n if (key.equals(\"pref_loginPassword\"))\n {\n newCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n } else if (key.equals(\"pref_updateMode\"))\n {\n newUpdateMode = sharedPrefs.getString(\"oldUpdateMode\", \"\");\n } else if (key.equals(\"pref_nsfwFilterLevel\"))\n {\n newFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n }\n }\n };\n }\n\n @Override\n public void onResume()\n {\n super.onResume();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.registerOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onPause()\n {\n super.onPause();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onStop()\n {\n super.onStop();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n \/\/ Functions in here action only on app exit\n @Override\n public void onDestroy()\n {\n super.onDestroy();\n \/\/ If new user credentials were entered and saved, then clear and invalidate existing stored user credentials\n if (!oldCreds.equals(newCreds))\n {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n SharedPreferences.Editor editor = sharedPrefs.edit();\n editor.putString(\"accessToken\", \"\");\n editor.putString(\"refreshToken\", \"\");\n editor.putString(\"deviceToken\", \"\");\n editor.putLong(\"accessTokenIssueTime\", 0);\n editor.commit();\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newCredentials), Toast.LENGTH_SHORT).show();\n }\n\n \/\/ TODO\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n if (sharedPrefs.getBoolean(\"pref_autoClearMode\", false))\n {\n Constraints constraints = new Constraints.Builder()\n .setRequiredNetworkType(NetworkType.CONNECTED)\n .build();\n PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(ClearCacheWorker.class, 24, TimeUnit.HOURS)\n .setInitialDelay(1, TimeUnit.HOURS)\n .addTag(\"PIXIV_CACHE\")\n .setConstraints(constraints)\n .build();\n WorkManager.getInstance(getApplicationContext()).enqueueUniquePeriodicWork(\"PIXIV_CACHE\", ExistingPeriodicWorkPolicy.KEEP, request);\n } else\n {\n WorkManager.getInstance((getApplicationContext())).cancelAllWorkByTag(\"PIXIV_CACHE\");\n }\n\n if (!oldUpdateMode.equals(newUpdateMode))\n {\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newUpdateMode), Toast.LENGTH_SHORT).show();\n } else if (!oldFilter.equals(newFilter))\n {\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newFilterMode), Toast.LENGTH_SHORT).show();\n }\n\n\n }\n\n \/\/ Functions in here action immediately on user interaction\n public static class SettingsFragment extends PreferenceFragmentCompat\n {\n @Override\n public void onCreatePreferences(Bundle savedInstanceState, String rootKey)\n {\n setPreferencesFromResource(R.xml.feed_preferences_layout, rootKey);\n\n \/\/ Immediately clear cache\n Preference buttonClearCache = findPreference(getString(R.string.button_clearCache));\n buttonClearCache.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n ProviderContract.getProviderClient(getContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getContext(), getString(R.string.toast_clearingCache), Toast.LENGTH_SHORT).show();\n return true;\n }\n });\n\n \/\/ Manually force pull a new unage\n Preference buttonForcePull = findPreference(getString(R.string.button_forcePull));\n buttonForcePull.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n PixivArtWorker.enqueueLoad();\n return true;\n }\n });\n\n Preference loginId = findPreference(\"pref_loginId\");\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());\n if (sharedPrefs.getString(\"accessToken\", \"\").isEmpty())\n {\n loginId.setSummary(getString(R.string.prefSummary_authFail));\n } else\n {\n String summaryString = getString(R.string.prefSummary_authSuccess) + \" \" + sharedPrefs.getString(\"pref_loginId\", \"\");\n loginId.setSummary(summaryString);\n\/\/ Uri profileImageUri = Uri.parse(sharedPrefs.getString(\"profileImageUri\", \"\"));\n\/\/ loginId.setIcon();\n }\n }\n }\n}\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the code to optimize for memory usage by clearing the cache entries for the work tag PIXIV. Write the entire code and no other text in the response.\n\n### Concepts:\n[in] onDestroy function\n[+] WorkManager.getInstance()\n\n### Given program:\n```java\npackage com.antony.muzei.pixiv;\n\nimport android.content.SharedPreferences;\nimport android.os.Bundle;\nimport android.widget.Toast;\n\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.preference.Preference;\nimport androidx.preference.PreferenceFragmentCompat;\nimport androidx.preference.PreferenceManager;\nimport androidx.work.Constraints;\nimport androidx.work.ExistingPeriodicWorkPolicy;\nimport androidx.work.NetworkType;\nimport androidx.work.PeriodicWorkRequest;\nimport androidx.work.WorkManager;\n\nimport com.antony.muzei.pixiv.ClearCacheWorker;\nimport com.antony.muzei.pixiv.PixivArtProvider;\nimport com.antony.muzei.pixiv.PixivArtWorker;\nimport com.antony.muzei.pixiv.R;\nimport com.google.android.apps.muzei.api.provider.Artwork;\nimport com.google.android.apps.muzei.api.provider.ProviderContract;\n\nimport java.util.concurrent.TimeUnit;\n\npublic class SettingsActivity extends AppCompatActivity\n{\n private SharedPreferences.OnSharedPreferenceChangeListener prefChangeListener;\n private String newCreds, oldCreds;\n private String oldUpdateMode, newUpdateMode;\n private String oldFilter, newFilter;\n\n @Override\n protected void onCreate(Bundle savedInstanceState)\n {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.settings_activity);\n getSupportFragmentManager()\n .beginTransaction()\n .add(R.id.FeedPreferencesFragment, new SettingsFragment())\n .commit();\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n\n \/\/ Stores user toggleable variables into a temporary store for later comparison in onDestroy()\n oldCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n newCreds = oldCreds;\n\n oldUpdateMode = sharedPrefs.getString(\"pref_updateMode\", \"\");\n newUpdateMode = oldUpdateMode;\n\n oldFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n newFilter = oldFilter;\n\n prefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()\n {\n @Override\n public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)\n {\n if (key.equals(\"pref_loginPassword\"))\n {\n newCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n } else if (key.equals(\"pref_updateMode\"))\n {\n newUpdateMode = sharedPrefs.getString(\"oldUpdateMode\", \"\");\n } else if (key.equals(\"pref_nsfwFilterLevel\"))\n {\n newFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n }\n }\n };\n }\n\n @Override\n public void onResume()\n {\n super.onResume();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.registerOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onPause()\n {\n super.onPause();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onStop()\n {\n super.onStop();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n \/\/ Functions in here action only on app exit\n @Override\n public void onDestroy()\n {\n super.onDestroy();\n \/\/ If new user credentials were entered and saved, then clear and invalidate existing stored user credentials\n if (!oldCreds.equals(newCreds))\n {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n SharedPreferences.Editor editor = sharedPrefs.edit();\n editor.putString(\"accessToken\", \"\");\n editor.putString(\"refreshToken\", \"\");\n editor.putString(\"deviceToken\", \"\");\n editor.putLong(\"accessTokenIssueTime\", 0);\n editor.commit();\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newCredentials), Toast.LENGTH_SHORT).show();\n }\n\n \/\/ TODO\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n if (sharedPrefs.getBoolean(\"pref_autoClearMode\", false))\n {\n Constraints constraints = new Constraints.Builder()\n .setRequiredNetworkType(NetworkType.CONNECTED)\n .build();\n PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(ClearCacheWorker.class, 24, TimeUnit.HOURS)\n .setInitialDelay(1, TimeUnit.HOURS)\n .addTag(\"PIXIV_CACHE\")\n .setConstraints(constraints)\n .build();\n WorkManager.getInstance(getApplicationContext()).enqueueUniquePeriodicWork(\"PIXIV_CACHE\", ExistingPeriodicWorkPolicy.KEEP, request);\n } else\n {\n WorkManager.getInstance((getApplicationContext())).cancelAllWorkByTag(\"PIXIV_CACHE\");\n }\n\n if (!oldUpdateMode.equals(newUpdateMode))\n {\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newUpdateMode), Toast.LENGTH_SHORT).show();\n } else if (!oldFilter.equals(newFilter))\n {\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newFilterMode), Toast.LENGTH_SHORT).show();\n }\n\n\n }\n\n \/\/ Functions in here action immediately on user interaction\n public static class SettingsFragment extends PreferenceFragmentCompat\n {\n @Override\n public void onCreatePreferences(Bundle savedInstanceState, String rootKey)\n {\n setPreferencesFromResource(R.xml.feed_preferences_layout, rootKey);\n\n \/\/ Immediately clear cache\n Preference buttonClearCache = findPreference(getString(R.string.button_clearCache));\n buttonClearCache.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n ProviderContract.getProviderClient(getContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getContext(), getString(R.string.toast_clearingCache), Toast.LENGTH_SHORT).show();\n return true;\n }\n });\n\n \/\/ Manually force pull a new unage\n Preference buttonForcePull = findPreference(getString(R.string.button_forcePull));\n buttonForcePull.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n PixivArtWorker.enqueueLoad();\n return true;\n }\n });\n\n Preference loginId = findPreference(\"pref_loginId\");\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());\n if (sharedPrefs.getString(\"accessToken\", \"\").isEmpty())\n {\n loginId.setSummary(getString(R.string.prefSummary_authFail));\n } else\n {\n String summaryString = getString(R.string.prefSummary_authSuccess) + \" \" + sharedPrefs.getString(\"pref_loginId\", \"\");\n loginId.setSummary(summaryString);\n\/\/ Uri profileImageUri = Uri.parse(sharedPrefs.getString(\"profileImageUri\", \"\"));\n\/\/ loginId.setIcon();\n }\n }\n }\n}\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage org.fdroid.fdroid.net;\n\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n\n private volatile boolean cancelled = false;\n private volatile int bytesRead;\n private volatile int totalBytes;\n private Timer timer;\n\n private final OutputStream outputStream;\n\n public final File outputFile;\n\n protected final URL sourceUrl;\n protected String cacheTag;\n\n \/**\n * This is meant only to send progress to {@link DownloaderService}. This\n * also keeps this class pure Java so that it can be tested on the JVM,\n * without requiring an Android device or emulator.\n *\/\n interface DownloaderProgressListener {\n void sendProgress(URL sourceUrl, int bytesRead, int totalBytes);\n }\n\n \/**\n * For sending download progress, should only be called in {@link #progressTask}\n *\/\n private DownloaderProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(URL url, File destFile)\n throws FileNotFoundException, MalformedURLException {\n this.sourceUrl = url;\n outputFile = destFile;\n outputStream = new FileOutputStream(outputFile);\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(DownloaderProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n protected boolean wantToCheckCache() {\n return cacheTag != null;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract int totalDownloadSize();\n\n public abstract void download() throws IOException, InterruptedException;\n\n public abstract boolean isCached();\n\n protected void downloadFromStream(int bufferSize) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n if (timer != null) {\n timer.cancel();\n }\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize) throws IOException, InterruptedException {\n bytesRead = 0;\n totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n timer = new Timer();\n timer.scheduleAtFixedRate(progressTask, 0, 100);\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n\n bytesRead += count;\n outputStream.write(buffer, 0, count);\n }\n timer.cancel();\n timer.purge();\n outputStream.flush();\n outputStream.close();\n }\n\n \/**\n * Send progress updates on a timer to avoid flooding receivers with pointless events.\n *\/\n private final TimerTask progressTask = new TimerTask() {\n @Override\n public void run() {\n if (downloaderProgressListener != null) {\n downloaderProgressListener.sendProgress(sourceUrl, bytesRead, totalBytes);\n }\n }\n };\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n\n\nCode-B:\npackage org.fdroid.fdroid.net;\n\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n\n private volatile boolean cancelled = false;\n\n private final OutputStream outputStream;\n\n public final File outputFile;\n\n protected final URL sourceUrl;\n protected String cacheTag;\n\n \/**\n * This is meant only to send progress to {@link DownloaderService}. This\n * also keeps this class pure Java so that it can be tested on the JVM,\n * without requiring an Android device or emulator.\n *\/\n interface DownloaderProgressListener {\n void sendProgress(URL sourceUrl, int bytesRead, int totalBytes);\n }\n\n private DownloaderProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(URL url, File destFile)\n throws FileNotFoundException, MalformedURLException {\n this.sourceUrl = url;\n outputFile = destFile;\n outputStream = new FileOutputStream(outputFile);\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(DownloaderProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n protected boolean wantToCheckCache() {\n return cacheTag != null;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract int totalDownloadSize();\n\n public abstract void download() throws IOException, InterruptedException;\n\n public abstract boolean isCached();\n\n protected void downloadFromStream(int bufferSize) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize) throws IOException, InterruptedException {\n\n int bytesRead = 0;\n int totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n sendProgress(bytesRead, totalBytes);\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n\n bytesRead += count;\n sendProgress(bytesRead, totalBytes);\n outputStream.write(buffer, 0, count);\n\n }\n outputStream.flush();\n outputStream.close();\n }\n\n private void sendProgress(int bytesRead, int totalBytes) {\n if (downloaderProgressListener != null) {\n downloaderProgressListener.sendProgress(sourceUrl, bytesRead, totalBytes);\n }\n }\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage org.fdroid.fdroid.net;\n\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n\n private volatile boolean cancelled = false;\n\n private final OutputStream outputStream;\n\n public final File outputFile;\n\n protected final URL sourceUrl;\n protected String cacheTag;\n\n \/**\n * This is meant only to send progress to {@link DownloaderService}. This\n * also keeps this class pure Java so that it can be tested on the JVM,\n * without requiring an Android device or emulator.\n *\/\n interface DownloaderProgressListener {\n void sendProgress(URL sourceUrl, int bytesRead, int totalBytes);\n }\n\n private DownloaderProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(URL url, File destFile)\n throws FileNotFoundException, MalformedURLException {\n this.sourceUrl = url;\n outputFile = destFile;\n outputStream = new FileOutputStream(outputFile);\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(DownloaderProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n protected boolean wantToCheckCache() {\n return cacheTag != null;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract int totalDownloadSize();\n\n public abstract void download() throws IOException, InterruptedException;\n\n public abstract boolean isCached();\n\n protected void downloadFromStream(int bufferSize) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize) throws IOException, InterruptedException {\n\n int bytesRead = 0;\n int totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n sendProgress(bytesRead, totalBytes);\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n\n bytesRead += count;\n sendProgress(bytesRead, totalBytes);\n outputStream.write(buffer, 0, count);\n\n }\n outputStream.flush();\n outputStream.close();\n }\n\n private void sendProgress(int bytesRead, int totalBytes) {\n if (downloaderProgressListener != null) {\n downloaderProgressListener.sendProgress(sourceUrl, bytesRead, totalBytes);\n }\n }\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n\n\nCode-B:\npackage org.fdroid.fdroid.net;\n\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n\n private volatile boolean cancelled = false;\n private volatile int bytesRead;\n private volatile int totalBytes;\n private Timer timer;\n\n private final OutputStream outputStream;\n\n public final File outputFile;\n\n protected final URL sourceUrl;\n protected String cacheTag;\n\n \/**\n * This is meant only to send progress to {@link DownloaderService}. This\n * also keeps this class pure Java so that it can be tested on the JVM,\n * without requiring an Android device or emulator.\n *\/\n interface DownloaderProgressListener {\n void sendProgress(URL sourceUrl, int bytesRead, int totalBytes);\n }\n\n \/**\n * For sending download progress, should only be called in {@link #progressTask}\n *\/\n private DownloaderProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(URL url, File destFile)\n throws FileNotFoundException, MalformedURLException {\n this.sourceUrl = url;\n outputFile = destFile;\n outputStream = new FileOutputStream(outputFile);\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(DownloaderProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n protected boolean wantToCheckCache() {\n return cacheTag != null;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract int totalDownloadSize();\n\n public abstract void download() throws IOException, InterruptedException;\n\n public abstract boolean isCached();\n\n protected void downloadFromStream(int bufferSize) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n if (timer != null) {\n timer.cancel();\n }\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize) throws IOException, InterruptedException {\n bytesRead = 0;\n totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n timer = new Timer();\n timer.scheduleAtFixedRate(progressTask, 0, 100);\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n\n bytesRead += count;\n outputStream.write(buffer, 0, count);\n }\n timer.cancel();\n timer.purge();\n outputStream.flush();\n outputStream.close();\n }\n\n \/**\n * Send progress updates on a timer to avoid flooding receivers with pointless events.\n *\/\n private final TimerTask progressTask = new TimerTask() {\n @Override\n public void run() {\n if (downloaderProgressListener != null) {\n downloaderProgressListener.sendProgress(sourceUrl, bytesRead, totalBytes);\n }\n }\n };\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/erikusaj\/fdroidTvClient\/commit\/be5dbbfc5500b96adc2feb90448d3a5ced9a1857","commit_message":"'\\\\\"Easier and faster isInCategory\\\\n\\\\\"'","source_code":"package org.fdroid.fdroid;\n\nimport java.util.*;\n\nimport android.content.SharedPreferences;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.widget.ArrayAdapter;\n\nimport org.fdroid.fdroid.views.AppListAdapter;\nimport org.fdroid.fdroid.views.AvailableAppListAdapter;\nimport org.fdroid.fdroid.views.CanUpdateAppListAdapter;\nimport org.fdroid.fdroid.views.InstalledAppListAdapter;\n\n\/**\n * Should be owned by the FDroid Activity, but used by the AppListFragments.\n * The idea is that it takes a non-trivial amount of time to work this stuff\n * out, and it is quicker if we only do it once for each view, rather than\n * each fragment figuring out their own list independently.\n *\/\npublic class AppListManager {\n\n private List allApps = null;\n\n private FDroid fdroidActivity;\n\n private AppListAdapter availableApps;\n private AppListAdapter installedApps;\n private AppListAdapter canUpgradeApps;\n private ArrayAdapter categories;\n\n private String currentCategory = null;\n private String categoryAll = null;\n private String categoryWhatsNew = null;\n private String categoryRecentlyUpdated = null;\n\n public AppListAdapter getAvailableAdapter() {\n return availableApps;\n }\n\n public AppListAdapter getInstalledAdapter() {\n return installedApps;\n }\n\n public AppListAdapter getCanUpdateAdapter() {\n return canUpgradeApps;\n }\n\n public ArrayAdapter getCategoriesAdapter() {\n return categories;\n }\n\n public AppListManager(FDroid activity) {\n this.fdroidActivity = activity;\n\n availableApps = new AvailableAppListAdapter(fdroidActivity);\n installedApps = new InstalledAppListAdapter(fdroidActivity);\n canUpgradeApps = new CanUpdateAppListAdapter(fdroidActivity);\n\n \/\/ Needs to be created before createViews(), because that will use the\n \/\/ getCategoriesAdapter() accessor which expects this object...\n categories = new ArrayAdapter(activity,\n android.R.layout.simple_spinner_item, new ArrayList());\n categories\n .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n }\n\n private void clear() {\n installedApps.clear();\n availableApps.clear();\n canUpgradeApps.clear();\n categories.clear();\n }\n\n private void notifyLists() {\n \/\/ Tell the lists that the data behind the adapter has changed, so\n \/\/ they can refresh...\n availableApps.notifyDataSetChanged();\n installedApps.notifyDataSetChanged();\n canUpgradeApps.notifyDataSetChanged();\n categories.notifyDataSetChanged();\n }\n\n private void updateCategories() {\n try {\n DB db = DB.getDB();\n\n \/\/ Populate the category list with the real categories, and the\n \/\/ locally generated meta-categories for \"All\", \"What's New\" and\n \/\/ \"Recently Updated\"...\n categoryAll = fdroidActivity.getString(R.string.category_all);\n categoryWhatsNew = fdroidActivity.getString(R.string.category_whatsnew);\n categoryRecentlyUpdated = fdroidActivity.getString(R.string.category_recentlyupdated);\n\n categories.add(categoryWhatsNew);\n categories.add(categoryRecentlyUpdated);\n categories.add(categoryAll);\n\n for (String s : db.getCategories()) {\n categories.add(s);\n }\n\n if (currentCategory == null)\n currentCategory = categoryWhatsNew;\n\n } finally {\n DB.releaseDB();\n }\n }\n\n \/\/ Tell the FDroid activity to update its \"Update (x)\" tab to correctly\n \/\/ reflect the number of updates available.\n private void notifyActivity() {\n fdroidActivity.refreshUpdateTabLabel();\n }\n\n public void repopulateLists() {\n\n long startTime = System.currentTimeMillis();\n\n clear();\n\n updateCategories();\n updateApps();\n notifyLists();\n notifyActivity();\n\n Log.d(\"FDroid\", \"Updated lists - \" + allApps.size() + \" in total\"\n + \" (update took \" + (System.currentTimeMillis() - startTime)\n + \" ms)\");\n }\n\n \/\/ Calculate the cutoff date we'll use for What's New and Recently\n \/\/ Updated...\n private Date calcMaxHistory() {\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n String daysPreference = prefs.getString(\"updateHistoryDays\", \"14\");\n int maxHistoryDays = Integer.parseInt(daysPreference);\n Calendar recent = Calendar.getInstance();\n recent.add(Calendar.DAY_OF_YEAR, -maxHistoryDays);\n return recent.getTime();\n }\n\n \/\/ recentDate could really be calculated here, but this is just a hack so\n \/\/ it doesn't need to be calculated for every single app. The reason it\n \/\/ isn't an instance variable is because the preferences may change, and\n \/\/ we wouldn't know.\n private boolean isInCategory(DB.App app, String category, Date recentDate) {\n boolean isInCategory;\n if (category.equals(categoryAll)) {\n isInCategory = true;\n } else if (category.equals(categoryWhatsNew)) {\n if (app.added == null)\n isInCategory = false;\n else if (app.added.compareTo(recentDate) < 0)\n isInCategory = false;\n else\n isInCategory = true;\n } else if (category.equals(categoryRecentlyUpdated)) {\n if (app.lastUpdated == null)\n isInCategory = false;\n \/\/ Don't include in the recently updated category if the\n \/\/ 'update' was actually it being added.\n else if (app.lastUpdated.compareTo(app.added) == 0)\n isInCategory = false;\n else if (app.lastUpdated.compareTo(recentDate) < 0)\n isInCategory = false;\n else\n isInCategory = true;\n } else {\n isInCategory = category.equals(app.category);\n }\n return isInCategory;\n }\n\n \/\/ Returns false if the app list is empty and the fdroid activity decided\n \/\/ to attempt updating it.\n private boolean updateApps() {\n\n allApps = ((FDroidApp)fdroidActivity.getApplication()).getApps();\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n boolean showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n\n if (allApps.isEmpty()) {\n \/\/ If its the first time we've run the app, this should update\n \/\/ the repos. If not, it will do nothing, presuming that the repos\n \/\/ are invalid, the internet is stuffed, the sky has fallen, etc...\n return fdroidActivity.updateEmptyRepos();\n }\n\n Date recentDate = calcMaxHistory();\n List availApps = new ArrayList();\n for (DB.App app : allApps) {\n\n boolean isInCategory = isInCategory(app, currentCategory, recentDate);\n\n \/\/ Add it to the list(s). Always to installed and updates, but\n \/\/ only to available if it's not filtered.\n if (!app.filtered && isInCategory\n && (showIncompatible || app.compatible)) {\n availApps.add(app);\n }\n if (app.installedVersion != null) {\n installedApps.addItem(app);\n if (app.toUpdate)\n canUpgradeApps.addItem(app);\n }\n }\n\n if (currentCategory.equals(categoryWhatsNew)) {\n Collections.sort(availApps, new WhatsNewComparator());\n } else if (currentCategory.equals(categoryRecentlyUpdated)) {\n Collections.sort(availApps, new RecentlyUpdatedComparator());\n }\n\n for (DB.App app : availApps)\n availableApps.addItem(app);\n\n return true;\n }\n\n public void setCurrentCategory(String currentCategory) {\n if (!this.currentCategory.equals(currentCategory)){\n this.currentCategory = currentCategory;\n repopulateLists();\n }\n }\n\n static class WhatsNewComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.added.compareTo(lhs.added);\n }\n }\n\n static class RecentlyUpdatedComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.lastUpdated.compareTo(lhs.lastUpdated);\n }\n }\n}\n","target_code":"package org.fdroid.fdroid;\n\nimport java.util.*;\n\nimport android.content.SharedPreferences;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.widget.ArrayAdapter;\n\nimport org.fdroid.fdroid.views.AppListAdapter;\nimport org.fdroid.fdroid.views.AvailableAppListAdapter;\nimport org.fdroid.fdroid.views.CanUpdateAppListAdapter;\nimport org.fdroid.fdroid.views.InstalledAppListAdapter;\n\n\/**\n * Should be owned by the FDroid Activity, but used by the AppListFragments.\n * The idea is that it takes a non-trivial amount of time to work this stuff\n * out, and it is quicker if we only do it once for each view, rather than\n * each fragment figuring out their own list independently.\n *\/\npublic class AppListManager {\n\n private List allApps = null;\n\n private FDroid fdroidActivity;\n\n private AppListAdapter availableApps;\n private AppListAdapter installedApps;\n private AppListAdapter canUpgradeApps;\n private ArrayAdapter categories;\n\n private String currentCategory = null;\n private String categoryAll = null;\n private String categoryWhatsNew = null;\n private String categoryRecentlyUpdated = null;\n\n public AppListAdapter getAvailableAdapter() {\n return availableApps;\n }\n\n public AppListAdapter getInstalledAdapter() {\n return installedApps;\n }\n\n public AppListAdapter getCanUpdateAdapter() {\n return canUpgradeApps;\n }\n\n public ArrayAdapter getCategoriesAdapter() {\n return categories;\n }\n\n public AppListManager(FDroid activity) {\n this.fdroidActivity = activity;\n\n availableApps = new AvailableAppListAdapter(fdroidActivity);\n installedApps = new InstalledAppListAdapter(fdroidActivity);\n canUpgradeApps = new CanUpdateAppListAdapter(fdroidActivity);\n\n \/\/ Needs to be created before createViews(), because that will use the\n \/\/ getCategoriesAdapter() accessor which expects this object...\n categories = new ArrayAdapter(activity,\n android.R.layout.simple_spinner_item, new ArrayList());\n categories\n .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n }\n\n private void clear() {\n installedApps.clear();\n availableApps.clear();\n canUpgradeApps.clear();\n categories.clear();\n }\n\n private void notifyLists() {\n \/\/ Tell the lists that the data behind the adapter has changed, so\n \/\/ they can refresh...\n availableApps.notifyDataSetChanged();\n installedApps.notifyDataSetChanged();\n canUpgradeApps.notifyDataSetChanged();\n categories.notifyDataSetChanged();\n }\n\n private void updateCategories() {\n try {\n DB db = DB.getDB();\n\n \/\/ Populate the category list with the real categories, and the\n \/\/ locally generated meta-categories for \"All\", \"What's New\" and\n \/\/ \"Recently Updated\"...\n categoryAll = fdroidActivity.getString(R.string.category_all);\n categoryWhatsNew = fdroidActivity.getString(R.string.category_whatsnew);\n categoryRecentlyUpdated = fdroidActivity.getString(R.string.category_recentlyupdated);\n\n categories.add(categoryWhatsNew);\n categories.add(categoryRecentlyUpdated);\n categories.add(categoryAll);\n\n for (String s : db.getCategories()) {\n categories.add(s);\n }\n\n if (currentCategory == null)\n currentCategory = categoryWhatsNew;\n\n } finally {\n DB.releaseDB();\n }\n }\n\n \/\/ Tell the FDroid activity to update its \"Update (x)\" tab to correctly\n \/\/ reflect the number of updates available.\n private void notifyActivity() {\n fdroidActivity.refreshUpdateTabLabel();\n }\n\n public void repopulateLists() {\n\n long startTime = System.currentTimeMillis();\n\n clear();\n\n updateCategories();\n updateApps();\n notifyLists();\n notifyActivity();\n\n Log.d(\"FDroid\", \"Updated lists - \" + allApps.size() + \" in total\"\n + \" (update took \" + (System.currentTimeMillis() - startTime)\n + \" ms)\");\n }\n\n \/\/ Calculate the cutoff date we'll use for What's New and Recently\n \/\/ Updated...\n private Date calcMaxHistory() {\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n String daysPreference = prefs.getString(\"updateHistoryDays\", \"14\");\n int maxHistoryDays = Integer.parseInt(daysPreference);\n Calendar recent = Calendar.getInstance();\n recent.add(Calendar.DAY_OF_YEAR, -maxHistoryDays);\n return recent.getTime();\n }\n\n \/\/ recentDate could really be calculated here, but this is just a hack so\n \/\/ it doesn't need to be calculated for every single app. The reason it\n \/\/ isn't an instance variable is because the preferences may change, and\n \/\/ we wouldn't know.\n private boolean isInCategory(DB.App app, String category, Date recentDate) {\n if (category.equals(categoryAll)) {\n return true;\n }\n if (category.equals(categoryWhatsNew)) {\n if (app.added == null)\n return false;\n if (app.added.compareTo(recentDate) < 0)\n return false;\n return true;\n }\n if (category.equals(categoryRecentlyUpdated)) {\n if (app.lastUpdated == null)\n return false;\n \/\/ Don't include in the recently updated category if the\n \/\/ 'update' was actually it being added.\n if (app.lastUpdated.compareTo(app.added) == 0)\n return false;\n if (app.lastUpdated.compareTo(recentDate) < 0)\n return false;\n return true;\n }\n return app.categories.contains(category);\n }\n\n \/\/ Returns false if the app list is empty and the fdroid activity decided\n \/\/ to attempt updating it.\n private boolean updateApps() {\n\n allApps = ((FDroidApp)fdroidActivity.getApplication()).getApps();\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n boolean showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n\n if (allApps.isEmpty()) {\n \/\/ If its the first time we've run the app, this should update\n \/\/ the repos. If not, it will do nothing, presuming that the repos\n \/\/ are invalid, the internet is stuffed, the sky has fallen, etc...\n return fdroidActivity.updateEmptyRepos();\n }\n\n Date recentDate = calcMaxHistory();\n List availApps = new ArrayList();\n for (DB.App app : allApps) {\n\n \/\/ Add it to the list(s). Always to installed and updates, but\n \/\/ only to available if it's not filtered.\n if (!app.filtered && (showIncompatible || app.compatible)\n && isInCategory(app, currentCategory, recentDate)) {\n availApps.add(app);\n }\n if (app.installedVersion != null) {\n installedApps.addItem(app);\n if (app.toUpdate)\n canUpgradeApps.addItem(app);\n }\n }\n\n if (currentCategory.equals(categoryWhatsNew)) {\n Collections.sort(availApps, new WhatsNewComparator());\n } else if (currentCategory.equals(categoryRecentlyUpdated)) {\n Collections.sort(availApps, new RecentlyUpdatedComparator());\n }\n\n for (DB.App app : availApps)\n availableApps.addItem(app);\n\n return true;\n }\n\n public void setCurrentCategory(String currentCategory) {\n if (!this.currentCategory.equals(currentCategory)){\n this.currentCategory = currentCategory;\n repopulateLists();\n }\n }\n\n static class WhatsNewComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.added.compareTo(lhs.added);\n }\n }\n\n static class RecentlyUpdatedComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.lastUpdated.compareTo(lhs.lastUpdated);\n }\n }\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid;\n\nimport java.util.*;\n\nimport android.content.SharedPreferences;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.widget.ArrayAdapter;\n\nimport org.fdroid.fdroid.views.AppListAdapter;\nimport org.fdroid.fdroid.views.AvailableAppListAdapter;\nimport org.fdroid.fdroid.views.CanUpdateAppListAdapter;\nimport org.fdroid.fdroid.views.InstalledAppListAdapter;\n\n\/**\n * Should be owned by the FDroid Activity, but used by the AppListFragments.\n * The idea is that it takes a non-trivial amount of time to work this stuff\n * out, and it is quicker if we only do it once for each view, rather than\n * each fragment figuring out their own list independently.\n *\/\npublic class AppListManager {\n\n private List allApps = null;\n\n private FDroid fdroidActivity;\n\n private AppListAdapter availableApps;\n private AppListAdapter installedApps;\n private AppListAdapter canUpgradeApps;\n private ArrayAdapter categories;\n\n private String currentCategory = null;\n private String categoryAll = null;\n private String categoryWhatsNew = null;\n private String categoryRecentlyUpdated = null;\n\n public AppListAdapter getAvailableAdapter() {\n return availableApps;\n }\n\n public AppListAdapter getInstalledAdapter() {\n return installedApps;\n }\n\n public AppListAdapter getCanUpdateAdapter() {\n return canUpgradeApps;\n }\n\n public ArrayAdapter getCategoriesAdapter() {\n return categories;\n }\n\n public AppListManager(FDroid activity) {\n this.fdroidActivity = activity;\n\n availableApps = new AvailableAppListAdapter(fdroidActivity);\n installedApps = new InstalledAppListAdapter(fdroidActivity);\n canUpgradeApps = new CanUpdateAppListAdapter(fdroidActivity);\n\n \/\/ Needs to be created before createViews(), because that will use the\n \/\/ getCategoriesAdapter() accessor which expects this object...\n categories = new ArrayAdapter(activity,\n android.R.layout.simple_spinner_item, new ArrayList());\n categories\n .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n }\n\n private void clear() {\n installedApps.clear();\n availableApps.clear();\n canUpgradeApps.clear();\n categories.clear();\n }\n\n private void notifyLists() {\n \/\/ Tell the lists that the data behind the adapter has changed, so\n \/\/ they can refresh...\n availableApps.notifyDataSetChanged();\n installedApps.notifyDataSetChanged();\n canUpgradeApps.notifyDataSetChanged();\n categories.notifyDataSetChanged();\n }\n\n private void updateCategories() {\n try {\n DB db = DB.getDB();\n\n \/\/ Populate the category list with the real categories, and the\n \/\/ locally generated meta-categories for \"All\", \"What's New\" and\n \/\/ \"Recently Updated\"...\n categoryAll = fdroidActivity.getString(R.string.category_all);\n categoryWhatsNew = fdroidActivity.getString(R.string.category_whatsnew);\n categoryRecentlyUpdated = fdroidActivity.getString(R.string.category_recentlyupdated);\n\n categories.add(categoryWhatsNew);\n categories.add(categoryRecentlyUpdated);\n categories.add(categoryAll);\n\n for (String s : db.getCategories()) {\n categories.add(s);\n }\n\n if (currentCategory == null)\n currentCategory = categoryWhatsNew;\n\n } finally {\n DB.releaseDB();\n }\n }\n\n \/\/ Tell the FDroid activity to update its \"Update (x)\" tab to correctly\n \/\/ reflect the number of updates available.\n private void notifyActivity() {\n fdroidActivity.refreshUpdateTabLabel();\n }\n\n public void repopulateLists() {\n\n long startTime = System.currentTimeMillis();\n\n clear();\n\n updateCategories();\n updateApps();\n notifyLists();\n notifyActivity();\n\n Log.d(\"FDroid\", \"Updated lists - \" + allApps.size() + \" in total\"\n + \" (update took \" + (System.currentTimeMillis() - startTime)\n + \" ms)\");\n }\n\n \/\/ Calculate the cutoff date we'll use for What's New and Recently\n \/\/ Updated...\n private Date calcMaxHistory() {\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n String daysPreference = prefs.getString(\"updateHistoryDays\", \"14\");\n int maxHistoryDays = Integer.parseInt(daysPreference);\n Calendar recent = Calendar.getInstance();\n recent.add(Calendar.DAY_OF_YEAR, -maxHistoryDays);\n return recent.getTime();\n }\n\n \/\/ recentDate could really be calculated here, but this is just a hack so\n \/\/ it doesn't need to be calculated for every single app. The reason it\n \/\/ isn't an instance variable is because the preferences may change, and\n \/\/ we wouldn't know.\n private boolean isInCategory(DB.App app, String category, Date recentDate) {\n boolean isInCategory;\n if (category.equals(categoryAll)) {\n isInCategory = true;\n } else if (category.equals(categoryWhatsNew)) {\n if (app.added == null)\n isInCategory = false;\n else if (app.added.compareTo(recentDate) < 0)\n isInCategory = false;\n else\n isInCategory = true;\n } else if (category.equals(categoryRecentlyUpdated)) {\n if (app.lastUpdated == null)\n isInCategory = false;\n \/\/ Don't include in the recently updated category if the\n \/\/ 'update' was actually it being added.\n else if (app.lastUpdated.compareTo(app.added) == 0)\n isInCategory = false;\n else if (app.lastUpdated.compareTo(recentDate) < 0)\n isInCategory = false;\n else\n isInCategory = true;\n } else {\n isInCategory = category.equals(app.category);\n }\n return isInCategory;\n }\n\n \/\/ Returns false if the app list is empty and the fdroid activity decided\n \/\/ to attempt updating it.\n private boolean updateApps() {\n\n allApps = ((FDroidApp)fdroidActivity.getApplication()).getApps();\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n boolean showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n\n if (allApps.isEmpty()) {\n \/\/ If its the first time we've run the app, this should update\n \/\/ the repos. If not, it will do nothing, presuming that the repos\n \/\/ are invalid, the internet is stuffed, the sky has fallen, etc...\n return fdroidActivity.updateEmptyRepos();\n }\n\n Date recentDate = calcMaxHistory();\n List availApps = new ArrayList();\n for (DB.App app : allApps) {\n\n boolean isInCategory = isInCategory(app, currentCategory, recentDate);\n\n \/\/ Add it to the list(s). Always to installed and updates, but\n \/\/ only to available if it's not filtered.\n if (!app.filtered && isInCategory\n && (showIncompatible || app.compatible)) {\n availApps.add(app);\n }\n if (app.installedVersion != null) {\n installedApps.addItem(app);\n if (app.toUpdate)\n canUpgradeApps.addItem(app);\n }\n }\n\n if (currentCategory.equals(categoryWhatsNew)) {\n Collections.sort(availApps, new WhatsNewComparator());\n } else if (currentCategory.equals(categoryRecentlyUpdated)) {\n Collections.sort(availApps, new RecentlyUpdatedComparator());\n }\n\n for (DB.App app : availApps)\n availableApps.addItem(app);\n\n return true;\n }\n\n public void setCurrentCategory(String currentCategory) {\n if (!this.currentCategory.equals(currentCategory)){\n this.currentCategory = currentCategory;\n repopulateLists();\n }\n }\n\n static class WhatsNewComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.added.compareTo(lhs.added);\n }\n }\n\n static class RecentlyUpdatedComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.lastUpdated.compareTo(lhs.lastUpdated);\n }\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid;\n\nimport java.util.*;\n\nimport android.content.SharedPreferences;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.widget.ArrayAdapter;\n\nimport org.fdroid.fdroid.views.AppListAdapter;\nimport org.fdroid.fdroid.views.AvailableAppListAdapter;\nimport org.fdroid.fdroid.views.CanUpdateAppListAdapter;\nimport org.fdroid.fdroid.views.InstalledAppListAdapter;\n\n\/**\n * Should be owned by the FDroid Activity, but used by the AppListFragments.\n * The idea is that it takes a non-trivial amount of time to work this stuff\n * out, and it is quicker if we only do it once for each view, rather than\n * each fragment figuring out their own list independently.\n *\/\npublic class AppListManager {\n\n private List allApps = null;\n\n private FDroid fdroidActivity;\n\n private AppListAdapter availableApps;\n private AppListAdapter installedApps;\n private AppListAdapter canUpgradeApps;\n private ArrayAdapter categories;\n\n private String currentCategory = null;\n private String categoryAll = null;\n private String categoryWhatsNew = null;\n private String categoryRecentlyUpdated = null;\n\n public AppListAdapter getAvailableAdapter() {\n return availableApps;\n }\n\n public AppListAdapter getInstalledAdapter() {\n return installedApps;\n }\n\n public AppListAdapter getCanUpdateAdapter() {\n return canUpgradeApps;\n }\n\n public ArrayAdapter getCategoriesAdapter() {\n return categories;\n }\n\n public AppListManager(FDroid activity) {\n this.fdroidActivity = activity;\n\n availableApps = new AvailableAppListAdapter(fdroidActivity);\n installedApps = new InstalledAppListAdapter(fdroidActivity);\n canUpgradeApps = new CanUpdateAppListAdapter(fdroidActivity);\n\n \/\/ Needs to be created before createViews(), because that will use the\n \/\/ getCategoriesAdapter() accessor which expects this object...\n categories = new ArrayAdapter(activity,\n android.R.layout.simple_spinner_item, new ArrayList());\n categories\n .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n }\n\n private void clear() {\n installedApps.clear();\n availableApps.clear();\n canUpgradeApps.clear();\n categories.clear();\n }\n\n private void notifyLists() {\n \/\/ Tell the lists that the data behind the adapter has changed, so\n \/\/ they can refresh...\n availableApps.notifyDataSetChanged();\n installedApps.notifyDataSetChanged();\n canUpgradeApps.notifyDataSetChanged();\n categories.notifyDataSetChanged();\n }\n\n private void updateCategories() {\n try {\n DB db = DB.getDB();\n\n \/\/ Populate the category list with the real categories, and the\n \/\/ locally generated meta-categories for \"All\", \"What's New\" and\n \/\/ \"Recently Updated\"...\n categoryAll = fdroidActivity.getString(R.string.category_all);\n categoryWhatsNew = fdroidActivity.getString(R.string.category_whatsnew);\n categoryRecentlyUpdated = fdroidActivity.getString(R.string.category_recentlyupdated);\n\n categories.add(categoryWhatsNew);\n categories.add(categoryRecentlyUpdated);\n categories.add(categoryAll);\n\n for (String s : db.getCategories()) {\n categories.add(s);\n }\n\n if (currentCategory == null)\n currentCategory = categoryWhatsNew;\n\n } finally {\n DB.releaseDB();\n }\n }\n\n \/\/ Tell the FDroid activity to update its \"Update (x)\" tab to correctly\n \/\/ reflect the number of updates available.\n private void notifyActivity() {\n fdroidActivity.refreshUpdateTabLabel();\n }\n\n public void repopulateLists() {\n\n long startTime = System.currentTimeMillis();\n\n clear();\n\n updateCategories();\n updateApps();\n notifyLists();\n notifyActivity();\n\n Log.d(\"FDroid\", \"Updated lists - \" + allApps.size() + \" in total\"\n + \" (update took \" + (System.currentTimeMillis() - startTime)\n + \" ms)\");\n }\n\n \/\/ Calculate the cutoff date we'll use for What's New and Recently\n \/\/ Updated...\n private Date calcMaxHistory() {\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n String daysPreference = prefs.getString(\"updateHistoryDays\", \"14\");\n int maxHistoryDays = Integer.parseInt(daysPreference);\n Calendar recent = Calendar.getInstance();\n recent.add(Calendar.DAY_OF_YEAR, -maxHistoryDays);\n return recent.getTime();\n }\n\n \/\/ recentDate could really be calculated here, but this is just a hack so\n \/\/ it doesn't need to be calculated for every single app. The reason it\n \/\/ isn't an instance variable is because the preferences may change, and\n \/\/ we wouldn't know.\n private boolean isInCategory(DB.App app, String category, Date recentDate) {\n boolean isInCategory;\n if (category.equals(categoryAll)) {\n isInCategory = true;\n } else if (category.equals(categoryWhatsNew)) {\n if (app.added == null)\n isInCategory = false;\n else if (app.added.compareTo(recentDate) < 0)\n isInCategory = false;\n else\n isInCategory = true;\n } else if (category.equals(categoryRecentlyUpdated)) {\n if (app.lastUpdated == null)\n isInCategory = false;\n \/\/ Don't include in the recently updated category if the\n \/\/ 'update' was actually it being added.\n else if (app.lastUpdated.compareTo(app.added) == 0)\n isInCategory = false;\n else if (app.lastUpdated.compareTo(recentDate) < 0)\n isInCategory = false;\n else\n isInCategory = true;\n } else {\n isInCategory = category.equals(app.category);\n }\n return isInCategory;\n }\n\n \/\/ Returns false if the app list is empty and the fdroid activity decided\n \/\/ to attempt updating it.\n private boolean updateApps() {\n\n allApps = ((FDroidApp)fdroidActivity.getApplication()).getApps();\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n boolean showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n\n if (allApps.isEmpty()) {\n \/\/ If its the first time we've run the app, this should update\n \/\/ the repos. If not, it will do nothing, presuming that the repos\n \/\/ are invalid, the internet is stuffed, the sky has fallen, etc...\n return fdroidActivity.updateEmptyRepos();\n }\n\n Date recentDate = calcMaxHistory();\n List availApps = new ArrayList();\n for (DB.App app : allApps) {\n\n boolean isInCategory = isInCategory(app, currentCategory, recentDate);\n\n \/\/ Add it to the list(s). Always to installed and updates, but\n \/\/ only to available if it's not filtered.\n if (!app.filtered && isInCategory\n && (showIncompatible || app.compatible)) {\n availApps.add(app);\n }\n if (app.installedVersion != null) {\n installedApps.addItem(app);\n if (app.toUpdate)\n canUpgradeApps.addItem(app);\n }\n }\n\n if (currentCategory.equals(categoryWhatsNew)) {\n Collections.sort(availApps, new WhatsNewComparator());\n } else if (currentCategory.equals(categoryRecentlyUpdated)) {\n Collections.sort(availApps, new RecentlyUpdatedComparator());\n }\n\n for (DB.App app : availApps)\n availableApps.addItem(app);\n\n return true;\n }\n\n public void setCurrentCategory(String currentCategory) {\n if (!this.currentCategory.equals(currentCategory)){\n this.currentCategory = currentCategory;\n repopulateLists();\n }\n }\n\n static class WhatsNewComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.added.compareTo(lhs.added);\n }\n }\n\n static class RecentlyUpdatedComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.lastUpdated.compareTo(lhs.lastUpdated);\n }\n }\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid;\n\nimport java.util.*;\n\nimport android.content.SharedPreferences;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.widget.ArrayAdapter;\n\nimport org.fdroid.fdroid.views.AppListAdapter;\nimport org.fdroid.fdroid.views.AvailableAppListAdapter;\nimport org.fdroid.fdroid.views.CanUpdateAppListAdapter;\nimport org.fdroid.fdroid.views.InstalledAppListAdapter;\n\n\/**\n * Should be owned by the FDroid Activity, but used by the AppListFragments.\n * The idea is that it takes a non-trivial amount of time to work this stuff\n * out, and it is quicker if we only do it once for each view, rather than\n * each fragment figuring out their own list independently.\n *\/\npublic class AppListManager {\n\n private List allApps = null;\n\n private FDroid fdroidActivity;\n\n private AppListAdapter availableApps;\n private AppListAdapter installedApps;\n private AppListAdapter canUpgradeApps;\n private ArrayAdapter categories;\n\n private String currentCategory = null;\n private String categoryAll = null;\n private String categoryWhatsNew = null;\n private String categoryRecentlyUpdated = null;\n\n public AppListAdapter getAvailableAdapter() {\n return availableApps;\n }\n\n public AppListAdapter getInstalledAdapter() {\n return installedApps;\n }\n\n public AppListAdapter getCanUpdateAdapter() {\n return canUpgradeApps;\n }\n\n public ArrayAdapter getCategoriesAdapter() {\n return categories;\n }\n\n public AppListManager(FDroid activity) {\n this.fdroidActivity = activity;\n\n availableApps = new AvailableAppListAdapter(fdroidActivity);\n installedApps = new InstalledAppListAdapter(fdroidActivity);\n canUpgradeApps = new CanUpdateAppListAdapter(fdroidActivity);\n\n \/\/ Needs to be created before createViews(), because that will use the\n \/\/ getCategoriesAdapter() accessor which expects this object...\n categories = new ArrayAdapter(activity,\n android.R.layout.simple_spinner_item, new ArrayList());\n categories\n .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n }\n\n private void clear() {\n installedApps.clear();\n availableApps.clear();\n canUpgradeApps.clear();\n categories.clear();\n }\n\n private void notifyLists() {\n \/\/ Tell the lists that the data behind the adapter has changed, so\n \/\/ they can refresh...\n availableApps.notifyDataSetChanged();\n installedApps.notifyDataSetChanged();\n canUpgradeApps.notifyDataSetChanged();\n categories.notifyDataSetChanged();\n }\n\n private void updateCategories() {\n try {\n DB db = DB.getDB();\n\n \/\/ Populate the category list with the real categories, and the\n \/\/ locally generated meta-categories for \"All\", \"What's New\" and\n \/\/ \"Recently Updated\"...\n categoryAll = fdroidActivity.getString(R.string.category_all);\n categoryWhatsNew = fdroidActivity.getString(R.string.category_whatsnew);\n categoryRecentlyUpdated = fdroidActivity.getString(R.string.category_recentlyupdated);\n\n categories.add(categoryWhatsNew);\n categories.add(categoryRecentlyUpdated);\n categories.add(categoryAll);\n\n for (String s : db.getCategories()) {\n categories.add(s);\n }\n\n if (currentCategory == null)\n currentCategory = categoryWhatsNew;\n\n } finally {\n DB.releaseDB();\n }\n }\n\n \/\/ Tell the FDroid activity to update its \"Update (x)\" tab to correctly\n \/\/ reflect the number of updates available.\n private void notifyActivity() {\n fdroidActivity.refreshUpdateTabLabel();\n }\n\n public void repopulateLists() {\n\n long startTime = System.currentTimeMillis();\n\n clear();\n\n updateCategories();\n updateApps();\n notifyLists();\n notifyActivity();\n\n Log.d(\"FDroid\", \"Updated lists - \" + allApps.size() + \" in total\"\n + \" (update took \" + (System.currentTimeMillis() - startTime)\n + \" ms)\");\n }\n\n \/\/ Calculate the cutoff date we'll use for What's New and Recently\n \/\/ Updated...\n private Date calcMaxHistory() {\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n String daysPreference = prefs.getString(\"updateHistoryDays\", \"14\");\n int maxHistoryDays = Integer.parseInt(daysPreference);\n Calendar recent = Calendar.getInstance();\n recent.add(Calendar.DAY_OF_YEAR, -maxHistoryDays);\n return recent.getTime();\n }\n\n \/\/ recentDate could really be calculated here, but this is just a hack so\n \/\/ it doesn't need to be calculated for every single app. The reason it\n \/\/ isn't an instance variable is because the preferences may change, and\n \/\/ we wouldn't know.\n private boolean isInCategory(DB.App app, String category, Date recentDate) {\n boolean isInCategory;\n if (category.equals(categoryAll)) {\n isInCategory = true;\n } else if (category.equals(categoryWhatsNew)) {\n if (app.added == null)\n isInCategory = false;\n else if (app.added.compareTo(recentDate) < 0)\n isInCategory = false;\n else\n isInCategory = true;\n } else if (category.equals(categoryRecentlyUpdated)) {\n if (app.lastUpdated == null)\n isInCategory = false;\n \/\/ Don't include in the recently updated category if the\n \/\/ 'update' was actually it being added.\n else if (app.lastUpdated.compareTo(app.added) == 0)\n isInCategory = false;\n else if (app.lastUpdated.compareTo(recentDate) < 0)\n isInCategory = false;\n else\n isInCategory = true;\n } else {\n isInCategory = category.equals(app.category);\n }\n return isInCategory;\n }\n\n \/\/ Returns false if the app list is empty and the fdroid activity decided\n \/\/ to attempt updating it.\n private boolean updateApps() {\n\n allApps = ((FDroidApp)fdroidActivity.getApplication()).getApps();\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n boolean showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n\n if (allApps.isEmpty()) {\n \/\/ If its the first time we've run the app, this should update\n \/\/ the repos. If not, it will do nothing, presuming that the repos\n \/\/ are invalid, the internet is stuffed, the sky has fallen, etc...\n return fdroidActivity.updateEmptyRepos();\n }\n\n Date recentDate = calcMaxHistory();\n List availApps = new ArrayList();\n for (DB.App app : allApps) {\n\n boolean isInCategory = isInCategory(app, currentCategory, recentDate);\n\n \/\/ Add it to the list(s). Always to installed and updates, but\n \/\/ only to available if it's not filtered.\n if (!app.filtered && isInCategory\n && (showIncompatible || app.compatible)) {\n availApps.add(app);\n }\n if (app.installedVersion != null) {\n installedApps.addItem(app);\n if (app.toUpdate)\n canUpgradeApps.addItem(app);\n }\n }\n\n if (currentCategory.equals(categoryWhatsNew)) {\n Collections.sort(availApps, new WhatsNewComparator());\n } else if (currentCategory.equals(categoryRecentlyUpdated)) {\n Collections.sort(availApps, new RecentlyUpdatedComparator());\n }\n\n for (DB.App app : availApps)\n availableApps.addItem(app);\n\n return true;\n }\n\n public void setCurrentCategory(String currentCategory) {\n if (!this.currentCategory.equals(currentCategory)){\n this.currentCategory = currentCategory;\n repopulateLists();\n }\n }\n\n static class WhatsNewComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.added.compareTo(lhs.added);\n }\n }\n\n static class RecentlyUpdatedComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.lastUpdated.compareTo(lhs.lastUpdated);\n }\n }\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nOptimize isInCategory and updateApps implementations to make them easier and faster. Write the entire code and no other text in the response.\n\n### Concepts:\n[in] isInCategory function\n[in] updateApps function\n[+] lazy evaluation\n\n### Given program:\n```java\npackage org.fdroid.fdroid;\n\nimport java.util.*;\n\nimport android.content.SharedPreferences;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.widget.ArrayAdapter;\n\nimport org.fdroid.fdroid.views.AppListAdapter;\nimport org.fdroid.fdroid.views.AvailableAppListAdapter;\nimport org.fdroid.fdroid.views.CanUpdateAppListAdapter;\nimport org.fdroid.fdroid.views.InstalledAppListAdapter;\n\n\/**\n * Should be owned by the FDroid Activity, but used by the AppListFragments.\n * The idea is that it takes a non-trivial amount of time to work this stuff\n * out, and it is quicker if we only do it once for each view, rather than\n * each fragment figuring out their own list independently.\n *\/\npublic class AppListManager {\n\n private List allApps = null;\n\n private FDroid fdroidActivity;\n\n private AppListAdapter availableApps;\n private AppListAdapter installedApps;\n private AppListAdapter canUpgradeApps;\n private ArrayAdapter categories;\n\n private String currentCategory = null;\n private String categoryAll = null;\n private String categoryWhatsNew = null;\n private String categoryRecentlyUpdated = null;\n\n public AppListAdapter getAvailableAdapter() {\n return availableApps;\n }\n\n public AppListAdapter getInstalledAdapter() {\n return installedApps;\n }\n\n public AppListAdapter getCanUpdateAdapter() {\n return canUpgradeApps;\n }\n\n public ArrayAdapter getCategoriesAdapter() {\n return categories;\n }\n\n public AppListManager(FDroid activity) {\n this.fdroidActivity = activity;\n\n availableApps = new AvailableAppListAdapter(fdroidActivity);\n installedApps = new InstalledAppListAdapter(fdroidActivity);\n canUpgradeApps = new CanUpdateAppListAdapter(fdroidActivity);\n\n \/\/ Needs to be created before createViews(), because that will use the\n \/\/ getCategoriesAdapter() accessor which expects this object...\n categories = new ArrayAdapter(activity,\n android.R.layout.simple_spinner_item, new ArrayList());\n categories\n .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n }\n\n private void clear() {\n installedApps.clear();\n availableApps.clear();\n canUpgradeApps.clear();\n categories.clear();\n }\n\n private void notifyLists() {\n \/\/ Tell the lists that the data behind the adapter has changed, so\n \/\/ they can refresh...\n availableApps.notifyDataSetChanged();\n installedApps.notifyDataSetChanged();\n canUpgradeApps.notifyDataSetChanged();\n categories.notifyDataSetChanged();\n }\n\n private void updateCategories() {\n try {\n DB db = DB.getDB();\n\n \/\/ Populate the category list with the real categories, and the\n \/\/ locally generated meta-categories for \"All\", \"What's New\" and\n \/\/ \"Recently Updated\"...\n categoryAll = fdroidActivity.getString(R.string.category_all);\n categoryWhatsNew = fdroidActivity.getString(R.string.category_whatsnew);\n categoryRecentlyUpdated = fdroidActivity.getString(R.string.category_recentlyupdated);\n\n categories.add(categoryWhatsNew);\n categories.add(categoryRecentlyUpdated);\n categories.add(categoryAll);\n\n for (String s : db.getCategories()) {\n categories.add(s);\n }\n\n if (currentCategory == null)\n currentCategory = categoryWhatsNew;\n\n } finally {\n DB.releaseDB();\n }\n }\n\n \/\/ Tell the FDroid activity to update its \"Update (x)\" tab to correctly\n \/\/ reflect the number of updates available.\n private void notifyActivity() {\n fdroidActivity.refreshUpdateTabLabel();\n }\n\n public void repopulateLists() {\n\n long startTime = System.currentTimeMillis();\n\n clear();\n\n updateCategories();\n updateApps();\n notifyLists();\n notifyActivity();\n\n Log.d(\"FDroid\", \"Updated lists - \" + allApps.size() + \" in total\"\n + \" (update took \" + (System.currentTimeMillis() - startTime)\n + \" ms)\");\n }\n\n \/\/ Calculate the cutoff date we'll use for What's New and Recently\n \/\/ Updated...\n private Date calcMaxHistory() {\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n String daysPreference = prefs.getString(\"updateHistoryDays\", \"14\");\n int maxHistoryDays = Integer.parseInt(daysPreference);\n Calendar recent = Calendar.getInstance();\n recent.add(Calendar.DAY_OF_YEAR, -maxHistoryDays);\n return recent.getTime();\n }\n\n \/\/ recentDate could really be calculated here, but this is just a hack so\n \/\/ it doesn't need to be calculated for every single app. The reason it\n \/\/ isn't an instance variable is because the preferences may change, and\n \/\/ we wouldn't know.\n private boolean isInCategory(DB.App app, String category, Date recentDate) {\n boolean isInCategory;\n if (category.equals(categoryAll)) {\n isInCategory = true;\n } else if (category.equals(categoryWhatsNew)) {\n if (app.added == null)\n isInCategory = false;\n else if (app.added.compareTo(recentDate) < 0)\n isInCategory = false;\n else\n isInCategory = true;\n } else if (category.equals(categoryRecentlyUpdated)) {\n if (app.lastUpdated == null)\n isInCategory = false;\n \/\/ Don't include in the recently updated category if the\n \/\/ 'update' was actually it being added.\n else if (app.lastUpdated.compareTo(app.added) == 0)\n isInCategory = false;\n else if (app.lastUpdated.compareTo(recentDate) < 0)\n isInCategory = false;\n else\n isInCategory = true;\n } else {\n isInCategory = category.equals(app.category);\n }\n return isInCategory;\n }\n\n \/\/ Returns false if the app list is empty and the fdroid activity decided\n \/\/ to attempt updating it.\n private boolean updateApps() {\n\n allApps = ((FDroidApp)fdroidActivity.getApplication()).getApps();\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n boolean showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n\n if (allApps.isEmpty()) {\n \/\/ If its the first time we've run the app, this should update\n \/\/ the repos. If not, it will do nothing, presuming that the repos\n \/\/ are invalid, the internet is stuffed, the sky has fallen, etc...\n return fdroidActivity.updateEmptyRepos();\n }\n\n Date recentDate = calcMaxHistory();\n List availApps = new ArrayList();\n for (DB.App app : allApps) {\n\n boolean isInCategory = isInCategory(app, currentCategory, recentDate);\n\n \/\/ Add it to the list(s). Always to installed and updates, but\n \/\/ only to available if it's not filtered.\n if (!app.filtered && isInCategory\n && (showIncompatible || app.compatible)) {\n availApps.add(app);\n }\n if (app.installedVersion != null) {\n installedApps.addItem(app);\n if (app.toUpdate)\n canUpgradeApps.addItem(app);\n }\n }\n\n if (currentCategory.equals(categoryWhatsNew)) {\n Collections.sort(availApps, new WhatsNewComparator());\n } else if (currentCategory.equals(categoryRecentlyUpdated)) {\n Collections.sort(availApps, new RecentlyUpdatedComparator());\n }\n\n for (DB.App app : availApps)\n availableApps.addItem(app);\n\n return true;\n }\n\n public void setCurrentCategory(String currentCategory) {\n if (!this.currentCategory.equals(currentCategory)){\n this.currentCategory = currentCategory;\n repopulateLists();\n }\n }\n\n static class WhatsNewComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.added.compareTo(lhs.added);\n }\n }\n\n static class RecentlyUpdatedComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.lastUpdated.compareTo(lhs.lastUpdated);\n }\n }\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/*\n * Copyright (C) 2018 Hans-Christoph Steiner \n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.nearby;\n\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.app.IntentService;\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Process;\nimport android.support.v4.provider.DocumentFile;\nimport android.util.Log;\nimport android.widget.Toast;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.IOUtils;\nimport org.fdroid.fdroid.AddRepoIntentService;\nimport org.fdroid.fdroid.IndexUpdater;\nimport org.fdroid.fdroid.IndexV1Updater;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Repo;\nimport org.fdroid.fdroid.data.RepoProvider;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.security.cert.Certificate;\nimport java.util.ArrayList;\nimport java.util.jar.JarEntry;\nimport java.util.jar.JarFile;\nimport java.util.jar.JarInputStream;\n\n\/**\n * An {@link IntentService} subclass for handling asynchronous scanning of a\n * removable storage device like an SD Card or USB OTG thumb drive using the\n * Storage Access Framework. Permission must first be granted by the user\n * {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} or\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)}request,\n * then F-Droid will have permanent access to that{@link Uri}.\n *

\n * Even though the Storage Access Framework was introduced in\n * {@link android.os.Build.VERSION_CODES#KITKAT android-19}, this approach is only\n * workable if {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} is available.\n * It was added in {@link android.os.Build.VERSION_CODES#LOLLIPOP android-21}.\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)} is also\n * necessary to do this with any kind of rational UX.\n *\n * @see The Storage Situation: Removable Storage <\/a>\n * @see Be Careful with Scoped Directory Access<\/a>\n * @see Using Scoped Directory Access<\/a>\n * @see Open Files using Storage Access Framework<\/a>\n *\/\n@TargetApi(21)\npublic class TreeUriScannerIntentService extends IntentService {\n public static final String TAG = \"TreeUriScannerIntentSer\";\n\n private static final String ACTION_SCAN_TREE_URI = \"org.fdroid.fdroid.nearby.action.SCAN_TREE_URI\";\n\n public TreeUriScannerIntentService() {\n super(\"TreeUriScannerIntentService\");\n }\n\n public static void scan(Context context, Uri data) {\n if (Preferences.get().isScanRemovableStorageEnabled()) {\n Intent intent = new Intent(context, TreeUriScannerIntentService.class);\n intent.setAction(ACTION_SCAN_TREE_URI);\n intent.setData(data);\n context.startService(intent);\n }\n }\n\n \/**\n * Now determine if it is External Storage that must be handled by the\n * {@link TreeUriScannerIntentService} or whether it is External Storage\n * like an SD Card that can be directly accessed via the file system.\n *\/\n public static void onActivityResult(Activity activity, Intent intent) {\n Uri uri = intent.getData();\n if (uri != null) {\n if (Build.VERSION.SDK_INT >= 19) {\n ContentResolver contentResolver = activity.getContentResolver();\n int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;\n contentResolver.takePersistableUriPermission(uri, perms);\n }\n String msg = String.format(activity.getString(R.string.swap_toast_using_path), uri.toString());\n Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();\n scan(activity, uri);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n if (intent == null || !ACTION_SCAN_TREE_URI.equals(intent.getAction())) {\n return;\n }\n Uri treeUri = intent.getData();\n if (treeUri == null) {\n return;\n }\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n DocumentFile treeFile = DocumentFile.fromTreeUri(this, treeUri);\n searchDirectory(treeFile);\n }\n\n \/**\n * Recursively search for {@link IndexV1Updater#SIGNED_FILE_NAME} starting\n * from the given directory, looking at files first before recursing into\n * directories. This is \"depth last\" since the index file is much more\n * likely to be shallow than deep, and there can be a lot of files to\n * search through starting at 4 or more levels deep, like the fdroid\n * icons dirs and the per-app \"external storage\" dirs.\n *\/\n private void searchDirectory(DocumentFile documentFileDir) {\n DocumentFile[] documentFiles = documentFileDir.listFiles();\n if (documentFiles == null) {\n return;\n }\n boolean foundIndex = false;\n ArrayList dirs = new ArrayList<>();\n for (DocumentFile documentFile : documentFiles) {\n if (documentFile.isDirectory()) {\n dirs.add(documentFile);\n } else if (!foundIndex) {\n if (IndexV1Updater.SIGNED_FILE_NAME.equals(documentFile.getName())) {\n registerRepo(documentFile);\n foundIndex = true;\n }\n }\n }\n for (DocumentFile dir : dirs) {\n searchDirectory(dir);\n }\n }\n\n \/**\n * For all files called {@link IndexV1Updater#SIGNED_FILE_NAME} found, check\n * the JAR signature and read the fingerprint of the signing certificate.\n * The fingerprint is then used to find whether this local repo is a mirror\n * of an existing repo, or a totally new repo. In order to verify the\n * signatures in the JAR, the whole file needs to be read in first.\n *\n * @see JarInputStream#JarInputStream(InputStream, boolean)\n *\/\n private void registerRepo(DocumentFile index) {\n InputStream inputStream = null;\n try {\n inputStream = getContentResolver().openInputStream(index.getUri());\n registerRepo(this, inputStream, index.getParentFile().getUri());\n } catch (IOException | IndexUpdater.SigningException e) {\n e.printStackTrace();\n } finally {\n Utils.closeQuietly(inputStream);\n }\n }\n\n public static void registerRepo(Context context, InputStream inputStream, Uri repoUri)\n throws IOException, IndexUpdater.SigningException {\n if (inputStream == null) {\n return;\n }\n File destFile = File.createTempFile(\"dl-\", IndexV1Updater.SIGNED_FILE_NAME, context.getCacheDir());\n FileUtils.copyInputStreamToFile(inputStream, destFile);\n JarFile jarFile = new JarFile(destFile, true);\n JarEntry indexEntry = (JarEntry) jarFile.getEntry(IndexV1Updater.DATA_FILE_NAME);\n IOUtils.readLines(jarFile.getInputStream(indexEntry));\n Certificate certificate = IndexUpdater.getSigningCertFromJar(indexEntry);\n String fingerprint = Utils.calcFingerprint(certificate);\n Log.i(TAG, \"Got fingerprint: \" + fingerprint);\n destFile.delete();\n\n Log.i(TAG, \"Found a valid, signed index-v1.json\");\n for (Repo repo : RepoProvider.Helper.all(context)) {\n if (fingerprint.equals(repo.fingerprint)) {\n Log.i(TAG, repo.address + \" has the SAME fingerprint: \" + fingerprint);\n } else {\n Log.i(TAG, repo.address + \" different fingerprint\");\n }\n }\n\n AddRepoIntentService.addRepo(context, repoUri, fingerprint);\n \/\/ TODO rework IndexUpdater.getSigningCertFromJar to work for here\n }\n}\n\n\nCode-B:\n\/*\n * Copyright (C) 2018 Hans-Christoph Steiner \n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.nearby;\n\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.app.IntentService;\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Process;\nimport android.support.v4.provider.DocumentFile;\nimport android.util.Log;\nimport android.widget.Toast;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.IOUtils;\nimport org.fdroid.fdroid.AddRepoIntentService;\nimport org.fdroid.fdroid.IndexUpdater;\nimport org.fdroid.fdroid.IndexV1Updater;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Repo;\nimport org.fdroid.fdroid.data.RepoProvider;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.security.cert.Certificate;\nimport java.util.jar.JarEntry;\nimport java.util.jar.JarFile;\nimport java.util.jar.JarInputStream;\n\n\/**\n * An {@link IntentService} subclass for handling asynchronous scanning of a\n * removable storage device like an SD Card or USB OTG thumb drive using the\n * Storage Access Framework. Permission must first be granted by the user\n * {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} or\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)}request,\n * then F-Droid will have permanent access to that{@link Uri}.\n *

\n * Even though the Storage Access Framework was introduced in\n * {@link android.os.Build.VERSION_CODES#KITKAT android-19}, this approach is only\n * workable if {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} is available.\n * It was added in {@link android.os.Build.VERSION_CODES#LOLLIPOP android-21}.\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)} is also\n * necessary to do this with any kind of rational UX.\n *\n * @see The Storage Situation: Removable Storage <\/a>\n * @see Be Careful with Scoped Directory Access<\/a>\n * @see Using Scoped Directory Access<\/a>\n * @see Open Files using Storage Access Framework<\/a>\n *\/\n@TargetApi(21)\npublic class TreeUriScannerIntentService extends IntentService {\n public static final String TAG = \"TreeUriScannerIntentSer\";\n\n private static final String ACTION_SCAN_TREE_URI = \"org.fdroid.fdroid.nearby.action.SCAN_TREE_URI\";\n\n public TreeUriScannerIntentService() {\n super(\"TreeUriScannerIntentService\");\n }\n\n public static void scan(Context context, Uri data) {\n if (Preferences.get().isScanRemovableStorageEnabled()) {\n Intent intent = new Intent(context, TreeUriScannerIntentService.class);\n intent.setAction(ACTION_SCAN_TREE_URI);\n intent.setData(data);\n context.startService(intent);\n }\n }\n\n \/**\n * Now determine if it is External Storage that must be handled by the\n * {@link TreeUriScannerIntentService} or whether it is External Storage\n * like an SD Card that can be directly accessed via the file system.\n *\/\n public static void onActivityResult(Activity activity, Intent intent) {\n Uri uri = intent.getData();\n if (uri != null) {\n if (Build.VERSION.SDK_INT >= 19) {\n ContentResolver contentResolver = activity.getContentResolver();\n int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;\n contentResolver.takePersistableUriPermission(uri, perms);\n }\n String msg = String.format(activity.getString(R.string.swap_toast_using_path), uri.toString());\n Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();\n scan(activity, uri);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n if (intent == null || !ACTION_SCAN_TREE_URI.equals(intent.getAction())) {\n return;\n }\n Uri treeUri = intent.getData();\n if (treeUri == null) {\n return;\n }\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n DocumentFile treeFile = DocumentFile.fromTreeUri(this, treeUri);\n searchDirectory(treeFile);\n }\n\n private void searchDirectory(DocumentFile documentFileDir) {\n DocumentFile[] documentFiles = documentFileDir.listFiles();\n if (documentFiles == null) {\n return;\n }\n for (DocumentFile documentFile : documentFiles) {\n if (documentFile.isDirectory()) {\n searchDirectory(documentFile);\n } else {\n if (IndexV1Updater.SIGNED_FILE_NAME.equals(documentFile.getName())) {\n registerRepo(documentFile);\n }\n }\n }\n }\n\n \/**\n * For all files called {@link IndexV1Updater#SIGNED_FILE_NAME} found, check\n * the JAR signature and read the fingerprint of the signing certificate.\n * The fingerprint is then used to find whether this local repo is a mirror\n * of an existing repo, or a totally new repo. In order to verify the\n * signatures in the JAR, the whole file needs to be read in first.\n *\n * @see JarInputStream#JarInputStream(InputStream, boolean)\n *\/\n private void registerRepo(DocumentFile index) {\n InputStream inputStream = null;\n try {\n inputStream = getContentResolver().openInputStream(index.getUri());\n registerRepo(this, inputStream, index.getParentFile().getUri());\n } catch (IOException | IndexUpdater.SigningException e) {\n e.printStackTrace();\n } finally {\n Utils.closeQuietly(inputStream);\n }\n }\n\n public static void registerRepo(Context context, InputStream inputStream, Uri repoUri)\n throws IOException, IndexUpdater.SigningException {\n if (inputStream == null) {\n return;\n }\n File destFile = File.createTempFile(\"dl-\", IndexV1Updater.SIGNED_FILE_NAME, context.getCacheDir());\n FileUtils.copyInputStreamToFile(inputStream, destFile);\n JarFile jarFile = new JarFile(destFile, true);\n JarEntry indexEntry = (JarEntry) jarFile.getEntry(IndexV1Updater.DATA_FILE_NAME);\n IOUtils.readLines(jarFile.getInputStream(indexEntry));\n Certificate certificate = IndexUpdater.getSigningCertFromJar(indexEntry);\n String fingerprint = Utils.calcFingerprint(certificate);\n Log.i(TAG, \"Got fingerprint: \" + fingerprint);\n destFile.delete();\n\n Log.i(TAG, \"Found a valid, signed index-v1.json\");\n for (Repo repo : RepoProvider.Helper.all(context)) {\n if (fingerprint.equals(repo.fingerprint)) {\n Log.i(TAG, repo.address + \" has the SAME fingerprint: \" + fingerprint);\n } else {\n Log.i(TAG, repo.address + \" different fingerprint\");\n }\n }\n\n AddRepoIntentService.addRepo(context, repoUri, fingerprint);\n \/\/ TODO rework IndexUpdater.getSigningCertFromJar to work for here\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/*\n * Copyright (C) 2018 Hans-Christoph Steiner \n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.nearby;\n\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.app.IntentService;\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Process;\nimport android.support.v4.provider.DocumentFile;\nimport android.util.Log;\nimport android.widget.Toast;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.IOUtils;\nimport org.fdroid.fdroid.AddRepoIntentService;\nimport org.fdroid.fdroid.IndexUpdater;\nimport org.fdroid.fdroid.IndexV1Updater;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Repo;\nimport org.fdroid.fdroid.data.RepoProvider;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.security.cert.Certificate;\nimport java.util.jar.JarEntry;\nimport java.util.jar.JarFile;\nimport java.util.jar.JarInputStream;\n\n\/**\n * An {@link IntentService} subclass for handling asynchronous scanning of a\n * removable storage device like an SD Card or USB OTG thumb drive using the\n * Storage Access Framework. Permission must first be granted by the user\n * {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} or\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)}request,\n * then F-Droid will have permanent access to that{@link Uri}.\n *

\n * Even though the Storage Access Framework was introduced in\n * {@link android.os.Build.VERSION_CODES#KITKAT android-19}, this approach is only\n * workable if {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} is available.\n * It was added in {@link android.os.Build.VERSION_CODES#LOLLIPOP android-21}.\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)} is also\n * necessary to do this with any kind of rational UX.\n *\n * @see The Storage Situation: Removable Storage <\/a>\n * @see Be Careful with Scoped Directory Access<\/a>\n * @see Using Scoped Directory Access<\/a>\n * @see Open Files using Storage Access Framework<\/a>\n *\/\n@TargetApi(21)\npublic class TreeUriScannerIntentService extends IntentService {\n public static final String TAG = \"TreeUriScannerIntentSer\";\n\n private static final String ACTION_SCAN_TREE_URI = \"org.fdroid.fdroid.nearby.action.SCAN_TREE_URI\";\n\n public TreeUriScannerIntentService() {\n super(\"TreeUriScannerIntentService\");\n }\n\n public static void scan(Context context, Uri data) {\n if (Preferences.get().isScanRemovableStorageEnabled()) {\n Intent intent = new Intent(context, TreeUriScannerIntentService.class);\n intent.setAction(ACTION_SCAN_TREE_URI);\n intent.setData(data);\n context.startService(intent);\n }\n }\n\n \/**\n * Now determine if it is External Storage that must be handled by the\n * {@link TreeUriScannerIntentService} or whether it is External Storage\n * like an SD Card that can be directly accessed via the file system.\n *\/\n public static void onActivityResult(Activity activity, Intent intent) {\n Uri uri = intent.getData();\n if (uri != null) {\n if (Build.VERSION.SDK_INT >= 19) {\n ContentResolver contentResolver = activity.getContentResolver();\n int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;\n contentResolver.takePersistableUriPermission(uri, perms);\n }\n String msg = String.format(activity.getString(R.string.swap_toast_using_path), uri.toString());\n Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();\n scan(activity, uri);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n if (intent == null || !ACTION_SCAN_TREE_URI.equals(intent.getAction())) {\n return;\n }\n Uri treeUri = intent.getData();\n if (treeUri == null) {\n return;\n }\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n DocumentFile treeFile = DocumentFile.fromTreeUri(this, treeUri);\n searchDirectory(treeFile);\n }\n\n private void searchDirectory(DocumentFile documentFileDir) {\n DocumentFile[] documentFiles = documentFileDir.listFiles();\n if (documentFiles == null) {\n return;\n }\n for (DocumentFile documentFile : documentFiles) {\n if (documentFile.isDirectory()) {\n searchDirectory(documentFile);\n } else {\n if (IndexV1Updater.SIGNED_FILE_NAME.equals(documentFile.getName())) {\n registerRepo(documentFile);\n }\n }\n }\n }\n\n \/**\n * For all files called {@link IndexV1Updater#SIGNED_FILE_NAME} found, check\n * the JAR signature and read the fingerprint of the signing certificate.\n * The fingerprint is then used to find whether this local repo is a mirror\n * of an existing repo, or a totally new repo. In order to verify the\n * signatures in the JAR, the whole file needs to be read in first.\n *\n * @see JarInputStream#JarInputStream(InputStream, boolean)\n *\/\n private void registerRepo(DocumentFile index) {\n InputStream inputStream = null;\n try {\n inputStream = getContentResolver().openInputStream(index.getUri());\n registerRepo(this, inputStream, index.getParentFile().getUri());\n } catch (IOException | IndexUpdater.SigningException e) {\n e.printStackTrace();\n } finally {\n Utils.closeQuietly(inputStream);\n }\n }\n\n public static void registerRepo(Context context, InputStream inputStream, Uri repoUri)\n throws IOException, IndexUpdater.SigningException {\n if (inputStream == null) {\n return;\n }\n File destFile = File.createTempFile(\"dl-\", IndexV1Updater.SIGNED_FILE_NAME, context.getCacheDir());\n FileUtils.copyInputStreamToFile(inputStream, destFile);\n JarFile jarFile = new JarFile(destFile, true);\n JarEntry indexEntry = (JarEntry) jarFile.getEntry(IndexV1Updater.DATA_FILE_NAME);\n IOUtils.readLines(jarFile.getInputStream(indexEntry));\n Certificate certificate = IndexUpdater.getSigningCertFromJar(indexEntry);\n String fingerprint = Utils.calcFingerprint(certificate);\n Log.i(TAG, \"Got fingerprint: \" + fingerprint);\n destFile.delete();\n\n Log.i(TAG, \"Found a valid, signed index-v1.json\");\n for (Repo repo : RepoProvider.Helper.all(context)) {\n if (fingerprint.equals(repo.fingerprint)) {\n Log.i(TAG, repo.address + \" has the SAME fingerprint: \" + fingerprint);\n } else {\n Log.i(TAG, repo.address + \" different fingerprint\");\n }\n }\n\n AddRepoIntentService.addRepo(context, repoUri, fingerprint);\n \/\/ TODO rework IndexUpdater.getSigningCertFromJar to work for here\n }\n}\n\n\nCode-B:\n\/*\n * Copyright (C) 2018 Hans-Christoph Steiner \n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid.nearby;\n\nimport android.annotation.TargetApi;\nimport android.app.Activity;\nimport android.app.IntentService;\nimport android.content.ContentResolver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Build;\nimport android.os.Process;\nimport android.support.v4.provider.DocumentFile;\nimport android.util.Log;\nimport android.widget.Toast;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.IOUtils;\nimport org.fdroid.fdroid.AddRepoIntentService;\nimport org.fdroid.fdroid.IndexUpdater;\nimport org.fdroid.fdroid.IndexV1Updater;\nimport org.fdroid.fdroid.Preferences;\nimport org.fdroid.fdroid.R;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Repo;\nimport org.fdroid.fdroid.data.RepoProvider;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.security.cert.Certificate;\nimport java.util.ArrayList;\nimport java.util.jar.JarEntry;\nimport java.util.jar.JarFile;\nimport java.util.jar.JarInputStream;\n\n\/**\n * An {@link IntentService} subclass for handling asynchronous scanning of a\n * removable storage device like an SD Card or USB OTG thumb drive using the\n * Storage Access Framework. Permission must first be granted by the user\n * {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} or\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)}request,\n * then F-Droid will have permanent access to that{@link Uri}.\n *

\n * Even though the Storage Access Framework was introduced in\n * {@link android.os.Build.VERSION_CODES#KITKAT android-19}, this approach is only\n * workable if {@link android.content.Intent#ACTION_OPEN_DOCUMENT_TREE} is available.\n * It was added in {@link android.os.Build.VERSION_CODES#LOLLIPOP android-21}.\n * {@link android.os.storage.StorageVolume#createAccessIntent(String)} is also\n * necessary to do this with any kind of rational UX.\n *\n * @see The Storage Situation: Removable Storage <\/a>\n * @see Be Careful with Scoped Directory Access<\/a>\n * @see Using Scoped Directory Access<\/a>\n * @see Open Files using Storage Access Framework<\/a>\n *\/\n@TargetApi(21)\npublic class TreeUriScannerIntentService extends IntentService {\n public static final String TAG = \"TreeUriScannerIntentSer\";\n\n private static final String ACTION_SCAN_TREE_URI = \"org.fdroid.fdroid.nearby.action.SCAN_TREE_URI\";\n\n public TreeUriScannerIntentService() {\n super(\"TreeUriScannerIntentService\");\n }\n\n public static void scan(Context context, Uri data) {\n if (Preferences.get().isScanRemovableStorageEnabled()) {\n Intent intent = new Intent(context, TreeUriScannerIntentService.class);\n intent.setAction(ACTION_SCAN_TREE_URI);\n intent.setData(data);\n context.startService(intent);\n }\n }\n\n \/**\n * Now determine if it is External Storage that must be handled by the\n * {@link TreeUriScannerIntentService} or whether it is External Storage\n * like an SD Card that can be directly accessed via the file system.\n *\/\n public static void onActivityResult(Activity activity, Intent intent) {\n Uri uri = intent.getData();\n if (uri != null) {\n if (Build.VERSION.SDK_INT >= 19) {\n ContentResolver contentResolver = activity.getContentResolver();\n int perms = Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;\n contentResolver.takePersistableUriPermission(uri, perms);\n }\n String msg = String.format(activity.getString(R.string.swap_toast_using_path), uri.toString());\n Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();\n scan(activity, uri);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n if (intent == null || !ACTION_SCAN_TREE_URI.equals(intent.getAction())) {\n return;\n }\n Uri treeUri = intent.getData();\n if (treeUri == null) {\n return;\n }\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n DocumentFile treeFile = DocumentFile.fromTreeUri(this, treeUri);\n searchDirectory(treeFile);\n }\n\n \/**\n * Recursively search for {@link IndexV1Updater#SIGNED_FILE_NAME} starting\n * from the given directory, looking at files first before recursing into\n * directories. This is \"depth last\" since the index file is much more\n * likely to be shallow than deep, and there can be a lot of files to\n * search through starting at 4 or more levels deep, like the fdroid\n * icons dirs and the per-app \"external storage\" dirs.\n *\/\n private void searchDirectory(DocumentFile documentFileDir) {\n DocumentFile[] documentFiles = documentFileDir.listFiles();\n if (documentFiles == null) {\n return;\n }\n boolean foundIndex = false;\n ArrayList dirs = new ArrayList<>();\n for (DocumentFile documentFile : documentFiles) {\n if (documentFile.isDirectory()) {\n dirs.add(documentFile);\n } else if (!foundIndex) {\n if (IndexV1Updater.SIGNED_FILE_NAME.equals(documentFile.getName())) {\n registerRepo(documentFile);\n foundIndex = true;\n }\n }\n }\n for (DocumentFile dir : dirs) {\n searchDirectory(dir);\n }\n }\n\n \/**\n * For all files called {@link IndexV1Updater#SIGNED_FILE_NAME} found, check\n * the JAR signature and read the fingerprint of the signing certificate.\n * The fingerprint is then used to find whether this local repo is a mirror\n * of an existing repo, or a totally new repo. In order to verify the\n * signatures in the JAR, the whole file needs to be read in first.\n *\n * @see JarInputStream#JarInputStream(InputStream, boolean)\n *\/\n private void registerRepo(DocumentFile index) {\n InputStream inputStream = null;\n try {\n inputStream = getContentResolver().openInputStream(index.getUri());\n registerRepo(this, inputStream, index.getParentFile().getUri());\n } catch (IOException | IndexUpdater.SigningException e) {\n e.printStackTrace();\n } finally {\n Utils.closeQuietly(inputStream);\n }\n }\n\n public static void registerRepo(Context context, InputStream inputStream, Uri repoUri)\n throws IOException, IndexUpdater.SigningException {\n if (inputStream == null) {\n return;\n }\n File destFile = File.createTempFile(\"dl-\", IndexV1Updater.SIGNED_FILE_NAME, context.getCacheDir());\n FileUtils.copyInputStreamToFile(inputStream, destFile);\n JarFile jarFile = new JarFile(destFile, true);\n JarEntry indexEntry = (JarEntry) jarFile.getEntry(IndexV1Updater.DATA_FILE_NAME);\n IOUtils.readLines(jarFile.getInputStream(indexEntry));\n Certificate certificate = IndexUpdater.getSigningCertFromJar(indexEntry);\n String fingerprint = Utils.calcFingerprint(certificate);\n Log.i(TAG, \"Got fingerprint: \" + fingerprint);\n destFile.delete();\n\n Log.i(TAG, \"Found a valid, signed index-v1.json\");\n for (Repo repo : RepoProvider.Helper.all(context)) {\n if (fingerprint.equals(repo.fingerprint)) {\n Log.i(TAG, repo.address + \" has the SAME fingerprint: \" + fingerprint);\n } else {\n Log.i(TAG, repo.address + \" different fingerprint\");\n }\n }\n\n AddRepoIntentService.addRepo(context, repoUri, fingerprint);\n \/\/ TODO rework IndexUpdater.getSigningCertFromJar to work for here\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/cbeyls\/fosdem-companion-android\/commit\/ff140b060c909a4e71c4fc2ebc384c3df280b87d","commit_message":"'\\\\\"Optimized iteration performance in SlidingTabLayout\\\\n\\\\\"'","source_code":"\/*\n * Copyright 2014 Chris Banes\n * Copyright 2016 Christophe Beyls\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage com.example.android.common.view;\n\nimport android.content.Context;\nimport android.content.res.ColorStateList;\nimport android.content.res.TypedArray;\nimport android.graphics.Typeface;\nimport android.os.Build;\nimport android.support.annotation.ColorInt;\nimport android.support.annotation.IdRes;\nimport android.support.annotation.LayoutRes;\nimport android.support.v4.view.PagerAdapter;\nimport android.support.v4.view.ViewPager;\nimport android.util.AttributeSet;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.widget.HorizontalScrollView;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\n\nimport be.digitalia.fosdem.R;\n\n\/**\n *\/\npublic class SlidingTabLayout extends HorizontalScrollView {\n\n\tpublic interface TabListener {\n\n\t\tvoid onTabSelected(int pos);\n\n\t\tvoid onTabReSelected(int pos);\n\n\t}\n\n\tprivate static final int[][] TAB_COLOR_STATES = new int[][]{SELECTED_STATE_SET, EMPTY_STATE_SET};\n\n\tprivate int mTitleOffset;\n\n\tprivate int mTabViewLayoutId;\n\tprivate int mTabViewTextViewId;\n\tprivate boolean mDistributeEvenly;\n\n\tprivate ColorStateList mTextColor;\n\n\tprivate ViewPager mViewPager;\n\n\tprivate TabListener mTabListener;\n\n\tprivate final SlidingTabStrip mTabStrip;\n\n\tpublic SlidingTabLayout(Context context) {\n\t\tthis(context, null);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs) {\n\t\tthis(context, attrs, 0);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {\n\t\tsuper(context, attrs, defStyle);\n\n\t\t\/\/ Disable the Scroll Bar\n\t\tsetHorizontalScrollBarEnabled(false);\n\t\t\/\/ Make sure that the Tab Strips fills this View\n\t\tsetFillViewport(true);\n\n\t\tmTabStrip = new SlidingTabStrip(context);\n\t\taddView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);\n\n\t\tTypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SlidingTabLayout,\n\t\t\t\tdefStyle, R.style.SlidingTabLayout);\n\n\t\tmTabStrip.setSelectedIndicatorHeight(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_indicatorHeight, 0));\n\t\tmTabStrip.setSelectedIndicatorColor(a.getColor(R.styleable.SlidingTabLayout_indicatorColor, 0));\n\t\tmTextColor = a.getColorStateList(R.styleable.SlidingTabLayout_textColor);\n\t\tif ((mTextColor != null) && a.hasValue(R.styleable.SlidingTabLayout_selectedTextColor)) {\n\t\t\tsetTabTextColors(mTextColor.getDefaultColor(), a.getColor(R.styleable.SlidingTabLayout_selectedTextColor, 0));\n\t\t}\n\t\tsetContentInsetStart(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_contentInsetStart, 0));\n\t\tsetDistributeEvenly(a.getBoolean(R.styleable.SlidingTabLayout_distributeEvenly, false));\n\n\t\ta.recycle();\n\t}\n\n\tpublic void setContentInsetStart(int offset) {\n\t\tmTitleOffset = offset;\n\t\tmTabStrip.setPadding(offset, 0, 0, 0);\n\t}\n\n\tpublic void setDistributeEvenly(boolean distributeEvenly) {\n\t\tmDistributeEvenly = distributeEvenly;\n\t}\n\n\t\/**\n\t * Sets the color to be used for indicating the selected tab.\n\t * This will override the style color.\n\t *\/\n\tpublic void setSelectedTabIndicatorColor(@ColorInt int color) {\n\t\tmTabStrip.setSelectedIndicatorColor(color);\n\t}\n\n\tpublic void setSelectedTabIndicatorHeight(int height) {\n\t\tmTabStrip.setSelectedIndicatorHeight(height);\n\t}\n\n\tpublic void setTabTextColors(ColorStateList color) {\n\t\tmTextColor = color;\n\t}\n\n\tpublic void setTabTextColors(@ColorInt int normalColor, @ColorInt int selectedColor) {\n\t\tmTextColor = createColorStateList(normalColor, selectedColor);\n\t}\n\n\tprivate static ColorStateList createColorStateList(int defaultColor, int selectedColor) {\n\t\tfinal int[] colors = new int[]{selectedColor, defaultColor};\n\t\treturn new ColorStateList(TAB_COLOR_STATES, colors);\n\t}\n\n\t\/**\n\t * Set the custom layout to be inflated for the tab views.\n\t *\n\t * @param layoutResId Layout id to be inflated\n\t * @param textViewId id of the {@link TextView} in the inflated view\n\t *\/\n\tpublic void setCustomTabView(@LayoutRes int layoutResId, @IdRes int textViewId) {\n\t\tmTabViewLayoutId = layoutResId;\n\t\tmTabViewTextViewId = textViewId;\n\t}\n\n\tpublic void setTabListener(TabListener tabListener) {\n\t\tmTabListener = tabListener;\n\t}\n\n\t\/**\n\t * Sets the associated view pager. Note that the assumption here is that the pager content\n\t * (number of tabs and tab titles) does not change after this call has been made.\n\t *\/\n\tpublic void setViewPager(ViewPager viewPager) {\n\t\tmViewPager = viewPager;\n\t\tif (viewPager != null) {\n\t\t\tviewPager.addOnPageChangeListener(new InternalViewPagerListener());\n\t\t}\n\t\tnotifyDataSetChanged();\n\t}\n\n\tpublic void notifyDataSetChanged() {\n\t\tmTabStrip.removeAllViews();\n\t\tif (mViewPager != null) {\n\t\t\tpopulateTabStrip();\n\t\t}\n\t}\n\n\tprivate void populateTabStrip() {\n\t\tfinal PagerAdapter adapter = mViewPager.getAdapter();\n\t\tfinal View.OnClickListener tabClickListener = new TabClickListener();\n\t\tfinal LayoutInflater inflater = LayoutInflater.from(getContext());\n\t\tfinal int currentItem = mViewPager.getCurrentItem();\n\n\t\tfor (int i = 0; i < adapter.getCount(); i++) {\n\t\t\tView tabView;\n\t\t\tTextView tabTitleView;\n\n\t\t\tif (mTabViewLayoutId != 0) {\n\t\t\t\t\/\/ If there is a custom tab view layout id set, try and inflate it\n\t\t\t\ttabView = inflater.inflate(mTabViewLayoutId, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);\n\t\t\t\tif (tabTitleView == null) {\n\t\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ Inflate our default tab layout\n\t\t\t\ttabView = inflater.inflate(R.layout.widget_sliding_tab_layout_text, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\tif (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {\n\t\t\t\t\t\/\/ Emulate Roboto Medium in previous Android versions\n\t\t\t\t\ttabTitleView.setTypeface(Typeface.DEFAULT_BOLD);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (mTextColor != null) {\n\t\t\t\ttabTitleView.setTextColor(mTextColor);\n\t\t\t}\n\n\t\t\tif (mDistributeEvenly) {\n\t\t\t\tLinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();\n\t\t\t\tlp.width = 0;\n\t\t\t\tlp.weight = 1;\n\t\t\t}\n\n\t\t\ttabTitleView.setText(adapter.getPageTitle(i));\n\t\t\ttabView.setFocusable(true);\n\t\t\ttabView.setOnClickListener(tabClickListener);\n\n\t\t\tmTabStrip.addView(tabView);\n\t\t\tif (i == currentItem) {\n\t\t\t\ttabView.setSelected(true);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tprotected void onAttachedToWindow() {\n\t\tsuper.onAttachedToWindow();\n\n\t\tif (mViewPager != null) {\n\t\t\tscrollToTab(mViewPager.getCurrentItem(), 0);\n\t\t}\n\t}\n\n\tprivate void scrollToTab(int tabIndex, float positionOffset) {\n\t\tfinal int tabStripChildCount = mTabStrip.getChildCount();\n\t\tif (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {\n\t\t\treturn;\n\t\t}\n\n\t\tView selectedChild = mTabStrip.getChildAt(tabIndex);\n\t\tif (selectedChild != null) {\n\t\t\tint targetScrollX = selectedChild.getLeft() +\n\t\t\t\t\tMath.round(positionOffset * selectedChild.getWidth()) - mTitleOffset;\n\n\t\t\tscrollTo(targetScrollX, 0);\n\t\t}\n\t}\n\n\tprivate class InternalViewPagerListener implements ViewPager.OnPageChangeListener {\n\t\tprivate int mScrollState;\n\n\t\t@Override\n\t\tpublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n\t\t\tint tabStripChildCount = mTabStrip.getChildCount();\n\t\t\tif ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tmTabStrip.onViewPagerPageChanged(position, positionOffset);\n\n\n\t\t\tscrollToTab(position, positionOffset);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageScrollStateChanged(int state) {\n\t\t\tmScrollState = state;\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageSelected(int position) {\n\t\t\tif (mScrollState == ViewPager.SCROLL_STATE_IDLE) {\n\t\t\t\tmTabStrip.onViewPagerPageChanged(position, 0f);\n\t\t\t\tscrollToTab(position, 0);\n\t\t\t}\n\t\t\tfor (int i = 0; i < mTabStrip.getChildCount(); i++) {\n\t\t\t\tmTabStrip.getChildAt(i).setSelected(position == i);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate class TabClickListener implements View.OnClickListener {\n\t\t@Override\n\t\tpublic void onClick(View v) {\n\t\t\tfor (int i = 0; i < mTabStrip.getChildCount(); i++) {\n\t\t\t\tif (v == mTabStrip.getChildAt(i)) {\n\t\t\t\t\tfinal int previousPos = mViewPager.getCurrentItem();\n\t\t\t\t\tmViewPager.setCurrentItem(i);\n\n\t\t\t\t\tif (mTabListener != null) {\n\t\t\t\t\t\tif (previousPos != i) {\n\t\t\t\t\t\t\tmTabListener.onTabSelected(i);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tmTabListener.onTabReSelected(i);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","target_code":"\/*\n * Copyright 2014 Chris Banes\n * Copyright 2016 Christophe Beyls\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage com.example.android.common.view;\n\nimport android.content.Context;\nimport android.content.res.ColorStateList;\nimport android.content.res.TypedArray;\nimport android.graphics.Typeface;\nimport android.os.Build;\nimport android.support.annotation.ColorInt;\nimport android.support.annotation.IdRes;\nimport android.support.annotation.LayoutRes;\nimport android.support.v4.view.PagerAdapter;\nimport android.support.v4.view.ViewPager;\nimport android.util.AttributeSet;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.widget.HorizontalScrollView;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\n\nimport be.digitalia.fosdem.R;\n\n\/**\n *\/\npublic class SlidingTabLayout extends HorizontalScrollView {\n\n\tpublic interface TabListener {\n\n\t\tvoid onTabSelected(int pos);\n\n\t\tvoid onTabReSelected(int pos);\n\n\t}\n\n\tprivate static final int[][] TAB_COLOR_STATES = new int[][]{SELECTED_STATE_SET, EMPTY_STATE_SET};\n\n\tprivate int mTitleOffset;\n\n\tprivate int mTabViewLayoutId;\n\tprivate int mTabViewTextViewId;\n\tprivate boolean mDistributeEvenly;\n\n\tprivate ColorStateList mTextColor;\n\n\tprivate ViewPager mViewPager;\n\n\tprivate TabListener mTabListener;\n\n\tprivate final SlidingTabStrip mTabStrip;\n\n\tpublic SlidingTabLayout(Context context) {\n\t\tthis(context, null);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs) {\n\t\tthis(context, attrs, 0);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {\n\t\tsuper(context, attrs, defStyle);\n\n\t\t\/\/ Disable the Scroll Bar\n\t\tsetHorizontalScrollBarEnabled(false);\n\t\t\/\/ Make sure that the Tab Strips fills this View\n\t\tsetFillViewport(true);\n\n\t\tmTabStrip = new SlidingTabStrip(context);\n\t\taddView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);\n\n\t\tTypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SlidingTabLayout,\n\t\t\t\tdefStyle, R.style.SlidingTabLayout);\n\n\t\tmTabStrip.setSelectedIndicatorHeight(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_indicatorHeight, 0));\n\t\tmTabStrip.setSelectedIndicatorColor(a.getColor(R.styleable.SlidingTabLayout_indicatorColor, 0));\n\t\tmTextColor = a.getColorStateList(R.styleable.SlidingTabLayout_textColor);\n\t\tif ((mTextColor != null) && a.hasValue(R.styleable.SlidingTabLayout_selectedTextColor)) {\n\t\t\tsetTabTextColors(mTextColor.getDefaultColor(), a.getColor(R.styleable.SlidingTabLayout_selectedTextColor, 0));\n\t\t}\n\t\tsetContentInsetStart(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_contentInsetStart, 0));\n\t\tsetDistributeEvenly(a.getBoolean(R.styleable.SlidingTabLayout_distributeEvenly, false));\n\n\t\ta.recycle();\n\t}\n\n\tpublic void setContentInsetStart(int offset) {\n\t\tmTitleOffset = offset;\n\t\tmTabStrip.setPadding(offset, 0, 0, 0);\n\t}\n\n\tpublic void setDistributeEvenly(boolean distributeEvenly) {\n\t\tmDistributeEvenly = distributeEvenly;\n\t}\n\n\t\/**\n\t * Sets the color to be used for indicating the selected tab.\n\t * This will override the style color.\n\t *\/\n\tpublic void setSelectedTabIndicatorColor(@ColorInt int color) {\n\t\tmTabStrip.setSelectedIndicatorColor(color);\n\t}\n\n\tpublic void setSelectedTabIndicatorHeight(int height) {\n\t\tmTabStrip.setSelectedIndicatorHeight(height);\n\t}\n\n\tpublic void setTabTextColors(ColorStateList color) {\n\t\tmTextColor = color;\n\t}\n\n\tpublic void setTabTextColors(@ColorInt int normalColor, @ColorInt int selectedColor) {\n\t\tmTextColor = createColorStateList(normalColor, selectedColor);\n\t}\n\n\tprivate static ColorStateList createColorStateList(int defaultColor, int selectedColor) {\n\t\tfinal int[] colors = new int[]{selectedColor, defaultColor};\n\t\treturn new ColorStateList(TAB_COLOR_STATES, colors);\n\t}\n\n\t\/**\n\t * Set the custom layout to be inflated for the tab views.\n\t *\n\t * @param layoutResId Layout id to be inflated\n\t * @param textViewId id of the {@link TextView} in the inflated view\n\t *\/\n\tpublic void setCustomTabView(@LayoutRes int layoutResId, @IdRes int textViewId) {\n\t\tmTabViewLayoutId = layoutResId;\n\t\tmTabViewTextViewId = textViewId;\n\t}\n\n\tpublic void setTabListener(TabListener tabListener) {\n\t\tmTabListener = tabListener;\n\t}\n\n\t\/**\n\t * Sets the associated view pager. Note that the assumption here is that the pager content\n\t * (number of tabs and tab titles) does not change after this call has been made.\n\t *\/\n\tpublic void setViewPager(ViewPager viewPager) {\n\t\tmViewPager = viewPager;\n\t\tif (viewPager != null) {\n\t\t\tviewPager.addOnPageChangeListener(new InternalViewPagerListener());\n\t\t}\n\t\tnotifyDataSetChanged();\n\t}\n\n\tpublic void notifyDataSetChanged() {\n\t\tmTabStrip.removeAllViews();\n\t\tif (mViewPager != null) {\n\t\t\tpopulateTabStrip();\n\t\t}\n\t}\n\n\tprivate void populateTabStrip() {\n\t\tfinal PagerAdapter adapter = mViewPager.getAdapter();\n\t\tfinal int adapterCount = adapter.getCount();\n\t\tfinal View.OnClickListener tabClickListener = new TabClickListener();\n\t\tfinal LayoutInflater inflater = LayoutInflater.from(getContext());\n\t\tfinal int currentItem = mViewPager.getCurrentItem();\n\n\t\tfor (int i = 0; i < adapterCount; i++) {\n\t\t\tView tabView;\n\t\t\tTextView tabTitleView;\n\n\t\t\tif (mTabViewLayoutId != 0) {\n\t\t\t\t\/\/ If there is a custom tab view layout id set, try and inflate it\n\t\t\t\ttabView = inflater.inflate(mTabViewLayoutId, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);\n\t\t\t\tif (tabTitleView == null) {\n\t\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ Inflate our default tab layout\n\t\t\t\ttabView = inflater.inflate(R.layout.widget_sliding_tab_layout_text, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\tif (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {\n\t\t\t\t\t\/\/ Emulate Roboto Medium in previous Android versions\n\t\t\t\t\ttabTitleView.setTypeface(Typeface.DEFAULT_BOLD);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (mTextColor != null) {\n\t\t\t\ttabTitleView.setTextColor(mTextColor);\n\t\t\t}\n\n\t\t\tif (mDistributeEvenly) {\n\t\t\t\tLinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();\n\t\t\t\tlp.width = 0;\n\t\t\t\tlp.weight = 1;\n\t\t\t}\n\n\t\t\ttabTitleView.setText(adapter.getPageTitle(i));\n\t\t\ttabView.setFocusable(true);\n\t\t\ttabView.setOnClickListener(tabClickListener);\n\n\t\t\tmTabStrip.addView(tabView);\n\t\t\tif (i == currentItem) {\n\t\t\t\ttabView.setSelected(true);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tprotected void onAttachedToWindow() {\n\t\tsuper.onAttachedToWindow();\n\n\t\tif (mViewPager != null) {\n\t\t\tscrollToTab(mViewPager.getCurrentItem(), 0);\n\t\t}\n\t}\n\n\tprivate void scrollToTab(int tabIndex, float positionOffset) {\n\t\tfinal int tabStripChildCount = mTabStrip.getChildCount();\n\t\tif (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {\n\t\t\treturn;\n\t\t}\n\n\t\tView selectedChild = mTabStrip.getChildAt(tabIndex);\n\t\tif (selectedChild != null) {\n\t\t\tint targetScrollX = selectedChild.getLeft() +\n\t\t\t\t\tMath.round(positionOffset * selectedChild.getWidth()) - mTitleOffset;\n\n\t\t\tscrollTo(targetScrollX, 0);\n\t\t}\n\t}\n\n\tprivate class InternalViewPagerListener implements ViewPager.OnPageChangeListener {\n\t\tprivate int mScrollState;\n\n\t\t@Override\n\t\tpublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n\t\t\tint tabStripChildCount = mTabStrip.getChildCount();\n\t\t\tif ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tmTabStrip.onViewPagerPageChanged(position, positionOffset);\n\n\n\t\t\tscrollToTab(position, positionOffset);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageScrollStateChanged(int state) {\n\t\t\tmScrollState = state;\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageSelected(int position) {\n\t\t\tif (mScrollState == ViewPager.SCROLL_STATE_IDLE) {\n\t\t\t\tmTabStrip.onViewPagerPageChanged(position, 0f);\n\t\t\t\tscrollToTab(position, 0);\n\t\t\t}\n\t\t\tfinal int childCount = mTabStrip.getChildCount();\n\t\t\tfor (int i = 0; i < childCount; i++) {\n\t\t\t\tmTabStrip.getChildAt(i).setSelected(position == i);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate class TabClickListener implements View.OnClickListener {\n\t\t@Override\n\t\tpublic void onClick(View v) {\n\t\t\tfinal int childCount = mTabStrip.getChildCount();\n\t\t\tfor (int i = 0; i < childCount; i++) {\n\t\t\t\tif (v == mTabStrip.getChildAt(i)) {\n\t\t\t\t\tfinal int previousPos = mViewPager.getCurrentItem();\n\t\t\t\t\tmViewPager.setCurrentItem(i);\n\n\t\t\t\t\tif (mTabListener != null) {\n\t\t\t\t\t\tif (previousPos != i) {\n\t\t\t\t\t\t\tmTabListener.onTabSelected(i);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tmTabListener.onTabReSelected(i);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright 2014 Chris Banes\n * Copyright 2016 Christophe Beyls\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage com.example.android.common.view;\n\nimport android.content.Context;\nimport android.content.res.ColorStateList;\nimport android.content.res.TypedArray;\nimport android.graphics.Typeface;\nimport android.os.Build;\nimport android.support.annotation.ColorInt;\nimport android.support.annotation.IdRes;\nimport android.support.annotation.LayoutRes;\nimport android.support.v4.view.PagerAdapter;\nimport android.support.v4.view.ViewPager;\nimport android.util.AttributeSet;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.widget.HorizontalScrollView;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\n\nimport be.digitalia.fosdem.R;\n\n\/**\n *\/\npublic class SlidingTabLayout extends HorizontalScrollView {\n\n\tpublic interface TabListener {\n\n\t\tvoid onTabSelected(int pos);\n\n\t\tvoid onTabReSelected(int pos);\n\n\t}\n\n\tprivate static final int[][] TAB_COLOR_STATES = new int[][]{SELECTED_STATE_SET, EMPTY_STATE_SET};\n\n\tprivate int mTitleOffset;\n\n\tprivate int mTabViewLayoutId;\n\tprivate int mTabViewTextViewId;\n\tprivate boolean mDistributeEvenly;\n\n\tprivate ColorStateList mTextColor;\n\n\tprivate ViewPager mViewPager;\n\n\tprivate TabListener mTabListener;\n\n\tprivate final SlidingTabStrip mTabStrip;\n\n\tpublic SlidingTabLayout(Context context) {\n\t\tthis(context, null);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs) {\n\t\tthis(context, attrs, 0);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {\n\t\tsuper(context, attrs, defStyle);\n\n\t\t\/\/ Disable the Scroll Bar\n\t\tsetHorizontalScrollBarEnabled(false);\n\t\t\/\/ Make sure that the Tab Strips fills this View\n\t\tsetFillViewport(true);\n\n\t\tmTabStrip = new SlidingTabStrip(context);\n\t\taddView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);\n\n\t\tTypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SlidingTabLayout,\n\t\t\t\tdefStyle, R.style.SlidingTabLayout);\n\n\t\tmTabStrip.setSelectedIndicatorHeight(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_indicatorHeight, 0));\n\t\tmTabStrip.setSelectedIndicatorColor(a.getColor(R.styleable.SlidingTabLayout_indicatorColor, 0));\n\t\tmTextColor = a.getColorStateList(R.styleable.SlidingTabLayout_textColor);\n\t\tif ((mTextColor != null) && a.hasValue(R.styleable.SlidingTabLayout_selectedTextColor)) {\n\t\t\tsetTabTextColors(mTextColor.getDefaultColor(), a.getColor(R.styleable.SlidingTabLayout_selectedTextColor, 0));\n\t\t}\n\t\tsetContentInsetStart(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_contentInsetStart, 0));\n\t\tsetDistributeEvenly(a.getBoolean(R.styleable.SlidingTabLayout_distributeEvenly, false));\n\n\t\ta.recycle();\n\t}\n\n\tpublic void setContentInsetStart(int offset) {\n\t\tmTitleOffset = offset;\n\t\tmTabStrip.setPadding(offset, 0, 0, 0);\n\t}\n\n\tpublic void setDistributeEvenly(boolean distributeEvenly) {\n\t\tmDistributeEvenly = distributeEvenly;\n\t}\n\n\t\/**\n\t * Sets the color to be used for indicating the selected tab.\n\t * This will override the style color.\n\t *\/\n\tpublic void setSelectedTabIndicatorColor(@ColorInt int color) {\n\t\tmTabStrip.setSelectedIndicatorColor(color);\n\t}\n\n\tpublic void setSelectedTabIndicatorHeight(int height) {\n\t\tmTabStrip.setSelectedIndicatorHeight(height);\n\t}\n\n\tpublic void setTabTextColors(ColorStateList color) {\n\t\tmTextColor = color;\n\t}\n\n\tpublic void setTabTextColors(@ColorInt int normalColor, @ColorInt int selectedColor) {\n\t\tmTextColor = createColorStateList(normalColor, selectedColor);\n\t}\n\n\tprivate static ColorStateList createColorStateList(int defaultColor, int selectedColor) {\n\t\tfinal int[] colors = new int[]{selectedColor, defaultColor};\n\t\treturn new ColorStateList(TAB_COLOR_STATES, colors);\n\t}\n\n\t\/**\n\t * Set the custom layout to be inflated for the tab views.\n\t *\n\t * @param layoutResId Layout id to be inflated\n\t * @param textViewId id of the {@link TextView} in the inflated view\n\t *\/\n\tpublic void setCustomTabView(@LayoutRes int layoutResId, @IdRes int textViewId) {\n\t\tmTabViewLayoutId = layoutResId;\n\t\tmTabViewTextViewId = textViewId;\n\t}\n\n\tpublic void setTabListener(TabListener tabListener) {\n\t\tmTabListener = tabListener;\n\t}\n\n\t\/**\n\t * Sets the associated view pager. Note that the assumption here is that the pager content\n\t * (number of tabs and tab titles) does not change after this call has been made.\n\t *\/\n\tpublic void setViewPager(ViewPager viewPager) {\n\t\tmViewPager = viewPager;\n\t\tif (viewPager != null) {\n\t\t\tviewPager.addOnPageChangeListener(new InternalViewPagerListener());\n\t\t}\n\t\tnotifyDataSetChanged();\n\t}\n\n\tpublic void notifyDataSetChanged() {\n\t\tmTabStrip.removeAllViews();\n\t\tif (mViewPager != null) {\n\t\t\tpopulateTabStrip();\n\t\t}\n\t}\n\n\tprivate void populateTabStrip() {\n\t\tfinal PagerAdapter adapter = mViewPager.getAdapter();\n\t\tfinal View.OnClickListener tabClickListener = new TabClickListener();\n\t\tfinal LayoutInflater inflater = LayoutInflater.from(getContext());\n\t\tfinal int currentItem = mViewPager.getCurrentItem();\n\n\t\tfor (int i = 0; i < adapter.getCount(); i++) {\n\t\t\tView tabView;\n\t\t\tTextView tabTitleView;\n\n\t\t\tif (mTabViewLayoutId != 0) {\n\t\t\t\t\/\/ If there is a custom tab view layout id set, try and inflate it\n\t\t\t\ttabView = inflater.inflate(mTabViewLayoutId, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);\n\t\t\t\tif (tabTitleView == null) {\n\t\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ Inflate our default tab layout\n\t\t\t\ttabView = inflater.inflate(R.layout.widget_sliding_tab_layout_text, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\tif (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {\n\t\t\t\t\t\/\/ Emulate Roboto Medium in previous Android versions\n\t\t\t\t\ttabTitleView.setTypeface(Typeface.DEFAULT_BOLD);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (mTextColor != null) {\n\t\t\t\ttabTitleView.setTextColor(mTextColor);\n\t\t\t}\n\n\t\t\tif (mDistributeEvenly) {\n\t\t\t\tLinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();\n\t\t\t\tlp.width = 0;\n\t\t\t\tlp.weight = 1;\n\t\t\t}\n\n\t\t\ttabTitleView.setText(adapter.getPageTitle(i));\n\t\t\ttabView.setFocusable(true);\n\t\t\ttabView.setOnClickListener(tabClickListener);\n\n\t\t\tmTabStrip.addView(tabView);\n\t\t\tif (i == currentItem) {\n\t\t\t\ttabView.setSelected(true);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tprotected void onAttachedToWindow() {\n\t\tsuper.onAttachedToWindow();\n\n\t\tif (mViewPager != null) {\n\t\t\tscrollToTab(mViewPager.getCurrentItem(), 0);\n\t\t}\n\t}\n\n\tprivate void scrollToTab(int tabIndex, float positionOffset) {\n\t\tfinal int tabStripChildCount = mTabStrip.getChildCount();\n\t\tif (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {\n\t\t\treturn;\n\t\t}\n\n\t\tView selectedChild = mTabStrip.getChildAt(tabIndex);\n\t\tif (selectedChild != null) {\n\t\t\tint targetScrollX = selectedChild.getLeft() +\n\t\t\t\t\tMath.round(positionOffset * selectedChild.getWidth()) - mTitleOffset;\n\n\t\t\tscrollTo(targetScrollX, 0);\n\t\t}\n\t}\n\n\tprivate class InternalViewPagerListener implements ViewPager.OnPageChangeListener {\n\t\tprivate int mScrollState;\n\n\t\t@Override\n\t\tpublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n\t\t\tint tabStripChildCount = mTabStrip.getChildCount();\n\t\t\tif ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tmTabStrip.onViewPagerPageChanged(position, positionOffset);\n\n\n\t\t\tscrollToTab(position, positionOffset);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageScrollStateChanged(int state) {\n\t\t\tmScrollState = state;\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageSelected(int position) {\n\t\t\tif (mScrollState == ViewPager.SCROLL_STATE_IDLE) {\n\t\t\t\tmTabStrip.onViewPagerPageChanged(position, 0f);\n\t\t\t\tscrollToTab(position, 0);\n\t\t\t}\n\t\t\tfor (int i = 0; i < mTabStrip.getChildCount(); i++) {\n\t\t\t\tmTabStrip.getChildAt(i).setSelected(position == i);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate class TabClickListener implements View.OnClickListener {\n\t\t@Override\n\t\tpublic void onClick(View v) {\n\t\t\tfor (int i = 0; i < mTabStrip.getChildCount(); i++) {\n\t\t\t\tif (v == mTabStrip.getChildAt(i)) {\n\t\t\t\t\tfinal int previousPos = mViewPager.getCurrentItem();\n\t\t\t\t\tmViewPager.setCurrentItem(i);\n\n\t\t\t\t\tif (mTabListener != null) {\n\t\t\t\t\t\tif (previousPos != i) {\n\t\t\t\t\t\t\tmTabListener.onTabSelected(i);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tmTabListener.onTabReSelected(i);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright 2014 Chris Banes\n * Copyright 2016 Christophe Beyls\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage com.example.android.common.view;\n\nimport android.content.Context;\nimport android.content.res.ColorStateList;\nimport android.content.res.TypedArray;\nimport android.graphics.Typeface;\nimport android.os.Build;\nimport android.support.annotation.ColorInt;\nimport android.support.annotation.IdRes;\nimport android.support.annotation.LayoutRes;\nimport android.support.v4.view.PagerAdapter;\nimport android.support.v4.view.ViewPager;\nimport android.util.AttributeSet;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.widget.HorizontalScrollView;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\n\nimport be.digitalia.fosdem.R;\n\n\/**\n *\/\npublic class SlidingTabLayout extends HorizontalScrollView {\n\n\tpublic interface TabListener {\n\n\t\tvoid onTabSelected(int pos);\n\n\t\tvoid onTabReSelected(int pos);\n\n\t}\n\n\tprivate static final int[][] TAB_COLOR_STATES = new int[][]{SELECTED_STATE_SET, EMPTY_STATE_SET};\n\n\tprivate int mTitleOffset;\n\n\tprivate int mTabViewLayoutId;\n\tprivate int mTabViewTextViewId;\n\tprivate boolean mDistributeEvenly;\n\n\tprivate ColorStateList mTextColor;\n\n\tprivate ViewPager mViewPager;\n\n\tprivate TabListener mTabListener;\n\n\tprivate final SlidingTabStrip mTabStrip;\n\n\tpublic SlidingTabLayout(Context context) {\n\t\tthis(context, null);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs) {\n\t\tthis(context, attrs, 0);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {\n\t\tsuper(context, attrs, defStyle);\n\n\t\t\/\/ Disable the Scroll Bar\n\t\tsetHorizontalScrollBarEnabled(false);\n\t\t\/\/ Make sure that the Tab Strips fills this View\n\t\tsetFillViewport(true);\n\n\t\tmTabStrip = new SlidingTabStrip(context);\n\t\taddView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);\n\n\t\tTypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SlidingTabLayout,\n\t\t\t\tdefStyle, R.style.SlidingTabLayout);\n\n\t\tmTabStrip.setSelectedIndicatorHeight(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_indicatorHeight, 0));\n\t\tmTabStrip.setSelectedIndicatorColor(a.getColor(R.styleable.SlidingTabLayout_indicatorColor, 0));\n\t\tmTextColor = a.getColorStateList(R.styleable.SlidingTabLayout_textColor);\n\t\tif ((mTextColor != null) && a.hasValue(R.styleable.SlidingTabLayout_selectedTextColor)) {\n\t\t\tsetTabTextColors(mTextColor.getDefaultColor(), a.getColor(R.styleable.SlidingTabLayout_selectedTextColor, 0));\n\t\t}\n\t\tsetContentInsetStart(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_contentInsetStart, 0));\n\t\tsetDistributeEvenly(a.getBoolean(R.styleable.SlidingTabLayout_distributeEvenly, false));\n\n\t\ta.recycle();\n\t}\n\n\tpublic void setContentInsetStart(int offset) {\n\t\tmTitleOffset = offset;\n\t\tmTabStrip.setPadding(offset, 0, 0, 0);\n\t}\n\n\tpublic void setDistributeEvenly(boolean distributeEvenly) {\n\t\tmDistributeEvenly = distributeEvenly;\n\t}\n\n\t\/**\n\t * Sets the color to be used for indicating the selected tab.\n\t * This will override the style color.\n\t *\/\n\tpublic void setSelectedTabIndicatorColor(@ColorInt int color) {\n\t\tmTabStrip.setSelectedIndicatorColor(color);\n\t}\n\n\tpublic void setSelectedTabIndicatorHeight(int height) {\n\t\tmTabStrip.setSelectedIndicatorHeight(height);\n\t}\n\n\tpublic void setTabTextColors(ColorStateList color) {\n\t\tmTextColor = color;\n\t}\n\n\tpublic void setTabTextColors(@ColorInt int normalColor, @ColorInt int selectedColor) {\n\t\tmTextColor = createColorStateList(normalColor, selectedColor);\n\t}\n\n\tprivate static ColorStateList createColorStateList(int defaultColor, int selectedColor) {\n\t\tfinal int[] colors = new int[]{selectedColor, defaultColor};\n\t\treturn new ColorStateList(TAB_COLOR_STATES, colors);\n\t}\n\n\t\/**\n\t * Set the custom layout to be inflated for the tab views.\n\t *\n\t * @param layoutResId Layout id to be inflated\n\t * @param textViewId id of the {@link TextView} in the inflated view\n\t *\/\n\tpublic void setCustomTabView(@LayoutRes int layoutResId, @IdRes int textViewId) {\n\t\tmTabViewLayoutId = layoutResId;\n\t\tmTabViewTextViewId = textViewId;\n\t}\n\n\tpublic void setTabListener(TabListener tabListener) {\n\t\tmTabListener = tabListener;\n\t}\n\n\t\/**\n\t * Sets the associated view pager. Note that the assumption here is that the pager content\n\t * (number of tabs and tab titles) does not change after this call has been made.\n\t *\/\n\tpublic void setViewPager(ViewPager viewPager) {\n\t\tmViewPager = viewPager;\n\t\tif (viewPager != null) {\n\t\t\tviewPager.addOnPageChangeListener(new InternalViewPagerListener());\n\t\t}\n\t\tnotifyDataSetChanged();\n\t}\n\n\tpublic void notifyDataSetChanged() {\n\t\tmTabStrip.removeAllViews();\n\t\tif (mViewPager != null) {\n\t\t\tpopulateTabStrip();\n\t\t}\n\t}\n\n\tprivate void populateTabStrip() {\n\t\tfinal PagerAdapter adapter = mViewPager.getAdapter();\n\t\tfinal View.OnClickListener tabClickListener = new TabClickListener();\n\t\tfinal LayoutInflater inflater = LayoutInflater.from(getContext());\n\t\tfinal int currentItem = mViewPager.getCurrentItem();\n\n\t\tfor (int i = 0; i < adapter.getCount(); i++) {\n\t\t\tView tabView;\n\t\t\tTextView tabTitleView;\n\n\t\t\tif (mTabViewLayoutId != 0) {\n\t\t\t\t\/\/ If there is a custom tab view layout id set, try and inflate it\n\t\t\t\ttabView = inflater.inflate(mTabViewLayoutId, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);\n\t\t\t\tif (tabTitleView == null) {\n\t\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ Inflate our default tab layout\n\t\t\t\ttabView = inflater.inflate(R.layout.widget_sliding_tab_layout_text, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\tif (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {\n\t\t\t\t\t\/\/ Emulate Roboto Medium in previous Android versions\n\t\t\t\t\ttabTitleView.setTypeface(Typeface.DEFAULT_BOLD);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (mTextColor != null) {\n\t\t\t\ttabTitleView.setTextColor(mTextColor);\n\t\t\t}\n\n\t\t\tif (mDistributeEvenly) {\n\t\t\t\tLinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();\n\t\t\t\tlp.width = 0;\n\t\t\t\tlp.weight = 1;\n\t\t\t}\n\n\t\t\ttabTitleView.setText(adapter.getPageTitle(i));\n\t\t\ttabView.setFocusable(true);\n\t\t\ttabView.setOnClickListener(tabClickListener);\n\n\t\t\tmTabStrip.addView(tabView);\n\t\t\tif (i == currentItem) {\n\t\t\t\ttabView.setSelected(true);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tprotected void onAttachedToWindow() {\n\t\tsuper.onAttachedToWindow();\n\n\t\tif (mViewPager != null) {\n\t\t\tscrollToTab(mViewPager.getCurrentItem(), 0);\n\t\t}\n\t}\n\n\tprivate void scrollToTab(int tabIndex, float positionOffset) {\n\t\tfinal int tabStripChildCount = mTabStrip.getChildCount();\n\t\tif (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {\n\t\t\treturn;\n\t\t}\n\n\t\tView selectedChild = mTabStrip.getChildAt(tabIndex);\n\t\tif (selectedChild != null) {\n\t\t\tint targetScrollX = selectedChild.getLeft() +\n\t\t\t\t\tMath.round(positionOffset * selectedChild.getWidth()) - mTitleOffset;\n\n\t\t\tscrollTo(targetScrollX, 0);\n\t\t}\n\t}\n\n\tprivate class InternalViewPagerListener implements ViewPager.OnPageChangeListener {\n\t\tprivate int mScrollState;\n\n\t\t@Override\n\t\tpublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n\t\t\tint tabStripChildCount = mTabStrip.getChildCount();\n\t\t\tif ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tmTabStrip.onViewPagerPageChanged(position, positionOffset);\n\n\n\t\t\tscrollToTab(position, positionOffset);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageScrollStateChanged(int state) {\n\t\t\tmScrollState = state;\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageSelected(int position) {\n\t\t\tif (mScrollState == ViewPager.SCROLL_STATE_IDLE) {\n\t\t\t\tmTabStrip.onViewPagerPageChanged(position, 0f);\n\t\t\t\tscrollToTab(position, 0);\n\t\t\t}\n\t\t\tfor (int i = 0; i < mTabStrip.getChildCount(); i++) {\n\t\t\t\tmTabStrip.getChildAt(i).setSelected(position == i);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate class TabClickListener implements View.OnClickListener {\n\t\t@Override\n\t\tpublic void onClick(View v) {\n\t\t\tfor (int i = 0; i < mTabStrip.getChildCount(); i++) {\n\t\t\t\tif (v == mTabStrip.getChildAt(i)) {\n\t\t\t\t\tfinal int previousPos = mViewPager.getCurrentItem();\n\t\t\t\t\tmViewPager.setCurrentItem(i);\n\n\t\t\t\t\tif (mTabListener != null) {\n\t\t\t\t\t\tif (previousPos != i) {\n\t\t\t\t\t\t\tmTabListener.onTabSelected(i);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tmTabListener.onTabReSelected(i);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright 2014 Chris Banes\n * Copyright 2016 Christophe Beyls\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage com.example.android.common.view;\n\nimport android.content.Context;\nimport android.content.res.ColorStateList;\nimport android.content.res.TypedArray;\nimport android.graphics.Typeface;\nimport android.os.Build;\nimport android.support.annotation.ColorInt;\nimport android.support.annotation.IdRes;\nimport android.support.annotation.LayoutRes;\nimport android.support.v4.view.PagerAdapter;\nimport android.support.v4.view.ViewPager;\nimport android.util.AttributeSet;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.widget.HorizontalScrollView;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\n\nimport be.digitalia.fosdem.R;\n\n\/**\n *\/\npublic class SlidingTabLayout extends HorizontalScrollView {\n\n\tpublic interface TabListener {\n\n\t\tvoid onTabSelected(int pos);\n\n\t\tvoid onTabReSelected(int pos);\n\n\t}\n\n\tprivate static final int[][] TAB_COLOR_STATES = new int[][]{SELECTED_STATE_SET, EMPTY_STATE_SET};\n\n\tprivate int mTitleOffset;\n\n\tprivate int mTabViewLayoutId;\n\tprivate int mTabViewTextViewId;\n\tprivate boolean mDistributeEvenly;\n\n\tprivate ColorStateList mTextColor;\n\n\tprivate ViewPager mViewPager;\n\n\tprivate TabListener mTabListener;\n\n\tprivate final SlidingTabStrip mTabStrip;\n\n\tpublic SlidingTabLayout(Context context) {\n\t\tthis(context, null);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs) {\n\t\tthis(context, attrs, 0);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {\n\t\tsuper(context, attrs, defStyle);\n\n\t\t\/\/ Disable the Scroll Bar\n\t\tsetHorizontalScrollBarEnabled(false);\n\t\t\/\/ Make sure that the Tab Strips fills this View\n\t\tsetFillViewport(true);\n\n\t\tmTabStrip = new SlidingTabStrip(context);\n\t\taddView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);\n\n\t\tTypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SlidingTabLayout,\n\t\t\t\tdefStyle, R.style.SlidingTabLayout);\n\n\t\tmTabStrip.setSelectedIndicatorHeight(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_indicatorHeight, 0));\n\t\tmTabStrip.setSelectedIndicatorColor(a.getColor(R.styleable.SlidingTabLayout_indicatorColor, 0));\n\t\tmTextColor = a.getColorStateList(R.styleable.SlidingTabLayout_textColor);\n\t\tif ((mTextColor != null) && a.hasValue(R.styleable.SlidingTabLayout_selectedTextColor)) {\n\t\t\tsetTabTextColors(mTextColor.getDefaultColor(), a.getColor(R.styleable.SlidingTabLayout_selectedTextColor, 0));\n\t\t}\n\t\tsetContentInsetStart(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_contentInsetStart, 0));\n\t\tsetDistributeEvenly(a.getBoolean(R.styleable.SlidingTabLayout_distributeEvenly, false));\n\n\t\ta.recycle();\n\t}\n\n\tpublic void setContentInsetStart(int offset) {\n\t\tmTitleOffset = offset;\n\t\tmTabStrip.setPadding(offset, 0, 0, 0);\n\t}\n\n\tpublic void setDistributeEvenly(boolean distributeEvenly) {\n\t\tmDistributeEvenly = distributeEvenly;\n\t}\n\n\t\/**\n\t * Sets the color to be used for indicating the selected tab.\n\t * This will override the style color.\n\t *\/\n\tpublic void setSelectedTabIndicatorColor(@ColorInt int color) {\n\t\tmTabStrip.setSelectedIndicatorColor(color);\n\t}\n\n\tpublic void setSelectedTabIndicatorHeight(int height) {\n\t\tmTabStrip.setSelectedIndicatorHeight(height);\n\t}\n\n\tpublic void setTabTextColors(ColorStateList color) {\n\t\tmTextColor = color;\n\t}\n\n\tpublic void setTabTextColors(@ColorInt int normalColor, @ColorInt int selectedColor) {\n\t\tmTextColor = createColorStateList(normalColor, selectedColor);\n\t}\n\n\tprivate static ColorStateList createColorStateList(int defaultColor, int selectedColor) {\n\t\tfinal int[] colors = new int[]{selectedColor, defaultColor};\n\t\treturn new ColorStateList(TAB_COLOR_STATES, colors);\n\t}\n\n\t\/**\n\t * Set the custom layout to be inflated for the tab views.\n\t *\n\t * @param layoutResId Layout id to be inflated\n\t * @param textViewId id of the {@link TextView} in the inflated view\n\t *\/\n\tpublic void setCustomTabView(@LayoutRes int layoutResId, @IdRes int textViewId) {\n\t\tmTabViewLayoutId = layoutResId;\n\t\tmTabViewTextViewId = textViewId;\n\t}\n\n\tpublic void setTabListener(TabListener tabListener) {\n\t\tmTabListener = tabListener;\n\t}\n\n\t\/**\n\t * Sets the associated view pager. Note that the assumption here is that the pager content\n\t * (number of tabs and tab titles) does not change after this call has been made.\n\t *\/\n\tpublic void setViewPager(ViewPager viewPager) {\n\t\tmViewPager = viewPager;\n\t\tif (viewPager != null) {\n\t\t\tviewPager.addOnPageChangeListener(new InternalViewPagerListener());\n\t\t}\n\t\tnotifyDataSetChanged();\n\t}\n\n\tpublic void notifyDataSetChanged() {\n\t\tmTabStrip.removeAllViews();\n\t\tif (mViewPager != null) {\n\t\t\tpopulateTabStrip();\n\t\t}\n\t}\n\n\tprivate void populateTabStrip() {\n\t\tfinal PagerAdapter adapter = mViewPager.getAdapter();\n\t\tfinal View.OnClickListener tabClickListener = new TabClickListener();\n\t\tfinal LayoutInflater inflater = LayoutInflater.from(getContext());\n\t\tfinal int currentItem = mViewPager.getCurrentItem();\n\n\t\tfor (int i = 0; i < adapter.getCount(); i++) {\n\t\t\tView tabView;\n\t\t\tTextView tabTitleView;\n\n\t\t\tif (mTabViewLayoutId != 0) {\n\t\t\t\t\/\/ If there is a custom tab view layout id set, try and inflate it\n\t\t\t\ttabView = inflater.inflate(mTabViewLayoutId, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);\n\t\t\t\tif (tabTitleView == null) {\n\t\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ Inflate our default tab layout\n\t\t\t\ttabView = inflater.inflate(R.layout.widget_sliding_tab_layout_text, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\tif (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {\n\t\t\t\t\t\/\/ Emulate Roboto Medium in previous Android versions\n\t\t\t\t\ttabTitleView.setTypeface(Typeface.DEFAULT_BOLD);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (mTextColor != null) {\n\t\t\t\ttabTitleView.setTextColor(mTextColor);\n\t\t\t}\n\n\t\t\tif (mDistributeEvenly) {\n\t\t\t\tLinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();\n\t\t\t\tlp.width = 0;\n\t\t\t\tlp.weight = 1;\n\t\t\t}\n\n\t\t\ttabTitleView.setText(adapter.getPageTitle(i));\n\t\t\ttabView.setFocusable(true);\n\t\t\ttabView.setOnClickListener(tabClickListener);\n\n\t\t\tmTabStrip.addView(tabView);\n\t\t\tif (i == currentItem) {\n\t\t\t\ttabView.setSelected(true);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tprotected void onAttachedToWindow() {\n\t\tsuper.onAttachedToWindow();\n\n\t\tif (mViewPager != null) {\n\t\t\tscrollToTab(mViewPager.getCurrentItem(), 0);\n\t\t}\n\t}\n\n\tprivate void scrollToTab(int tabIndex, float positionOffset) {\n\t\tfinal int tabStripChildCount = mTabStrip.getChildCount();\n\t\tif (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {\n\t\t\treturn;\n\t\t}\n\n\t\tView selectedChild = mTabStrip.getChildAt(tabIndex);\n\t\tif (selectedChild != null) {\n\t\t\tint targetScrollX = selectedChild.getLeft() +\n\t\t\t\t\tMath.round(positionOffset * selectedChild.getWidth()) - mTitleOffset;\n\n\t\t\tscrollTo(targetScrollX, 0);\n\t\t}\n\t}\n\n\tprivate class InternalViewPagerListener implements ViewPager.OnPageChangeListener {\n\t\tprivate int mScrollState;\n\n\t\t@Override\n\t\tpublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n\t\t\tint tabStripChildCount = mTabStrip.getChildCount();\n\t\t\tif ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tmTabStrip.onViewPagerPageChanged(position, positionOffset);\n\n\n\t\t\tscrollToTab(position, positionOffset);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageScrollStateChanged(int state) {\n\t\t\tmScrollState = state;\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageSelected(int position) {\n\t\t\tif (mScrollState == ViewPager.SCROLL_STATE_IDLE) {\n\t\t\t\tmTabStrip.onViewPagerPageChanged(position, 0f);\n\t\t\t\tscrollToTab(position, 0);\n\t\t\t}\n\t\t\tfor (int i = 0; i < mTabStrip.getChildCount(); i++) {\n\t\t\t\tmTabStrip.getChildAt(i).setSelected(position == i);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate class TabClickListener implements View.OnClickListener {\n\t\t@Override\n\t\tpublic void onClick(View v) {\n\t\t\tfor (int i = 0; i < mTabStrip.getChildCount(); i++) {\n\t\t\t\tif (v == mTabStrip.getChildAt(i)) {\n\t\t\t\t\tfinal int previousPos = mViewPager.getCurrentItem();\n\t\t\t\t\tmViewPager.setCurrentItem(i);\n\n\t\t\t\t\tif (mTabListener != null) {\n\t\t\t\t\t\tif (previousPos != i) {\n\t\t\t\t\t\t\tmTabListener.onTabSelected(i);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tmTabListener.onTabReSelected(i);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nOptimize iteration performance in SlidingTabLayout. Write the entire code and no other text in the response.\n\n### Concepts:\n[in] populateTabStrip function\n[in] onPageSelected function\n[in] onClick function\n[+] final int\n\n### Given program:\n```java\n\/*\n * Copyright 2014 Chris Banes\n * Copyright 2016 Christophe Beyls\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage com.example.android.common.view;\n\nimport android.content.Context;\nimport android.content.res.ColorStateList;\nimport android.content.res.TypedArray;\nimport android.graphics.Typeface;\nimport android.os.Build;\nimport android.support.annotation.ColorInt;\nimport android.support.annotation.IdRes;\nimport android.support.annotation.LayoutRes;\nimport android.support.v4.view.PagerAdapter;\nimport android.support.v4.view.ViewPager;\nimport android.util.AttributeSet;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.widget.HorizontalScrollView;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\n\nimport be.digitalia.fosdem.R;\n\n\/**\n *\/\npublic class SlidingTabLayout extends HorizontalScrollView {\n\n\tpublic interface TabListener {\n\n\t\tvoid onTabSelected(int pos);\n\n\t\tvoid onTabReSelected(int pos);\n\n\t}\n\n\tprivate static final int[][] TAB_COLOR_STATES = new int[][]{SELECTED_STATE_SET, EMPTY_STATE_SET};\n\n\tprivate int mTitleOffset;\n\n\tprivate int mTabViewLayoutId;\n\tprivate int mTabViewTextViewId;\n\tprivate boolean mDistributeEvenly;\n\n\tprivate ColorStateList mTextColor;\n\n\tprivate ViewPager mViewPager;\n\n\tprivate TabListener mTabListener;\n\n\tprivate final SlidingTabStrip mTabStrip;\n\n\tpublic SlidingTabLayout(Context context) {\n\t\tthis(context, null);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs) {\n\t\tthis(context, attrs, 0);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {\n\t\tsuper(context, attrs, defStyle);\n\n\t\t\/\/ Disable the Scroll Bar\n\t\tsetHorizontalScrollBarEnabled(false);\n\t\t\/\/ Make sure that the Tab Strips fills this View\n\t\tsetFillViewport(true);\n\n\t\tmTabStrip = new SlidingTabStrip(context);\n\t\taddView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);\n\n\t\tTypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SlidingTabLayout,\n\t\t\t\tdefStyle, R.style.SlidingTabLayout);\n\n\t\tmTabStrip.setSelectedIndicatorHeight(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_indicatorHeight, 0));\n\t\tmTabStrip.setSelectedIndicatorColor(a.getColor(R.styleable.SlidingTabLayout_indicatorColor, 0));\n\t\tmTextColor = a.getColorStateList(R.styleable.SlidingTabLayout_textColor);\n\t\tif ((mTextColor != null) && a.hasValue(R.styleable.SlidingTabLayout_selectedTextColor)) {\n\t\t\tsetTabTextColors(mTextColor.getDefaultColor(), a.getColor(R.styleable.SlidingTabLayout_selectedTextColor, 0));\n\t\t}\n\t\tsetContentInsetStart(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_contentInsetStart, 0));\n\t\tsetDistributeEvenly(a.getBoolean(R.styleable.SlidingTabLayout_distributeEvenly, false));\n\n\t\ta.recycle();\n\t}\n\n\tpublic void setContentInsetStart(int offset) {\n\t\tmTitleOffset = offset;\n\t\tmTabStrip.setPadding(offset, 0, 0, 0);\n\t}\n\n\tpublic void setDistributeEvenly(boolean distributeEvenly) {\n\t\tmDistributeEvenly = distributeEvenly;\n\t}\n\n\t\/**\n\t * Sets the color to be used for indicating the selected tab.\n\t * This will override the style color.\n\t *\/\n\tpublic void setSelectedTabIndicatorColor(@ColorInt int color) {\n\t\tmTabStrip.setSelectedIndicatorColor(color);\n\t}\n\n\tpublic void setSelectedTabIndicatorHeight(int height) {\n\t\tmTabStrip.setSelectedIndicatorHeight(height);\n\t}\n\n\tpublic void setTabTextColors(ColorStateList color) {\n\t\tmTextColor = color;\n\t}\n\n\tpublic void setTabTextColors(@ColorInt int normalColor, @ColorInt int selectedColor) {\n\t\tmTextColor = createColorStateList(normalColor, selectedColor);\n\t}\n\n\tprivate static ColorStateList createColorStateList(int defaultColor, int selectedColor) {\n\t\tfinal int[] colors = new int[]{selectedColor, defaultColor};\n\t\treturn new ColorStateList(TAB_COLOR_STATES, colors);\n\t}\n\n\t\/**\n\t * Set the custom layout to be inflated for the tab views.\n\t *\n\t * @param layoutResId Layout id to be inflated\n\t * @param textViewId id of the {@link TextView} in the inflated view\n\t *\/\n\tpublic void setCustomTabView(@LayoutRes int layoutResId, @IdRes int textViewId) {\n\t\tmTabViewLayoutId = layoutResId;\n\t\tmTabViewTextViewId = textViewId;\n\t}\n\n\tpublic void setTabListener(TabListener tabListener) {\n\t\tmTabListener = tabListener;\n\t}\n\n\t\/**\n\t * Sets the associated view pager. Note that the assumption here is that the pager content\n\t * (number of tabs and tab titles) does not change after this call has been made.\n\t *\/\n\tpublic void setViewPager(ViewPager viewPager) {\n\t\tmViewPager = viewPager;\n\t\tif (viewPager != null) {\n\t\t\tviewPager.addOnPageChangeListener(new InternalViewPagerListener());\n\t\t}\n\t\tnotifyDataSetChanged();\n\t}\n\n\tpublic void notifyDataSetChanged() {\n\t\tmTabStrip.removeAllViews();\n\t\tif (mViewPager != null) {\n\t\t\tpopulateTabStrip();\n\t\t}\n\t}\n\n\tprivate void populateTabStrip() {\n\t\tfinal PagerAdapter adapter = mViewPager.getAdapter();\n\t\tfinal View.OnClickListener tabClickListener = new TabClickListener();\n\t\tfinal LayoutInflater inflater = LayoutInflater.from(getContext());\n\t\tfinal int currentItem = mViewPager.getCurrentItem();\n\n\t\tfor (int i = 0; i < adapter.getCount(); i++) {\n\t\t\tView tabView;\n\t\t\tTextView tabTitleView;\n\n\t\t\tif (mTabViewLayoutId != 0) {\n\t\t\t\t\/\/ If there is a custom tab view layout id set, try and inflate it\n\t\t\t\ttabView = inflater.inflate(mTabViewLayoutId, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);\n\t\t\t\tif (tabTitleView == null) {\n\t\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ Inflate our default tab layout\n\t\t\t\ttabView = inflater.inflate(R.layout.widget_sliding_tab_layout_text, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\tif (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {\n\t\t\t\t\t\/\/ Emulate Roboto Medium in previous Android versions\n\t\t\t\t\ttabTitleView.setTypeface(Typeface.DEFAULT_BOLD);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (mTextColor != null) {\n\t\t\t\ttabTitleView.setTextColor(mTextColor);\n\t\t\t}\n\n\t\t\tif (mDistributeEvenly) {\n\t\t\t\tLinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();\n\t\t\t\tlp.width = 0;\n\t\t\t\tlp.weight = 1;\n\t\t\t}\n\n\t\t\ttabTitleView.setText(adapter.getPageTitle(i));\n\t\t\ttabView.setFocusable(true);\n\t\t\ttabView.setOnClickListener(tabClickListener);\n\n\t\t\tmTabStrip.addView(tabView);\n\t\t\tif (i == currentItem) {\n\t\t\t\ttabView.setSelected(true);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tprotected void onAttachedToWindow() {\n\t\tsuper.onAttachedToWindow();\n\n\t\tif (mViewPager != null) {\n\t\t\tscrollToTab(mViewPager.getCurrentItem(), 0);\n\t\t}\n\t}\n\n\tprivate void scrollToTab(int tabIndex, float positionOffset) {\n\t\tfinal int tabStripChildCount = mTabStrip.getChildCount();\n\t\tif (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {\n\t\t\treturn;\n\t\t}\n\n\t\tView selectedChild = mTabStrip.getChildAt(tabIndex);\n\t\tif (selectedChild != null) {\n\t\t\tint targetScrollX = selectedChild.getLeft() +\n\t\t\t\t\tMath.round(positionOffset * selectedChild.getWidth()) - mTitleOffset;\n\n\t\t\tscrollTo(targetScrollX, 0);\n\t\t}\n\t}\n\n\tprivate class InternalViewPagerListener implements ViewPager.OnPageChangeListener {\n\t\tprivate int mScrollState;\n\n\t\t@Override\n\t\tpublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n\t\t\tint tabStripChildCount = mTabStrip.getChildCount();\n\t\t\tif ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tmTabStrip.onViewPagerPageChanged(position, positionOffset);\n\n\n\t\t\tscrollToTab(position, positionOffset);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageScrollStateChanged(int state) {\n\t\t\tmScrollState = state;\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageSelected(int position) {\n\t\t\tif (mScrollState == ViewPager.SCROLL_STATE_IDLE) {\n\t\t\t\tmTabStrip.onViewPagerPageChanged(position, 0f);\n\t\t\t\tscrollToTab(position, 0);\n\t\t\t}\n\t\t\tfor (int i = 0; i < mTabStrip.getChildCount(); i++) {\n\t\t\t\tmTabStrip.getChildAt(i).setSelected(position == i);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate class TabClickListener implements View.OnClickListener {\n\t\t@Override\n\t\tpublic void onClick(View v) {\n\t\t\tfor (int i = 0; i < mTabStrip.getChildCount(); i++) {\n\t\t\t\tif (v == mTabStrip.getChildAt(i)) {\n\t\t\t\t\tfinal int previousPos = mViewPager.getCurrentItem();\n\t\t\t\t\tmViewPager.setCurrentItem(i);\n\n\t\t\t\t\tif (mTabListener != null) {\n\t\t\t\t\t\tif (previousPos != i) {\n\t\t\t\t\t\t\tmTabListener.onTabSelected(i);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tmTabListener.onTabReSelected(i);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.antony.muzei.pixiv;\n\nimport android.content.SharedPreferences;\nimport android.os.Bundle;\nimport android.widget.Toast;\n\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.preference.Preference;\nimport androidx.preference.PreferenceFragmentCompat;\nimport androidx.preference.PreferenceManager;\nimport androidx.work.Constraints;\nimport androidx.work.ExistingPeriodicWorkPolicy;\nimport androidx.work.NetworkType;\nimport androidx.work.PeriodicWorkRequest;\nimport androidx.work.WorkManager;\n\nimport com.antony.muzei.pixiv.ClearCacheWorker;\nimport com.antony.muzei.pixiv.PixivArtProvider;\nimport com.antony.muzei.pixiv.PixivArtWorker;\nimport com.antony.muzei.pixiv.R;\nimport com.google.android.apps.muzei.api.provider.Artwork;\nimport com.google.android.apps.muzei.api.provider.ProviderContract;\n\nimport java.util.concurrent.TimeUnit;\n\npublic class SettingsActivity extends AppCompatActivity\n{\n private SharedPreferences.OnSharedPreferenceChangeListener prefChangeListener;\n private String newCreds, oldCreds;\n private String oldUpdateMode, newUpdateMode;\n private String oldFilter, newFilter;\n\n @Override\n protected void onCreate(Bundle savedInstanceState)\n {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.settings_activity);\n getSupportFragmentManager()\n .beginTransaction()\n .add(R.id.FeedPreferencesFragment, new SettingsFragment())\n .commit();\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n\n \/\/ Stores user toggleable variables into a temporary store for later comparison in onDestroy()\n oldCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n newCreds = oldCreds;\n\n oldUpdateMode = sharedPrefs.getString(\"pref_updateMode\", \"\");\n newUpdateMode = oldUpdateMode;\n\n oldFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n newFilter = oldFilter;\n\n prefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()\n {\n @Override\n public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)\n {\n if (key.equals(\"pref_loginPassword\"))\n {\n newCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n } else if (key.equals(\"pref_updateMode\"))\n {\n newUpdateMode = sharedPrefs.getString(\"oldUpdateMode\", \"\");\n } else if (key.equals(\"pref_nsfwFilterLevel\"))\n {\n newFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n }\n }\n };\n }\n\n @Override\n public void onResume()\n {\n super.onResume();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.registerOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onPause()\n {\n super.onPause();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onStop()\n {\n super.onStop();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n \/\/ Functions in here action only on app exit\n @Override\n public void onDestroy()\n {\n super.onDestroy();\n \/\/ If new user credentials were entered and saved, then clear and invalidate existing stored user credentials\n if (!oldCreds.equals(newCreds))\n {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n SharedPreferences.Editor editor = sharedPrefs.edit();\n editor.putString(\"accessToken\", \"\");\n editor.putString(\"refreshToken\", \"\");\n editor.putString(\"deviceToken\", \"\");\n editor.putLong(\"accessTokenIssueTime\", 0);\n editor.commit();\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newCredentials), Toast.LENGTH_SHORT).show();\n }\n\n \/\/ TODO\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n if (sharedPrefs.getBoolean(\"pref_autoClearMode\", false))\n {\n Constraints constraints = new Constraints.Builder()\n .setRequiredNetworkType(NetworkType.CONNECTED)\n .build();\n PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(ClearCacheWorker.class, 24, TimeUnit.HOURS)\n .setInitialDelay(1, TimeUnit.HOURS)\n .addTag(\"PIXIV_CACHE\")\n .setConstraints(constraints)\n .build();\n WorkManager.getInstance(getApplicationContext()).enqueueUniquePeriodicWork(\"PIXIV_CACHE\", ExistingPeriodicWorkPolicy.KEEP, request);\n } else\n {\n WorkManager.getInstance((getApplicationContext())).cancelAllWorkByTag(\"PIXIV_CACHE\");\n }\n\n if (!oldUpdateMode.equals(newUpdateMode))\n {\n WorkManager.getInstance().cancelAllWorkByTag(\"PIXIV\");\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newUpdateMode), Toast.LENGTH_SHORT).show();\n } else if (!oldFilter.equals(newFilter))\n {\n WorkManager.getInstance().cancelAllWorkByTag(\"PIXIV\");\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newFilterMode), Toast.LENGTH_SHORT).show();\n }\n\n\n }\n\n \/\/ Functions in here action immediately on user interaction\n public static class SettingsFragment extends PreferenceFragmentCompat\n {\n @Override\n public void onCreatePreferences(Bundle savedInstanceState, String rootKey)\n {\n setPreferencesFromResource(R.xml.feed_preferences_layout, rootKey);\n\n \/\/ Immediately clear cache\n Preference buttonClearCache = findPreference(getString(R.string.button_clearCache));\n buttonClearCache.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n ProviderContract.getProviderClient(getContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getContext(), getString(R.string.toast_clearingCache), Toast.LENGTH_SHORT).show();\n return true;\n }\n });\n\n \/\/ Manually force pull a new unage\n Preference buttonForcePull = findPreference(getString(R.string.button_forcePull));\n buttonForcePull.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n PixivArtWorker.enqueueLoad();\n return true;\n }\n });\n\n Preference loginId = findPreference(\"pref_loginId\");\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());\n if (sharedPrefs.getString(\"accessToken\", \"\").isEmpty())\n {\n loginId.setSummary(getString(R.string.prefSummary_authFail));\n } else\n {\n String summaryString = getString(R.string.prefSummary_authSuccess) + \" \" + sharedPrefs.getString(\"pref_loginId\", \"\");\n loginId.setSummary(summaryString);\n\/\/ Uri profileImageUri = Uri.parse(sharedPrefs.getString(\"profileImageUri\", \"\"));\n\/\/ loginId.setIcon();\n }\n }\n }\n}\n\nCode-B:\npackage com.antony.muzei.pixiv;\n\nimport android.content.SharedPreferences;\nimport android.os.Bundle;\nimport android.widget.Toast;\n\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.preference.Preference;\nimport androidx.preference.PreferenceFragmentCompat;\nimport androidx.preference.PreferenceManager;\nimport androidx.work.Constraints;\nimport androidx.work.ExistingPeriodicWorkPolicy;\nimport androidx.work.NetworkType;\nimport androidx.work.PeriodicWorkRequest;\nimport androidx.work.WorkManager;\n\nimport com.antony.muzei.pixiv.ClearCacheWorker;\nimport com.antony.muzei.pixiv.PixivArtProvider;\nimport com.antony.muzei.pixiv.PixivArtWorker;\nimport com.antony.muzei.pixiv.R;\nimport com.google.android.apps.muzei.api.provider.Artwork;\nimport com.google.android.apps.muzei.api.provider.ProviderContract;\n\nimport java.util.concurrent.TimeUnit;\n\npublic class SettingsActivity extends AppCompatActivity\n{\n private SharedPreferences.OnSharedPreferenceChangeListener prefChangeListener;\n private String newCreds, oldCreds;\n private String oldUpdateMode, newUpdateMode;\n private String oldFilter, newFilter;\n\n @Override\n protected void onCreate(Bundle savedInstanceState)\n {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.settings_activity);\n getSupportFragmentManager()\n .beginTransaction()\n .add(R.id.FeedPreferencesFragment, new SettingsFragment())\n .commit();\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n\n \/\/ Stores user toggleable variables into a temporary store for later comparison in onDestroy()\n oldCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n newCreds = oldCreds;\n\n oldUpdateMode = sharedPrefs.getString(\"pref_updateMode\", \"\");\n newUpdateMode = oldUpdateMode;\n\n oldFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n newFilter = oldFilter;\n\n prefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()\n {\n @Override\n public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)\n {\n if (key.equals(\"pref_loginPassword\"))\n {\n newCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n } else if (key.equals(\"pref_updateMode\"))\n {\n newUpdateMode = sharedPrefs.getString(\"oldUpdateMode\", \"\");\n } else if (key.equals(\"pref_nsfwFilterLevel\"))\n {\n newFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n }\n }\n };\n }\n\n @Override\n public void onResume()\n {\n super.onResume();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.registerOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onPause()\n {\n super.onPause();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onStop()\n {\n super.onStop();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n \/\/ Functions in here action only on app exit\n @Override\n public void onDestroy()\n {\n super.onDestroy();\n \/\/ If new user credentials were entered and saved, then clear and invalidate existing stored user credentials\n if (!oldCreds.equals(newCreds))\n {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n SharedPreferences.Editor editor = sharedPrefs.edit();\n editor.putString(\"accessToken\", \"\");\n editor.putString(\"refreshToken\", \"\");\n editor.putString(\"deviceToken\", \"\");\n editor.putLong(\"accessTokenIssueTime\", 0);\n editor.commit();\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newCredentials), Toast.LENGTH_SHORT).show();\n }\n\n \/\/ TODO\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n if (sharedPrefs.getBoolean(\"pref_autoClearMode\", false))\n {\n Constraints constraints = new Constraints.Builder()\n .setRequiredNetworkType(NetworkType.CONNECTED)\n .build();\n PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(ClearCacheWorker.class, 24, TimeUnit.HOURS)\n .setInitialDelay(1, TimeUnit.HOURS)\n .addTag(\"PIXIV_CACHE\")\n .setConstraints(constraints)\n .build();\n WorkManager.getInstance(getApplicationContext()).enqueueUniquePeriodicWork(\"PIXIV_CACHE\", ExistingPeriodicWorkPolicy.KEEP, request);\n } else\n {\n WorkManager.getInstance((getApplicationContext())).cancelAllWorkByTag(\"PIXIV_CACHE\");\n }\n\n if (!oldUpdateMode.equals(newUpdateMode))\n {\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newUpdateMode), Toast.LENGTH_SHORT).show();\n } else if (!oldFilter.equals(newFilter))\n {\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newFilterMode), Toast.LENGTH_SHORT).show();\n }\n\n\n }\n\n \/\/ Functions in here action immediately on user interaction\n public static class SettingsFragment extends PreferenceFragmentCompat\n {\n @Override\n public void onCreatePreferences(Bundle savedInstanceState, String rootKey)\n {\n setPreferencesFromResource(R.xml.feed_preferences_layout, rootKey);\n\n \/\/ Immediately clear cache\n Preference buttonClearCache = findPreference(getString(R.string.button_clearCache));\n buttonClearCache.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n ProviderContract.getProviderClient(getContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getContext(), getString(R.string.toast_clearingCache), Toast.LENGTH_SHORT).show();\n return true;\n }\n });\n\n \/\/ Manually force pull a new unage\n Preference buttonForcePull = findPreference(getString(R.string.button_forcePull));\n buttonForcePull.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n PixivArtWorker.enqueueLoad();\n return true;\n }\n });\n\n Preference loginId = findPreference(\"pref_loginId\");\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());\n if (sharedPrefs.getString(\"accessToken\", \"\").isEmpty())\n {\n loginId.setSummary(getString(R.string.prefSummary_authFail));\n } else\n {\n String summaryString = getString(R.string.prefSummary_authSuccess) + \" \" + sharedPrefs.getString(\"pref_loginId\", \"\");\n loginId.setSummary(summaryString);\n\/\/ Uri profileImageUri = Uri.parse(sharedPrefs.getString(\"profileImageUri\", \"\"));\n\/\/ loginId.setIcon();\n }\n }\n }\n}\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.antony.muzei.pixiv;\n\nimport android.content.SharedPreferences;\nimport android.os.Bundle;\nimport android.widget.Toast;\n\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.preference.Preference;\nimport androidx.preference.PreferenceFragmentCompat;\nimport androidx.preference.PreferenceManager;\nimport androidx.work.Constraints;\nimport androidx.work.ExistingPeriodicWorkPolicy;\nimport androidx.work.NetworkType;\nimport androidx.work.PeriodicWorkRequest;\nimport androidx.work.WorkManager;\n\nimport com.antony.muzei.pixiv.ClearCacheWorker;\nimport com.antony.muzei.pixiv.PixivArtProvider;\nimport com.antony.muzei.pixiv.PixivArtWorker;\nimport com.antony.muzei.pixiv.R;\nimport com.google.android.apps.muzei.api.provider.Artwork;\nimport com.google.android.apps.muzei.api.provider.ProviderContract;\n\nimport java.util.concurrent.TimeUnit;\n\npublic class SettingsActivity extends AppCompatActivity\n{\n private SharedPreferences.OnSharedPreferenceChangeListener prefChangeListener;\n private String newCreds, oldCreds;\n private String oldUpdateMode, newUpdateMode;\n private String oldFilter, newFilter;\n\n @Override\n protected void onCreate(Bundle savedInstanceState)\n {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.settings_activity);\n getSupportFragmentManager()\n .beginTransaction()\n .add(R.id.FeedPreferencesFragment, new SettingsFragment())\n .commit();\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n\n \/\/ Stores user toggleable variables into a temporary store for later comparison in onDestroy()\n oldCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n newCreds = oldCreds;\n\n oldUpdateMode = sharedPrefs.getString(\"pref_updateMode\", \"\");\n newUpdateMode = oldUpdateMode;\n\n oldFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n newFilter = oldFilter;\n\n prefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()\n {\n @Override\n public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)\n {\n if (key.equals(\"pref_loginPassword\"))\n {\n newCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n } else if (key.equals(\"pref_updateMode\"))\n {\n newUpdateMode = sharedPrefs.getString(\"oldUpdateMode\", \"\");\n } else if (key.equals(\"pref_nsfwFilterLevel\"))\n {\n newFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n }\n }\n };\n }\n\n @Override\n public void onResume()\n {\n super.onResume();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.registerOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onPause()\n {\n super.onPause();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onStop()\n {\n super.onStop();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n \/\/ Functions in here action only on app exit\n @Override\n public void onDestroy()\n {\n super.onDestroy();\n \/\/ If new user credentials were entered and saved, then clear and invalidate existing stored user credentials\n if (!oldCreds.equals(newCreds))\n {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n SharedPreferences.Editor editor = sharedPrefs.edit();\n editor.putString(\"accessToken\", \"\");\n editor.putString(\"refreshToken\", \"\");\n editor.putString(\"deviceToken\", \"\");\n editor.putLong(\"accessTokenIssueTime\", 0);\n editor.commit();\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newCredentials), Toast.LENGTH_SHORT).show();\n }\n\n \/\/ TODO\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n if (sharedPrefs.getBoolean(\"pref_autoClearMode\", false))\n {\n Constraints constraints = new Constraints.Builder()\n .setRequiredNetworkType(NetworkType.CONNECTED)\n .build();\n PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(ClearCacheWorker.class, 24, TimeUnit.HOURS)\n .setInitialDelay(1, TimeUnit.HOURS)\n .addTag(\"PIXIV_CACHE\")\n .setConstraints(constraints)\n .build();\n WorkManager.getInstance(getApplicationContext()).enqueueUniquePeriodicWork(\"PIXIV_CACHE\", ExistingPeriodicWorkPolicy.KEEP, request);\n } else\n {\n WorkManager.getInstance((getApplicationContext())).cancelAllWorkByTag(\"PIXIV_CACHE\");\n }\n\n if (!oldUpdateMode.equals(newUpdateMode))\n {\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newUpdateMode), Toast.LENGTH_SHORT).show();\n } else if (!oldFilter.equals(newFilter))\n {\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newFilterMode), Toast.LENGTH_SHORT).show();\n }\n\n\n }\n\n \/\/ Functions in here action immediately on user interaction\n public static class SettingsFragment extends PreferenceFragmentCompat\n {\n @Override\n public void onCreatePreferences(Bundle savedInstanceState, String rootKey)\n {\n setPreferencesFromResource(R.xml.feed_preferences_layout, rootKey);\n\n \/\/ Immediately clear cache\n Preference buttonClearCache = findPreference(getString(R.string.button_clearCache));\n buttonClearCache.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n ProviderContract.getProviderClient(getContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getContext(), getString(R.string.toast_clearingCache), Toast.LENGTH_SHORT).show();\n return true;\n }\n });\n\n \/\/ Manually force pull a new unage\n Preference buttonForcePull = findPreference(getString(R.string.button_forcePull));\n buttonForcePull.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n PixivArtWorker.enqueueLoad();\n return true;\n }\n });\n\n Preference loginId = findPreference(\"pref_loginId\");\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());\n if (sharedPrefs.getString(\"accessToken\", \"\").isEmpty())\n {\n loginId.setSummary(getString(R.string.prefSummary_authFail));\n } else\n {\n String summaryString = getString(R.string.prefSummary_authSuccess) + \" \" + sharedPrefs.getString(\"pref_loginId\", \"\");\n loginId.setSummary(summaryString);\n\/\/ Uri profileImageUri = Uri.parse(sharedPrefs.getString(\"profileImageUri\", \"\"));\n\/\/ loginId.setIcon();\n }\n }\n }\n}\n\nCode-B:\npackage com.antony.muzei.pixiv;\n\nimport android.content.SharedPreferences;\nimport android.os.Bundle;\nimport android.widget.Toast;\n\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.preference.Preference;\nimport androidx.preference.PreferenceFragmentCompat;\nimport androidx.preference.PreferenceManager;\nimport androidx.work.Constraints;\nimport androidx.work.ExistingPeriodicWorkPolicy;\nimport androidx.work.NetworkType;\nimport androidx.work.PeriodicWorkRequest;\nimport androidx.work.WorkManager;\n\nimport com.antony.muzei.pixiv.ClearCacheWorker;\nimport com.antony.muzei.pixiv.PixivArtProvider;\nimport com.antony.muzei.pixiv.PixivArtWorker;\nimport com.antony.muzei.pixiv.R;\nimport com.google.android.apps.muzei.api.provider.Artwork;\nimport com.google.android.apps.muzei.api.provider.ProviderContract;\n\nimport java.util.concurrent.TimeUnit;\n\npublic class SettingsActivity extends AppCompatActivity\n{\n private SharedPreferences.OnSharedPreferenceChangeListener prefChangeListener;\n private String newCreds, oldCreds;\n private String oldUpdateMode, newUpdateMode;\n private String oldFilter, newFilter;\n\n @Override\n protected void onCreate(Bundle savedInstanceState)\n {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.settings_activity);\n getSupportFragmentManager()\n .beginTransaction()\n .add(R.id.FeedPreferencesFragment, new SettingsFragment())\n .commit();\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n\n \/\/ Stores user toggleable variables into a temporary store for later comparison in onDestroy()\n oldCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n newCreds = oldCreds;\n\n oldUpdateMode = sharedPrefs.getString(\"pref_updateMode\", \"\");\n newUpdateMode = oldUpdateMode;\n\n oldFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n newFilter = oldFilter;\n\n prefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()\n {\n @Override\n public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)\n {\n if (key.equals(\"pref_loginPassword\"))\n {\n newCreds = sharedPrefs.getString(\"pref_loginPassword\", \"\");\n } else if (key.equals(\"pref_updateMode\"))\n {\n newUpdateMode = sharedPrefs.getString(\"oldUpdateMode\", \"\");\n } else if (key.equals(\"pref_nsfwFilterLevel\"))\n {\n newFilter = sharedPrefs.getString(\"pref_nsfwFilterLevel\", \"\");\n }\n }\n };\n }\n\n @Override\n public void onResume()\n {\n super.onResume();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.registerOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onPause()\n {\n super.onPause();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n @Override\n public void onStop()\n {\n super.onStop();\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n sharedPrefs.unregisterOnSharedPreferenceChangeListener(prefChangeListener);\n }\n\n \/\/ Functions in here action only on app exit\n @Override\n public void onDestroy()\n {\n super.onDestroy();\n \/\/ If new user credentials were entered and saved, then clear and invalidate existing stored user credentials\n if (!oldCreds.equals(newCreds))\n {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n SharedPreferences.Editor editor = sharedPrefs.edit();\n editor.putString(\"accessToken\", \"\");\n editor.putString(\"refreshToken\", \"\");\n editor.putString(\"deviceToken\", \"\");\n editor.putLong(\"accessTokenIssueTime\", 0);\n editor.commit();\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newCredentials), Toast.LENGTH_SHORT).show();\n }\n\n \/\/ TODO\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());\n if (sharedPrefs.getBoolean(\"pref_autoClearMode\", false))\n {\n Constraints constraints = new Constraints.Builder()\n .setRequiredNetworkType(NetworkType.CONNECTED)\n .build();\n PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(ClearCacheWorker.class, 24, TimeUnit.HOURS)\n .setInitialDelay(1, TimeUnit.HOURS)\n .addTag(\"PIXIV_CACHE\")\n .setConstraints(constraints)\n .build();\n WorkManager.getInstance(getApplicationContext()).enqueueUniquePeriodicWork(\"PIXIV_CACHE\", ExistingPeriodicWorkPolicy.KEEP, request);\n } else\n {\n WorkManager.getInstance((getApplicationContext())).cancelAllWorkByTag(\"PIXIV_CACHE\");\n }\n\n if (!oldUpdateMode.equals(newUpdateMode))\n {\n WorkManager.getInstance().cancelAllWorkByTag(\"PIXIV\");\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newUpdateMode), Toast.LENGTH_SHORT).show();\n } else if (!oldFilter.equals(newFilter))\n {\n WorkManager.getInstance().cancelAllWorkByTag(\"PIXIV\");\n ProviderContract.getProviderClient(getApplicationContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getApplicationContext(), getString(R.string.toast_newFilterMode), Toast.LENGTH_SHORT).show();\n }\n\n\n }\n\n \/\/ Functions in here action immediately on user interaction\n public static class SettingsFragment extends PreferenceFragmentCompat\n {\n @Override\n public void onCreatePreferences(Bundle savedInstanceState, String rootKey)\n {\n setPreferencesFromResource(R.xml.feed_preferences_layout, rootKey);\n\n \/\/ Immediately clear cache\n Preference buttonClearCache = findPreference(getString(R.string.button_clearCache));\n buttonClearCache.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n ProviderContract.getProviderClient(getContext(), PixivArtProvider.class).setArtwork(new Artwork());\n Toast.makeText(getContext(), getString(R.string.toast_clearingCache), Toast.LENGTH_SHORT).show();\n return true;\n }\n });\n\n \/\/ Manually force pull a new unage\n Preference buttonForcePull = findPreference(getString(R.string.button_forcePull));\n buttonForcePull.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener()\n {\n @Override\n public boolean onPreferenceClick(Preference preference)\n {\n PixivArtWorker.enqueueLoad();\n return true;\n }\n });\n\n Preference loginId = findPreference(\"pref_loginId\");\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());\n if (sharedPrefs.getString(\"accessToken\", \"\").isEmpty())\n {\n loginId.setSummary(getString(R.string.prefSummary_authFail));\n } else\n {\n String summaryString = getString(R.string.prefSummary_authSuccess) + \" \" + sharedPrefs.getString(\"pref_loginId\", \"\");\n loginId.setSummary(summaryString);\n\/\/ Uri profileImageUri = Uri.parse(sharedPrefs.getString(\"profileImageUri\", \"\"));\n\/\/ loginId.setIcon();\n }\n }\n }\n}\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/erikusaj\/fdroidTvClient\/commit\/f7531fcdb5e826a01b364eaf2f3efb26df0301e4","commit_message":"'\\\\\"Place an empty drawable before icons are loaded; faster animations\\\\n\\\\\"'","source_code":"\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport java.io.File;\nimport java.lang.Runtime;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.Semaphore;\n\nimport android.os.Build;\nimport android.app.Application;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Bitmap;\n\nimport com.nostra13.universalimageloader.utils.StorageUtils;\nimport com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;\nimport com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;\nimport com.nostra13.universalimageloader.core.assist.ImageScaleType;\nimport com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;\nimport com.nostra13.universalimageloader.core.DisplayImageOptions;\nimport com.nostra13.universalimageloader.core.ImageLoader;\nimport com.nostra13.universalimageloader.core.ImageLoaderConfiguration;\n\npublic class FDroidApp extends Application {\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n \/\/ Needs to be setup before anything else tries to access it.\n \/\/ Perhaps the constructor is a better place, but then again,\n \/\/ it is more deterministic as to when this gets called...\n Preferences.setup(this);\n\n \/\/ Clear cached apk files. We used to just remove them after they'd\n \/\/ been installed, but this causes problems for proprietary gapps\n \/\/ users since the introduction of verification (on pre-4.2 Android),\n \/\/ because the install intent says it's finished when it hasn't.\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(getBaseContext());\n showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n if (!prefs.getBoolean(\"cacheDownloaded\", false)) {\n\n File local_path = DB.getDataPath(this);\n \/\/ Things can be null if the SD card is not ready - we'll just\n \/\/ ignore that and do it next time.\n if(local_path != null) {\n File[] files = local_path.listFiles();\n if(files != null) {\n for(File f : files) {\n if(f.getName().endsWith(\".apk\")) {\n f.delete();\n }\n }\n }\n }\n }\n\n apps = null;\n invalidApps = new ArrayList();\n ctx = getApplicationContext();\n DB.initDB(ctx);\n UpdateService.schedule(ctx);\n\n DisplayImageOptions defaultOptions;\n int threads;\n\n \/\/ Parameters for 2.2 and below\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.drawable.sym_def_app_icon)\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = 1;\n }\n \/\/ Parameters for 2.3 and above\n else {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.drawable.sym_def_app_icon)\n .displayer(new FadeInBitmapDisplayer(250, true, true, false))\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = Runtime.getRuntime().availableProcessors() * 2;\n }\n\n ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx)\n .discCache(new UnlimitedDiscCache(\n new File(StorageUtils.getCacheDirectory(ctx), \"icons\"),\n new FileNameGenerator() {\n public String generate(String imageUri) {\n return imageUri.substring(\n imageUri.lastIndexOf('\/') + 1);\n } } ))\n .defaultDisplayImageOptions(defaultOptions)\n .threadPoolSize(threads)\n .build();\n ImageLoader.getInstance().init(config);\n Log.d(\"FDroid\", \"Universal Image Loader started with \"\n + threads + \" threads\");\n }\n\n Context ctx;\n\n \/\/ Global list of all known applications.\n private List apps;\n\n private boolean showIncompatible;\n\n \/\/ Set when something has changed (database or installed apps) so we know\n \/\/ we should invalidate the apps.\n private volatile boolean appsAllInvalid = false;\n private Semaphore appsInvalidLock = new Semaphore(1, false);\n private List invalidApps;\n\n \/\/ Set apps invalid. Call this when the database has been updated with\n \/\/ new app information, or when the installed packages have changed.\n public void invalidateAllApps() {\n try {\n appsInvalidLock.acquire();\n appsAllInvalid = true;\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n }\n\n \/\/ Invalidate a single app\n public void invalidateApp(String id) {\n Log.d(\"FDroid\", \"Invalidating \"+id);\n invalidApps.add(id);\n }\n\n \/\/ Get a list of all known applications. Should not be called when the\n \/\/ database is locked (i.e. between DB.getDB() and db.releaseDB(). The\n \/\/ contents should never be modified, it's for reading only.\n public List getApps() {\n\n boolean invalid = false;\n try {\n appsInvalidLock.acquire();\n invalid = appsAllInvalid;\n if (invalid) {\n appsAllInvalid = false;\n Log.d(\"FDroid\", \"Dropping cached app data\");\n }\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n\n if (apps == null || invalid) {\n try {\n DB db = DB.getDB();\n apps = db.getApps(true);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n } finally {\n DB.releaseDB();\n }\n } else if (!invalidApps.isEmpty()) {\n try {\n DB db = DB.getDB();\n apps = db.refreshApps(apps, invalidApps);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n if (!invalidApps.contains(app.id)) continue;\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n invalidApps.clear();\n } finally {\n DB.releaseDB();\n }\n }\n if (apps == null)\n return new ArrayList();\n filterApps();\n return apps;\n }\n\n public void filterApps() {\n AppFilter appFilter = new AppFilter(ctx);\n for (DB.App app : apps) {\n app.filtered = appFilter.filter(app);\n\n app.toUpdate = (app.hasUpdates\n && !app.ignoreAllUpdates\n && app.curApk.vercode > app.ignoreThisUpdate\n && !app.filtered\n && (showIncompatible || app.compatible));\n }\n }\n\n}\n","target_code":"\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport java.io.File;\nimport java.lang.Runtime;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.Semaphore;\n\nimport android.os.Build;\nimport android.app.Application;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Bitmap;\n\nimport com.nostra13.universalimageloader.utils.StorageUtils;\nimport com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;\nimport com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;\nimport com.nostra13.universalimageloader.core.assist.ImageScaleType;\nimport com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;\nimport com.nostra13.universalimageloader.core.DisplayImageOptions;\nimport com.nostra13.universalimageloader.core.ImageLoader;\nimport com.nostra13.universalimageloader.core.ImageLoaderConfiguration;\n\npublic class FDroidApp extends Application {\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n \/\/ Needs to be setup before anything else tries to access it.\n \/\/ Perhaps the constructor is a better place, but then again,\n \/\/ it is more deterministic as to when this gets called...\n Preferences.setup(this);\n\n \/\/ Clear cached apk files. We used to just remove them after they'd\n \/\/ been installed, but this causes problems for proprietary gapps\n \/\/ users since the introduction of verification (on pre-4.2 Android),\n \/\/ because the install intent says it's finished when it hasn't.\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(getBaseContext());\n showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n if (!prefs.getBoolean(\"cacheDownloaded\", false)) {\n\n File local_path = DB.getDataPath(this);\n \/\/ Things can be null if the SD card is not ready - we'll just\n \/\/ ignore that and do it next time.\n if(local_path != null) {\n File[] files = local_path.listFiles();\n if(files != null) {\n for(File f : files) {\n if(f.getName().endsWith(\".apk\")) {\n f.delete();\n }\n }\n }\n }\n }\n\n apps = null;\n invalidApps = new ArrayList();\n ctx = getApplicationContext();\n DB.initDB(ctx);\n UpdateService.schedule(ctx);\n\n DisplayImageOptions defaultOptions;\n int threads;\n\n \/\/ Parameters for 2.2 and below\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.color.transparent)\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = 1;\n }\n \/\/ Parameters for 2.3 and above\n else {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.color.transparent)\n .displayer(new FadeInBitmapDisplayer(200, true, true, false))\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = Runtime.getRuntime().availableProcessors() * 2;\n }\n\n ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx)\n .discCache(new UnlimitedDiscCache(\n new File(StorageUtils.getCacheDirectory(ctx), \"icons\"),\n new FileNameGenerator() {\n public String generate(String imageUri) {\n return imageUri.substring(\n imageUri.lastIndexOf('\/') + 1);\n } } ))\n .defaultDisplayImageOptions(defaultOptions)\n .threadPoolSize(threads)\n .build();\n ImageLoader.getInstance().init(config);\n Log.d(\"FDroid\", \"Universal Image Loader started with \"\n + threads + \" threads\");\n }\n\n Context ctx;\n\n \/\/ Global list of all known applications.\n private List apps;\n\n private boolean showIncompatible;\n\n \/\/ Set when something has changed (database or installed apps) so we know\n \/\/ we should invalidate the apps.\n private volatile boolean appsAllInvalid = false;\n private Semaphore appsInvalidLock = new Semaphore(1, false);\n private List invalidApps;\n\n \/\/ Set apps invalid. Call this when the database has been updated with\n \/\/ new app information, or when the installed packages have changed.\n public void invalidateAllApps() {\n try {\n appsInvalidLock.acquire();\n appsAllInvalid = true;\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n }\n\n \/\/ Invalidate a single app\n public void invalidateApp(String id) {\n Log.d(\"FDroid\", \"Invalidating \"+id);\n invalidApps.add(id);\n }\n\n \/\/ Get a list of all known applications. Should not be called when the\n \/\/ database is locked (i.e. between DB.getDB() and db.releaseDB(). The\n \/\/ contents should never be modified, it's for reading only.\n public List getApps() {\n\n boolean invalid = false;\n try {\n appsInvalidLock.acquire();\n invalid = appsAllInvalid;\n if (invalid) {\n appsAllInvalid = false;\n Log.d(\"FDroid\", \"Dropping cached app data\");\n }\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n\n if (apps == null || invalid) {\n try {\n DB db = DB.getDB();\n apps = db.getApps(true);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n } finally {\n DB.releaseDB();\n }\n } else if (!invalidApps.isEmpty()) {\n try {\n DB db = DB.getDB();\n apps = db.refreshApps(apps, invalidApps);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n if (!invalidApps.contains(app.id)) continue;\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n invalidApps.clear();\n } finally {\n DB.releaseDB();\n }\n }\n if (apps == null)\n return new ArrayList();\n filterApps();\n return apps;\n }\n\n public void filterApps() {\n AppFilter appFilter = new AppFilter(ctx);\n for (DB.App app : apps) {\n app.filtered = appFilter.filter(app);\n\n app.toUpdate = (app.hasUpdates\n && !app.ignoreAllUpdates\n && app.curApk.vercode > app.ignoreThisUpdate\n && !app.filtered\n && (showIncompatible || app.compatible));\n }\n }\n\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport java.io.File;\nimport java.lang.Runtime;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.Semaphore;\n\nimport android.os.Build;\nimport android.app.Application;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Bitmap;\n\nimport com.nostra13.universalimageloader.utils.StorageUtils;\nimport com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;\nimport com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;\nimport com.nostra13.universalimageloader.core.assist.ImageScaleType;\nimport com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;\nimport com.nostra13.universalimageloader.core.DisplayImageOptions;\nimport com.nostra13.universalimageloader.core.ImageLoader;\nimport com.nostra13.universalimageloader.core.ImageLoaderConfiguration;\n\npublic class FDroidApp extends Application {\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n \/\/ Needs to be setup before anything else tries to access it.\n \/\/ Perhaps the constructor is a better place, but then again,\n \/\/ it is more deterministic as to when this gets called...\n Preferences.setup(this);\n\n \/\/ Clear cached apk files. We used to just remove them after they'd\n \/\/ been installed, but this causes problems for proprietary gapps\n \/\/ users since the introduction of verification (on pre-4.2 Android),\n \/\/ because the install intent says it's finished when it hasn't.\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(getBaseContext());\n showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n if (!prefs.getBoolean(\"cacheDownloaded\", false)) {\n\n File local_path = DB.getDataPath(this);\n \/\/ Things can be null if the SD card is not ready - we'll just\n \/\/ ignore that and do it next time.\n if(local_path != null) {\n File[] files = local_path.listFiles();\n if(files != null) {\n for(File f : files) {\n if(f.getName().endsWith(\".apk\")) {\n f.delete();\n }\n }\n }\n }\n }\n\n apps = null;\n invalidApps = new ArrayList();\n ctx = getApplicationContext();\n DB.initDB(ctx);\n UpdateService.schedule(ctx);\n\n DisplayImageOptions defaultOptions;\n int threads;\n\n \/\/ Parameters for 2.2 and below\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.drawable.sym_def_app_icon)\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = 1;\n }\n \/\/ Parameters for 2.3 and above\n else {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.drawable.sym_def_app_icon)\n .displayer(new FadeInBitmapDisplayer(250, true, true, false))\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = Runtime.getRuntime().availableProcessors() * 2;\n }\n\n ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx)\n .discCache(new UnlimitedDiscCache(\n new File(StorageUtils.getCacheDirectory(ctx), \"icons\"),\n new FileNameGenerator() {\n public String generate(String imageUri) {\n return imageUri.substring(\n imageUri.lastIndexOf('\/') + 1);\n } } ))\n .defaultDisplayImageOptions(defaultOptions)\n .threadPoolSize(threads)\n .build();\n ImageLoader.getInstance().init(config);\n Log.d(\"FDroid\", \"Universal Image Loader started with \"\n + threads + \" threads\");\n }\n\n Context ctx;\n\n \/\/ Global list of all known applications.\n private List apps;\n\n private boolean showIncompatible;\n\n \/\/ Set when something has changed (database or installed apps) so we know\n \/\/ we should invalidate the apps.\n private volatile boolean appsAllInvalid = false;\n private Semaphore appsInvalidLock = new Semaphore(1, false);\n private List invalidApps;\n\n \/\/ Set apps invalid. Call this when the database has been updated with\n \/\/ new app information, or when the installed packages have changed.\n public void invalidateAllApps() {\n try {\n appsInvalidLock.acquire();\n appsAllInvalid = true;\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n }\n\n \/\/ Invalidate a single app\n public void invalidateApp(String id) {\n Log.d(\"FDroid\", \"Invalidating \"+id);\n invalidApps.add(id);\n }\n\n \/\/ Get a list of all known applications. Should not be called when the\n \/\/ database is locked (i.e. between DB.getDB() and db.releaseDB(). The\n \/\/ contents should never be modified, it's for reading only.\n public List getApps() {\n\n boolean invalid = false;\n try {\n appsInvalidLock.acquire();\n invalid = appsAllInvalid;\n if (invalid) {\n appsAllInvalid = false;\n Log.d(\"FDroid\", \"Dropping cached app data\");\n }\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n\n if (apps == null || invalid) {\n try {\n DB db = DB.getDB();\n apps = db.getApps(true);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n } finally {\n DB.releaseDB();\n }\n } else if (!invalidApps.isEmpty()) {\n try {\n DB db = DB.getDB();\n apps = db.refreshApps(apps, invalidApps);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n if (!invalidApps.contains(app.id)) continue;\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n invalidApps.clear();\n } finally {\n DB.releaseDB();\n }\n }\n if (apps == null)\n return new ArrayList();\n filterApps();\n return apps;\n }\n\n public void filterApps() {\n AppFilter appFilter = new AppFilter(ctx);\n for (DB.App app : apps) {\n app.filtered = appFilter.filter(app);\n\n app.toUpdate = (app.hasUpdates\n && !app.ignoreAllUpdates\n && app.curApk.vercode > app.ignoreThisUpdate\n && !app.filtered\n && (showIncompatible || app.compatible));\n }\n }\n\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport java.io.File;\nimport java.lang.Runtime;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.Semaphore;\n\nimport android.os.Build;\nimport android.app.Application;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Bitmap;\n\nimport com.nostra13.universalimageloader.utils.StorageUtils;\nimport com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;\nimport com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;\nimport com.nostra13.universalimageloader.core.assist.ImageScaleType;\nimport com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;\nimport com.nostra13.universalimageloader.core.DisplayImageOptions;\nimport com.nostra13.universalimageloader.core.ImageLoader;\nimport com.nostra13.universalimageloader.core.ImageLoaderConfiguration;\n\npublic class FDroidApp extends Application {\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n \/\/ Needs to be setup before anything else tries to access it.\n \/\/ Perhaps the constructor is a better place, but then again,\n \/\/ it is more deterministic as to when this gets called...\n Preferences.setup(this);\n\n \/\/ Clear cached apk files. We used to just remove them after they'd\n \/\/ been installed, but this causes problems for proprietary gapps\n \/\/ users since the introduction of verification (on pre-4.2 Android),\n \/\/ because the install intent says it's finished when it hasn't.\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(getBaseContext());\n showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n if (!prefs.getBoolean(\"cacheDownloaded\", false)) {\n\n File local_path = DB.getDataPath(this);\n \/\/ Things can be null if the SD card is not ready - we'll just\n \/\/ ignore that and do it next time.\n if(local_path != null) {\n File[] files = local_path.listFiles();\n if(files != null) {\n for(File f : files) {\n if(f.getName().endsWith(\".apk\")) {\n f.delete();\n }\n }\n }\n }\n }\n\n apps = null;\n invalidApps = new ArrayList();\n ctx = getApplicationContext();\n DB.initDB(ctx);\n UpdateService.schedule(ctx);\n\n DisplayImageOptions defaultOptions;\n int threads;\n\n \/\/ Parameters for 2.2 and below\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.drawable.sym_def_app_icon)\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = 1;\n }\n \/\/ Parameters for 2.3 and above\n else {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.drawable.sym_def_app_icon)\n .displayer(new FadeInBitmapDisplayer(250, true, true, false))\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = Runtime.getRuntime().availableProcessors() * 2;\n }\n\n ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx)\n .discCache(new UnlimitedDiscCache(\n new File(StorageUtils.getCacheDirectory(ctx), \"icons\"),\n new FileNameGenerator() {\n public String generate(String imageUri) {\n return imageUri.substring(\n imageUri.lastIndexOf('\/') + 1);\n } } ))\n .defaultDisplayImageOptions(defaultOptions)\n .threadPoolSize(threads)\n .build();\n ImageLoader.getInstance().init(config);\n Log.d(\"FDroid\", \"Universal Image Loader started with \"\n + threads + \" threads\");\n }\n\n Context ctx;\n\n \/\/ Global list of all known applications.\n private List apps;\n\n private boolean showIncompatible;\n\n \/\/ Set when something has changed (database or installed apps) so we know\n \/\/ we should invalidate the apps.\n private volatile boolean appsAllInvalid = false;\n private Semaphore appsInvalidLock = new Semaphore(1, false);\n private List invalidApps;\n\n \/\/ Set apps invalid. Call this when the database has been updated with\n \/\/ new app information, or when the installed packages have changed.\n public void invalidateAllApps() {\n try {\n appsInvalidLock.acquire();\n appsAllInvalid = true;\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n }\n\n \/\/ Invalidate a single app\n public void invalidateApp(String id) {\n Log.d(\"FDroid\", \"Invalidating \"+id);\n invalidApps.add(id);\n }\n\n \/\/ Get a list of all known applications. Should not be called when the\n \/\/ database is locked (i.e. between DB.getDB() and db.releaseDB(). The\n \/\/ contents should never be modified, it's for reading only.\n public List getApps() {\n\n boolean invalid = false;\n try {\n appsInvalidLock.acquire();\n invalid = appsAllInvalid;\n if (invalid) {\n appsAllInvalid = false;\n Log.d(\"FDroid\", \"Dropping cached app data\");\n }\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n\n if (apps == null || invalid) {\n try {\n DB db = DB.getDB();\n apps = db.getApps(true);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n } finally {\n DB.releaseDB();\n }\n } else if (!invalidApps.isEmpty()) {\n try {\n DB db = DB.getDB();\n apps = db.refreshApps(apps, invalidApps);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n if (!invalidApps.contains(app.id)) continue;\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n invalidApps.clear();\n } finally {\n DB.releaseDB();\n }\n }\n if (apps == null)\n return new ArrayList();\n filterApps();\n return apps;\n }\n\n public void filterApps() {\n AppFilter appFilter = new AppFilter(ctx);\n for (DB.App app : apps) {\n app.filtered = appFilter.filter(app);\n\n app.toUpdate = (app.hasUpdates\n && !app.ignoreAllUpdates\n && app.curApk.vercode > app.ignoreThisUpdate\n && !app.filtered\n && (showIncompatible || app.compatible));\n }\n }\n\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport java.io.File;\nimport java.lang.Runtime;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.Semaphore;\n\nimport android.os.Build;\nimport android.app.Application;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Bitmap;\n\nimport com.nostra13.universalimageloader.utils.StorageUtils;\nimport com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;\nimport com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;\nimport com.nostra13.universalimageloader.core.assist.ImageScaleType;\nimport com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;\nimport com.nostra13.universalimageloader.core.DisplayImageOptions;\nimport com.nostra13.universalimageloader.core.ImageLoader;\nimport com.nostra13.universalimageloader.core.ImageLoaderConfiguration;\n\npublic class FDroidApp extends Application {\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n \/\/ Needs to be setup before anything else tries to access it.\n \/\/ Perhaps the constructor is a better place, but then again,\n \/\/ it is more deterministic as to when this gets called...\n Preferences.setup(this);\n\n \/\/ Clear cached apk files. We used to just remove them after they'd\n \/\/ been installed, but this causes problems for proprietary gapps\n \/\/ users since the introduction of verification (on pre-4.2 Android),\n \/\/ because the install intent says it's finished when it hasn't.\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(getBaseContext());\n showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n if (!prefs.getBoolean(\"cacheDownloaded\", false)) {\n\n File local_path = DB.getDataPath(this);\n \/\/ Things can be null if the SD card is not ready - we'll just\n \/\/ ignore that and do it next time.\n if(local_path != null) {\n File[] files = local_path.listFiles();\n if(files != null) {\n for(File f : files) {\n if(f.getName().endsWith(\".apk\")) {\n f.delete();\n }\n }\n }\n }\n }\n\n apps = null;\n invalidApps = new ArrayList();\n ctx = getApplicationContext();\n DB.initDB(ctx);\n UpdateService.schedule(ctx);\n\n DisplayImageOptions defaultOptions;\n int threads;\n\n \/\/ Parameters for 2.2 and below\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.drawable.sym_def_app_icon)\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = 1;\n }\n \/\/ Parameters for 2.3 and above\n else {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.drawable.sym_def_app_icon)\n .displayer(new FadeInBitmapDisplayer(250, true, true, false))\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = Runtime.getRuntime().availableProcessors() * 2;\n }\n\n ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx)\n .discCache(new UnlimitedDiscCache(\n new File(StorageUtils.getCacheDirectory(ctx), \"icons\"),\n new FileNameGenerator() {\n public String generate(String imageUri) {\n return imageUri.substring(\n imageUri.lastIndexOf('\/') + 1);\n } } ))\n .defaultDisplayImageOptions(defaultOptions)\n .threadPoolSize(threads)\n .build();\n ImageLoader.getInstance().init(config);\n Log.d(\"FDroid\", \"Universal Image Loader started with \"\n + threads + \" threads\");\n }\n\n Context ctx;\n\n \/\/ Global list of all known applications.\n private List apps;\n\n private boolean showIncompatible;\n\n \/\/ Set when something has changed (database or installed apps) so we know\n \/\/ we should invalidate the apps.\n private volatile boolean appsAllInvalid = false;\n private Semaphore appsInvalidLock = new Semaphore(1, false);\n private List invalidApps;\n\n \/\/ Set apps invalid. Call this when the database has been updated with\n \/\/ new app information, or when the installed packages have changed.\n public void invalidateAllApps() {\n try {\n appsInvalidLock.acquire();\n appsAllInvalid = true;\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n }\n\n \/\/ Invalidate a single app\n public void invalidateApp(String id) {\n Log.d(\"FDroid\", \"Invalidating \"+id);\n invalidApps.add(id);\n }\n\n \/\/ Get a list of all known applications. Should not be called when the\n \/\/ database is locked (i.e. between DB.getDB() and db.releaseDB(). The\n \/\/ contents should never be modified, it's for reading only.\n public List getApps() {\n\n boolean invalid = false;\n try {\n appsInvalidLock.acquire();\n invalid = appsAllInvalid;\n if (invalid) {\n appsAllInvalid = false;\n Log.d(\"FDroid\", \"Dropping cached app data\");\n }\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n\n if (apps == null || invalid) {\n try {\n DB db = DB.getDB();\n apps = db.getApps(true);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n } finally {\n DB.releaseDB();\n }\n } else if (!invalidApps.isEmpty()) {\n try {\n DB db = DB.getDB();\n apps = db.refreshApps(apps, invalidApps);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n if (!invalidApps.contains(app.id)) continue;\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n invalidApps.clear();\n } finally {\n DB.releaseDB();\n }\n }\n if (apps == null)\n return new ArrayList();\n filterApps();\n return apps;\n }\n\n public void filterApps() {\n AppFilter appFilter = new AppFilter(ctx);\n for (DB.App app : apps) {\n app.filtered = appFilter.filter(app);\n\n app.toUpdate = (app.hasUpdates\n && !app.ignoreAllUpdates\n && app.curApk.vercode > app.ignoreThisUpdate\n && !app.filtered\n && (showIncompatible || app.compatible));\n }\n }\n\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite the code to place an empty drawable before icons are loaded and make animations faster. Write the entire code and no other text in the response.\n\n### Concepts:\n[hint] reduce the fade-in time by 50ms\n[in] onCreate function \n\n### Given program:\n```java\n\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport java.io.File;\nimport java.lang.Runtime;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.Semaphore;\n\nimport android.os.Build;\nimport android.app.Application;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Bitmap;\n\nimport com.nostra13.universalimageloader.utils.StorageUtils;\nimport com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;\nimport com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;\nimport com.nostra13.universalimageloader.core.assist.ImageScaleType;\nimport com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;\nimport com.nostra13.universalimageloader.core.DisplayImageOptions;\nimport com.nostra13.universalimageloader.core.ImageLoader;\nimport com.nostra13.universalimageloader.core.ImageLoaderConfiguration;\n\npublic class FDroidApp extends Application {\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n \/\/ Needs to be setup before anything else tries to access it.\n \/\/ Perhaps the constructor is a better place, but then again,\n \/\/ it is more deterministic as to when this gets called...\n Preferences.setup(this);\n\n \/\/ Clear cached apk files. We used to just remove them after they'd\n \/\/ been installed, but this causes problems for proprietary gapps\n \/\/ users since the introduction of verification (on pre-4.2 Android),\n \/\/ because the install intent says it's finished when it hasn't.\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(getBaseContext());\n showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n if (!prefs.getBoolean(\"cacheDownloaded\", false)) {\n\n File local_path = DB.getDataPath(this);\n \/\/ Things can be null if the SD card is not ready - we'll just\n \/\/ ignore that and do it next time.\n if(local_path != null) {\n File[] files = local_path.listFiles();\n if(files != null) {\n for(File f : files) {\n if(f.getName().endsWith(\".apk\")) {\n f.delete();\n }\n }\n }\n }\n }\n\n apps = null;\n invalidApps = new ArrayList();\n ctx = getApplicationContext();\n DB.initDB(ctx);\n UpdateService.schedule(ctx);\n\n DisplayImageOptions defaultOptions;\n int threads;\n\n \/\/ Parameters for 2.2 and below\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.drawable.sym_def_app_icon)\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = 1;\n }\n \/\/ Parameters for 2.3 and above\n else {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.drawable.sym_def_app_icon)\n .displayer(new FadeInBitmapDisplayer(250, true, true, false))\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = Runtime.getRuntime().availableProcessors() * 2;\n }\n\n ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx)\n .discCache(new UnlimitedDiscCache(\n new File(StorageUtils.getCacheDirectory(ctx), \"icons\"),\n new FileNameGenerator() {\n public String generate(String imageUri) {\n return imageUri.substring(\n imageUri.lastIndexOf('\/') + 1);\n } } ))\n .defaultDisplayImageOptions(defaultOptions)\n .threadPoolSize(threads)\n .build();\n ImageLoader.getInstance().init(config);\n Log.d(\"FDroid\", \"Universal Image Loader started with \"\n + threads + \" threads\");\n }\n\n Context ctx;\n\n \/\/ Global list of all known applications.\n private List apps;\n\n private boolean showIncompatible;\n\n \/\/ Set when something has changed (database or installed apps) so we know\n \/\/ we should invalidate the apps.\n private volatile boolean appsAllInvalid = false;\n private Semaphore appsInvalidLock = new Semaphore(1, false);\n private List invalidApps;\n\n \/\/ Set apps invalid. Call this when the database has been updated with\n \/\/ new app information, or when the installed packages have changed.\n public void invalidateAllApps() {\n try {\n appsInvalidLock.acquire();\n appsAllInvalid = true;\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n }\n\n \/\/ Invalidate a single app\n public void invalidateApp(String id) {\n Log.d(\"FDroid\", \"Invalidating \"+id);\n invalidApps.add(id);\n }\n\n \/\/ Get a list of all known applications. Should not be called when the\n \/\/ database is locked (i.e. between DB.getDB() and db.releaseDB(). The\n \/\/ contents should never be modified, it's for reading only.\n public List getApps() {\n\n boolean invalid = false;\n try {\n appsInvalidLock.acquire();\n invalid = appsAllInvalid;\n if (invalid) {\n appsAllInvalid = false;\n Log.d(\"FDroid\", \"Dropping cached app data\");\n }\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n\n if (apps == null || invalid) {\n try {\n DB db = DB.getDB();\n apps = db.getApps(true);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n } finally {\n DB.releaseDB();\n }\n } else if (!invalidApps.isEmpty()) {\n try {\n DB db = DB.getDB();\n apps = db.refreshApps(apps, invalidApps);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n if (!invalidApps.contains(app.id)) continue;\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n invalidApps.clear();\n } finally {\n DB.releaseDB();\n }\n }\n if (apps == null)\n return new ArrayList();\n filterApps();\n return apps;\n }\n\n public void filterApps() {\n AppFilter appFilter = new AppFilter(ctx);\n for (DB.App app : apps) {\n app.filtered = appFilter.filter(app);\n\n app.toUpdate = (app.hasUpdates\n && !app.ignoreAllUpdates\n && app.curApk.vercode > app.ignoreThisUpdate\n && !app.filtered\n && (showIncompatible || app.compatible));\n }\n }\n\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage org.fdroid.fdroid;\n\nimport java.util.*;\n\nimport android.content.SharedPreferences;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.widget.ArrayAdapter;\n\nimport org.fdroid.fdroid.views.AppListAdapter;\nimport org.fdroid.fdroid.views.AvailableAppListAdapter;\nimport org.fdroid.fdroid.views.CanUpdateAppListAdapter;\nimport org.fdroid.fdroid.views.InstalledAppListAdapter;\n\n\/**\n * Should be owned by the FDroid Activity, but used by the AppListFragments.\n * The idea is that it takes a non-trivial amount of time to work this stuff\n * out, and it is quicker if we only do it once for each view, rather than\n * each fragment figuring out their own list independently.\n *\/\npublic class AppListManager {\n\n private List allApps = null;\n\n private FDroid fdroidActivity;\n\n private AppListAdapter availableApps;\n private AppListAdapter installedApps;\n private AppListAdapter canUpgradeApps;\n private ArrayAdapter categories;\n\n private String currentCategory = null;\n private String categoryAll = null;\n private String categoryWhatsNew = null;\n private String categoryRecentlyUpdated = null;\n\n public AppListAdapter getAvailableAdapter() {\n return availableApps;\n }\n\n public AppListAdapter getInstalledAdapter() {\n return installedApps;\n }\n\n public AppListAdapter getCanUpdateAdapter() {\n return canUpgradeApps;\n }\n\n public ArrayAdapter getCategoriesAdapter() {\n return categories;\n }\n\n public AppListManager(FDroid activity) {\n this.fdroidActivity = activity;\n\n availableApps = new AvailableAppListAdapter(fdroidActivity);\n installedApps = new InstalledAppListAdapter(fdroidActivity);\n canUpgradeApps = new CanUpdateAppListAdapter(fdroidActivity);\n\n \/\/ Needs to be created before createViews(), because that will use the\n \/\/ getCategoriesAdapter() accessor which expects this object...\n categories = new ArrayAdapter(activity,\n android.R.layout.simple_spinner_item, new ArrayList());\n categories\n .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n }\n\n private void clear() {\n installedApps.clear();\n availableApps.clear();\n canUpgradeApps.clear();\n categories.clear();\n }\n\n private void notifyLists() {\n \/\/ Tell the lists that the data behind the adapter has changed, so\n \/\/ they can refresh...\n availableApps.notifyDataSetChanged();\n installedApps.notifyDataSetChanged();\n canUpgradeApps.notifyDataSetChanged();\n categories.notifyDataSetChanged();\n }\n\n private void updateCategories() {\n try {\n DB db = DB.getDB();\n\n \/\/ Populate the category list with the real categories, and the\n \/\/ locally generated meta-categories for \"All\", \"What's New\" and\n \/\/ \"Recently Updated\"...\n categoryAll = fdroidActivity.getString(R.string.category_all);\n categoryWhatsNew = fdroidActivity.getString(R.string.category_whatsnew);\n categoryRecentlyUpdated = fdroidActivity.getString(R.string.category_recentlyupdated);\n\n categories.add(categoryWhatsNew);\n categories.add(categoryRecentlyUpdated);\n categories.add(categoryAll);\n\n for (String s : db.getCategories()) {\n categories.add(s);\n }\n\n if (currentCategory == null)\n currentCategory = categoryWhatsNew;\n\n } finally {\n DB.releaseDB();\n }\n }\n\n \/\/ Tell the FDroid activity to update its \"Update (x)\" tab to correctly\n \/\/ reflect the number of updates available.\n private void notifyActivity() {\n fdroidActivity.refreshUpdateTabLabel();\n }\n\n public void repopulateLists() {\n\n long startTime = System.currentTimeMillis();\n\n clear();\n\n updateCategories();\n updateApps();\n notifyLists();\n notifyActivity();\n\n Log.d(\"FDroid\", \"Updated lists - \" + allApps.size() + \" in total\"\n + \" (update took \" + (System.currentTimeMillis() - startTime)\n + \" ms)\");\n }\n\n \/\/ Calculate the cutoff date we'll use for What's New and Recently\n \/\/ Updated...\n private Date calcMaxHistory() {\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n String daysPreference = prefs.getString(\"updateHistoryDays\", \"14\");\n int maxHistoryDays = Integer.parseInt(daysPreference);\n Calendar recent = Calendar.getInstance();\n recent.add(Calendar.DAY_OF_YEAR, -maxHistoryDays);\n return recent.getTime();\n }\n\n \/\/ recentDate could really be calculated here, but this is just a hack so\n \/\/ it doesn't need to be calculated for every single app. The reason it\n \/\/ isn't an instance variable is because the preferences may change, and\n \/\/ we wouldn't know.\n private boolean isInCategory(DB.App app, String category, Date recentDate) {\n if (category.equals(categoryAll)) {\n return true;\n }\n if (category.equals(categoryWhatsNew)) {\n if (app.added == null)\n return false;\n if (app.added.compareTo(recentDate) < 0)\n return false;\n return true;\n }\n if (category.equals(categoryRecentlyUpdated)) {\n if (app.lastUpdated == null)\n return false;\n \/\/ Don't include in the recently updated category if the\n \/\/ 'update' was actually it being added.\n if (app.lastUpdated.compareTo(app.added) == 0)\n return false;\n if (app.lastUpdated.compareTo(recentDate) < 0)\n return false;\n return true;\n }\n return app.categories.contains(category);\n }\n\n \/\/ Returns false if the app list is empty and the fdroid activity decided\n \/\/ to attempt updating it.\n private boolean updateApps() {\n\n allApps = ((FDroidApp)fdroidActivity.getApplication()).getApps();\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n boolean showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n\n if (allApps.isEmpty()) {\n \/\/ If its the first time we've run the app, this should update\n \/\/ the repos. If not, it will do nothing, presuming that the repos\n \/\/ are invalid, the internet is stuffed, the sky has fallen, etc...\n return fdroidActivity.updateEmptyRepos();\n }\n\n Date recentDate = calcMaxHistory();\n List availApps = new ArrayList();\n for (DB.App app : allApps) {\n\n \/\/ Add it to the list(s). Always to installed and updates, but\n \/\/ only to available if it's not filtered.\n if (!app.filtered && (showIncompatible || app.compatible)\n && isInCategory(app, currentCategory, recentDate)) {\n availApps.add(app);\n }\n if (app.installedVersion != null) {\n installedApps.addItem(app);\n if (app.toUpdate)\n canUpgradeApps.addItem(app);\n }\n }\n\n if (currentCategory.equals(categoryWhatsNew)) {\n Collections.sort(availApps, new WhatsNewComparator());\n } else if (currentCategory.equals(categoryRecentlyUpdated)) {\n Collections.sort(availApps, new RecentlyUpdatedComparator());\n }\n\n for (DB.App app : availApps)\n availableApps.addItem(app);\n\n return true;\n }\n\n public void setCurrentCategory(String currentCategory) {\n if (!this.currentCategory.equals(currentCategory)){\n this.currentCategory = currentCategory;\n repopulateLists();\n }\n }\n\n static class WhatsNewComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.added.compareTo(lhs.added);\n }\n }\n\n static class RecentlyUpdatedComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.lastUpdated.compareTo(lhs.lastUpdated);\n }\n }\n}\n\n\nCode-B:\npackage org.fdroid.fdroid;\n\nimport java.util.*;\n\nimport android.content.SharedPreferences;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.widget.ArrayAdapter;\n\nimport org.fdroid.fdroid.views.AppListAdapter;\nimport org.fdroid.fdroid.views.AvailableAppListAdapter;\nimport org.fdroid.fdroid.views.CanUpdateAppListAdapter;\nimport org.fdroid.fdroid.views.InstalledAppListAdapter;\n\n\/**\n * Should be owned by the FDroid Activity, but used by the AppListFragments.\n * The idea is that it takes a non-trivial amount of time to work this stuff\n * out, and it is quicker if we only do it once for each view, rather than\n * each fragment figuring out their own list independently.\n *\/\npublic class AppListManager {\n\n private List allApps = null;\n\n private FDroid fdroidActivity;\n\n private AppListAdapter availableApps;\n private AppListAdapter installedApps;\n private AppListAdapter canUpgradeApps;\n private ArrayAdapter categories;\n\n private String currentCategory = null;\n private String categoryAll = null;\n private String categoryWhatsNew = null;\n private String categoryRecentlyUpdated = null;\n\n public AppListAdapter getAvailableAdapter() {\n return availableApps;\n }\n\n public AppListAdapter getInstalledAdapter() {\n return installedApps;\n }\n\n public AppListAdapter getCanUpdateAdapter() {\n return canUpgradeApps;\n }\n\n public ArrayAdapter getCategoriesAdapter() {\n return categories;\n }\n\n public AppListManager(FDroid activity) {\n this.fdroidActivity = activity;\n\n availableApps = new AvailableAppListAdapter(fdroidActivity);\n installedApps = new InstalledAppListAdapter(fdroidActivity);\n canUpgradeApps = new CanUpdateAppListAdapter(fdroidActivity);\n\n \/\/ Needs to be created before createViews(), because that will use the\n \/\/ getCategoriesAdapter() accessor which expects this object...\n categories = new ArrayAdapter(activity,\n android.R.layout.simple_spinner_item, new ArrayList());\n categories\n .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n }\n\n private void clear() {\n installedApps.clear();\n availableApps.clear();\n canUpgradeApps.clear();\n categories.clear();\n }\n\n private void notifyLists() {\n \/\/ Tell the lists that the data behind the adapter has changed, so\n \/\/ they can refresh...\n availableApps.notifyDataSetChanged();\n installedApps.notifyDataSetChanged();\n canUpgradeApps.notifyDataSetChanged();\n categories.notifyDataSetChanged();\n }\n\n private void updateCategories() {\n try {\n DB db = DB.getDB();\n\n \/\/ Populate the category list with the real categories, and the\n \/\/ locally generated meta-categories for \"All\", \"What's New\" and\n \/\/ \"Recently Updated\"...\n categoryAll = fdroidActivity.getString(R.string.category_all);\n categoryWhatsNew = fdroidActivity.getString(R.string.category_whatsnew);\n categoryRecentlyUpdated = fdroidActivity.getString(R.string.category_recentlyupdated);\n\n categories.add(categoryWhatsNew);\n categories.add(categoryRecentlyUpdated);\n categories.add(categoryAll);\n\n for (String s : db.getCategories()) {\n categories.add(s);\n }\n\n if (currentCategory == null)\n currentCategory = categoryWhatsNew;\n\n } finally {\n DB.releaseDB();\n }\n }\n\n \/\/ Tell the FDroid activity to update its \"Update (x)\" tab to correctly\n \/\/ reflect the number of updates available.\n private void notifyActivity() {\n fdroidActivity.refreshUpdateTabLabel();\n }\n\n public void repopulateLists() {\n\n long startTime = System.currentTimeMillis();\n\n clear();\n\n updateCategories();\n updateApps();\n notifyLists();\n notifyActivity();\n\n Log.d(\"FDroid\", \"Updated lists - \" + allApps.size() + \" in total\"\n + \" (update took \" + (System.currentTimeMillis() - startTime)\n + \" ms)\");\n }\n\n \/\/ Calculate the cutoff date we'll use for What's New and Recently\n \/\/ Updated...\n private Date calcMaxHistory() {\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n String daysPreference = prefs.getString(\"updateHistoryDays\", \"14\");\n int maxHistoryDays = Integer.parseInt(daysPreference);\n Calendar recent = Calendar.getInstance();\n recent.add(Calendar.DAY_OF_YEAR, -maxHistoryDays);\n return recent.getTime();\n }\n\n \/\/ recentDate could really be calculated here, but this is just a hack so\n \/\/ it doesn't need to be calculated for every single app. The reason it\n \/\/ isn't an instance variable is because the preferences may change, and\n \/\/ we wouldn't know.\n private boolean isInCategory(DB.App app, String category, Date recentDate) {\n boolean isInCategory;\n if (category.equals(categoryAll)) {\n isInCategory = true;\n } else if (category.equals(categoryWhatsNew)) {\n if (app.added == null)\n isInCategory = false;\n else if (app.added.compareTo(recentDate) < 0)\n isInCategory = false;\n else\n isInCategory = true;\n } else if (category.equals(categoryRecentlyUpdated)) {\n if (app.lastUpdated == null)\n isInCategory = false;\n \/\/ Don't include in the recently updated category if the\n \/\/ 'update' was actually it being added.\n else if (app.lastUpdated.compareTo(app.added) == 0)\n isInCategory = false;\n else if (app.lastUpdated.compareTo(recentDate) < 0)\n isInCategory = false;\n else\n isInCategory = true;\n } else {\n isInCategory = category.equals(app.category);\n }\n return isInCategory;\n }\n\n \/\/ Returns false if the app list is empty and the fdroid activity decided\n \/\/ to attempt updating it.\n private boolean updateApps() {\n\n allApps = ((FDroidApp)fdroidActivity.getApplication()).getApps();\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n boolean showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n\n if (allApps.isEmpty()) {\n \/\/ If its the first time we've run the app, this should update\n \/\/ the repos. If not, it will do nothing, presuming that the repos\n \/\/ are invalid, the internet is stuffed, the sky has fallen, etc...\n return fdroidActivity.updateEmptyRepos();\n }\n\n Date recentDate = calcMaxHistory();\n List availApps = new ArrayList();\n for (DB.App app : allApps) {\n\n boolean isInCategory = isInCategory(app, currentCategory, recentDate);\n\n \/\/ Add it to the list(s). Always to installed and updates, but\n \/\/ only to available if it's not filtered.\n if (!app.filtered && isInCategory\n && (showIncompatible || app.compatible)) {\n availApps.add(app);\n }\n if (app.installedVersion != null) {\n installedApps.addItem(app);\n if (app.toUpdate)\n canUpgradeApps.addItem(app);\n }\n }\n\n if (currentCategory.equals(categoryWhatsNew)) {\n Collections.sort(availApps, new WhatsNewComparator());\n } else if (currentCategory.equals(categoryRecentlyUpdated)) {\n Collections.sort(availApps, new RecentlyUpdatedComparator());\n }\n\n for (DB.App app : availApps)\n availableApps.addItem(app);\n\n return true;\n }\n\n public void setCurrentCategory(String currentCategory) {\n if (!this.currentCategory.equals(currentCategory)){\n this.currentCategory = currentCategory;\n repopulateLists();\n }\n }\n\n static class WhatsNewComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.added.compareTo(lhs.added);\n }\n }\n\n static class RecentlyUpdatedComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.lastUpdated.compareTo(lhs.lastUpdated);\n }\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage org.fdroid.fdroid;\n\nimport java.util.*;\n\nimport android.content.SharedPreferences;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.widget.ArrayAdapter;\n\nimport org.fdroid.fdroid.views.AppListAdapter;\nimport org.fdroid.fdroid.views.AvailableAppListAdapter;\nimport org.fdroid.fdroid.views.CanUpdateAppListAdapter;\nimport org.fdroid.fdroid.views.InstalledAppListAdapter;\n\n\/**\n * Should be owned by the FDroid Activity, but used by the AppListFragments.\n * The idea is that it takes a non-trivial amount of time to work this stuff\n * out, and it is quicker if we only do it once for each view, rather than\n * each fragment figuring out their own list independently.\n *\/\npublic class AppListManager {\n\n private List allApps = null;\n\n private FDroid fdroidActivity;\n\n private AppListAdapter availableApps;\n private AppListAdapter installedApps;\n private AppListAdapter canUpgradeApps;\n private ArrayAdapter categories;\n\n private String currentCategory = null;\n private String categoryAll = null;\n private String categoryWhatsNew = null;\n private String categoryRecentlyUpdated = null;\n\n public AppListAdapter getAvailableAdapter() {\n return availableApps;\n }\n\n public AppListAdapter getInstalledAdapter() {\n return installedApps;\n }\n\n public AppListAdapter getCanUpdateAdapter() {\n return canUpgradeApps;\n }\n\n public ArrayAdapter getCategoriesAdapter() {\n return categories;\n }\n\n public AppListManager(FDroid activity) {\n this.fdroidActivity = activity;\n\n availableApps = new AvailableAppListAdapter(fdroidActivity);\n installedApps = new InstalledAppListAdapter(fdroidActivity);\n canUpgradeApps = new CanUpdateAppListAdapter(fdroidActivity);\n\n \/\/ Needs to be created before createViews(), because that will use the\n \/\/ getCategoriesAdapter() accessor which expects this object...\n categories = new ArrayAdapter(activity,\n android.R.layout.simple_spinner_item, new ArrayList());\n categories\n .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n }\n\n private void clear() {\n installedApps.clear();\n availableApps.clear();\n canUpgradeApps.clear();\n categories.clear();\n }\n\n private void notifyLists() {\n \/\/ Tell the lists that the data behind the adapter has changed, so\n \/\/ they can refresh...\n availableApps.notifyDataSetChanged();\n installedApps.notifyDataSetChanged();\n canUpgradeApps.notifyDataSetChanged();\n categories.notifyDataSetChanged();\n }\n\n private void updateCategories() {\n try {\n DB db = DB.getDB();\n\n \/\/ Populate the category list with the real categories, and the\n \/\/ locally generated meta-categories for \"All\", \"What's New\" and\n \/\/ \"Recently Updated\"...\n categoryAll = fdroidActivity.getString(R.string.category_all);\n categoryWhatsNew = fdroidActivity.getString(R.string.category_whatsnew);\n categoryRecentlyUpdated = fdroidActivity.getString(R.string.category_recentlyupdated);\n\n categories.add(categoryWhatsNew);\n categories.add(categoryRecentlyUpdated);\n categories.add(categoryAll);\n\n for (String s : db.getCategories()) {\n categories.add(s);\n }\n\n if (currentCategory == null)\n currentCategory = categoryWhatsNew;\n\n } finally {\n DB.releaseDB();\n }\n }\n\n \/\/ Tell the FDroid activity to update its \"Update (x)\" tab to correctly\n \/\/ reflect the number of updates available.\n private void notifyActivity() {\n fdroidActivity.refreshUpdateTabLabel();\n }\n\n public void repopulateLists() {\n\n long startTime = System.currentTimeMillis();\n\n clear();\n\n updateCategories();\n updateApps();\n notifyLists();\n notifyActivity();\n\n Log.d(\"FDroid\", \"Updated lists - \" + allApps.size() + \" in total\"\n + \" (update took \" + (System.currentTimeMillis() - startTime)\n + \" ms)\");\n }\n\n \/\/ Calculate the cutoff date we'll use for What's New and Recently\n \/\/ Updated...\n private Date calcMaxHistory() {\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n String daysPreference = prefs.getString(\"updateHistoryDays\", \"14\");\n int maxHistoryDays = Integer.parseInt(daysPreference);\n Calendar recent = Calendar.getInstance();\n recent.add(Calendar.DAY_OF_YEAR, -maxHistoryDays);\n return recent.getTime();\n }\n\n \/\/ recentDate could really be calculated here, but this is just a hack so\n \/\/ it doesn't need to be calculated for every single app. The reason it\n \/\/ isn't an instance variable is because the preferences may change, and\n \/\/ we wouldn't know.\n private boolean isInCategory(DB.App app, String category, Date recentDate) {\n boolean isInCategory;\n if (category.equals(categoryAll)) {\n isInCategory = true;\n } else if (category.equals(categoryWhatsNew)) {\n if (app.added == null)\n isInCategory = false;\n else if (app.added.compareTo(recentDate) < 0)\n isInCategory = false;\n else\n isInCategory = true;\n } else if (category.equals(categoryRecentlyUpdated)) {\n if (app.lastUpdated == null)\n isInCategory = false;\n \/\/ Don't include in the recently updated category if the\n \/\/ 'update' was actually it being added.\n else if (app.lastUpdated.compareTo(app.added) == 0)\n isInCategory = false;\n else if (app.lastUpdated.compareTo(recentDate) < 0)\n isInCategory = false;\n else\n isInCategory = true;\n } else {\n isInCategory = category.equals(app.category);\n }\n return isInCategory;\n }\n\n \/\/ Returns false if the app list is empty and the fdroid activity decided\n \/\/ to attempt updating it.\n private boolean updateApps() {\n\n allApps = ((FDroidApp)fdroidActivity.getApplication()).getApps();\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n boolean showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n\n if (allApps.isEmpty()) {\n \/\/ If its the first time we've run the app, this should update\n \/\/ the repos. If not, it will do nothing, presuming that the repos\n \/\/ are invalid, the internet is stuffed, the sky has fallen, etc...\n return fdroidActivity.updateEmptyRepos();\n }\n\n Date recentDate = calcMaxHistory();\n List availApps = new ArrayList();\n for (DB.App app : allApps) {\n\n boolean isInCategory = isInCategory(app, currentCategory, recentDate);\n\n \/\/ Add it to the list(s). Always to installed and updates, but\n \/\/ only to available if it's not filtered.\n if (!app.filtered && isInCategory\n && (showIncompatible || app.compatible)) {\n availApps.add(app);\n }\n if (app.installedVersion != null) {\n installedApps.addItem(app);\n if (app.toUpdate)\n canUpgradeApps.addItem(app);\n }\n }\n\n if (currentCategory.equals(categoryWhatsNew)) {\n Collections.sort(availApps, new WhatsNewComparator());\n } else if (currentCategory.equals(categoryRecentlyUpdated)) {\n Collections.sort(availApps, new RecentlyUpdatedComparator());\n }\n\n for (DB.App app : availApps)\n availableApps.addItem(app);\n\n return true;\n }\n\n public void setCurrentCategory(String currentCategory) {\n if (!this.currentCategory.equals(currentCategory)){\n this.currentCategory = currentCategory;\n repopulateLists();\n }\n }\n\n static class WhatsNewComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.added.compareTo(lhs.added);\n }\n }\n\n static class RecentlyUpdatedComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.lastUpdated.compareTo(lhs.lastUpdated);\n }\n }\n}\n\n\nCode-B:\npackage org.fdroid.fdroid;\n\nimport java.util.*;\n\nimport android.content.SharedPreferences;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.widget.ArrayAdapter;\n\nimport org.fdroid.fdroid.views.AppListAdapter;\nimport org.fdroid.fdroid.views.AvailableAppListAdapter;\nimport org.fdroid.fdroid.views.CanUpdateAppListAdapter;\nimport org.fdroid.fdroid.views.InstalledAppListAdapter;\n\n\/**\n * Should be owned by the FDroid Activity, but used by the AppListFragments.\n * The idea is that it takes a non-trivial amount of time to work this stuff\n * out, and it is quicker if we only do it once for each view, rather than\n * each fragment figuring out their own list independently.\n *\/\npublic class AppListManager {\n\n private List allApps = null;\n\n private FDroid fdroidActivity;\n\n private AppListAdapter availableApps;\n private AppListAdapter installedApps;\n private AppListAdapter canUpgradeApps;\n private ArrayAdapter categories;\n\n private String currentCategory = null;\n private String categoryAll = null;\n private String categoryWhatsNew = null;\n private String categoryRecentlyUpdated = null;\n\n public AppListAdapter getAvailableAdapter() {\n return availableApps;\n }\n\n public AppListAdapter getInstalledAdapter() {\n return installedApps;\n }\n\n public AppListAdapter getCanUpdateAdapter() {\n return canUpgradeApps;\n }\n\n public ArrayAdapter getCategoriesAdapter() {\n return categories;\n }\n\n public AppListManager(FDroid activity) {\n this.fdroidActivity = activity;\n\n availableApps = new AvailableAppListAdapter(fdroidActivity);\n installedApps = new InstalledAppListAdapter(fdroidActivity);\n canUpgradeApps = new CanUpdateAppListAdapter(fdroidActivity);\n\n \/\/ Needs to be created before createViews(), because that will use the\n \/\/ getCategoriesAdapter() accessor which expects this object...\n categories = new ArrayAdapter(activity,\n android.R.layout.simple_spinner_item, new ArrayList());\n categories\n .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);\n }\n\n private void clear() {\n installedApps.clear();\n availableApps.clear();\n canUpgradeApps.clear();\n categories.clear();\n }\n\n private void notifyLists() {\n \/\/ Tell the lists that the data behind the adapter has changed, so\n \/\/ they can refresh...\n availableApps.notifyDataSetChanged();\n installedApps.notifyDataSetChanged();\n canUpgradeApps.notifyDataSetChanged();\n categories.notifyDataSetChanged();\n }\n\n private void updateCategories() {\n try {\n DB db = DB.getDB();\n\n \/\/ Populate the category list with the real categories, and the\n \/\/ locally generated meta-categories for \"All\", \"What's New\" and\n \/\/ \"Recently Updated\"...\n categoryAll = fdroidActivity.getString(R.string.category_all);\n categoryWhatsNew = fdroidActivity.getString(R.string.category_whatsnew);\n categoryRecentlyUpdated = fdroidActivity.getString(R.string.category_recentlyupdated);\n\n categories.add(categoryWhatsNew);\n categories.add(categoryRecentlyUpdated);\n categories.add(categoryAll);\n\n for (String s : db.getCategories()) {\n categories.add(s);\n }\n\n if (currentCategory == null)\n currentCategory = categoryWhatsNew;\n\n } finally {\n DB.releaseDB();\n }\n }\n\n \/\/ Tell the FDroid activity to update its \"Update (x)\" tab to correctly\n \/\/ reflect the number of updates available.\n private void notifyActivity() {\n fdroidActivity.refreshUpdateTabLabel();\n }\n\n public void repopulateLists() {\n\n long startTime = System.currentTimeMillis();\n\n clear();\n\n updateCategories();\n updateApps();\n notifyLists();\n notifyActivity();\n\n Log.d(\"FDroid\", \"Updated lists - \" + allApps.size() + \" in total\"\n + \" (update took \" + (System.currentTimeMillis() - startTime)\n + \" ms)\");\n }\n\n \/\/ Calculate the cutoff date we'll use for What's New and Recently\n \/\/ Updated...\n private Date calcMaxHistory() {\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n String daysPreference = prefs.getString(\"updateHistoryDays\", \"14\");\n int maxHistoryDays = Integer.parseInt(daysPreference);\n Calendar recent = Calendar.getInstance();\n recent.add(Calendar.DAY_OF_YEAR, -maxHistoryDays);\n return recent.getTime();\n }\n\n \/\/ recentDate could really be calculated here, but this is just a hack so\n \/\/ it doesn't need to be calculated for every single app. The reason it\n \/\/ isn't an instance variable is because the preferences may change, and\n \/\/ we wouldn't know.\n private boolean isInCategory(DB.App app, String category, Date recentDate) {\n if (category.equals(categoryAll)) {\n return true;\n }\n if (category.equals(categoryWhatsNew)) {\n if (app.added == null)\n return false;\n if (app.added.compareTo(recentDate) < 0)\n return false;\n return true;\n }\n if (category.equals(categoryRecentlyUpdated)) {\n if (app.lastUpdated == null)\n return false;\n \/\/ Don't include in the recently updated category if the\n \/\/ 'update' was actually it being added.\n if (app.lastUpdated.compareTo(app.added) == 0)\n return false;\n if (app.lastUpdated.compareTo(recentDate) < 0)\n return false;\n return true;\n }\n return app.categories.contains(category);\n }\n\n \/\/ Returns false if the app list is empty and the fdroid activity decided\n \/\/ to attempt updating it.\n private boolean updateApps() {\n\n allApps = ((FDroidApp)fdroidActivity.getApplication()).getApps();\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(fdroidActivity.getBaseContext());\n boolean showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n\n if (allApps.isEmpty()) {\n \/\/ If its the first time we've run the app, this should update\n \/\/ the repos. If not, it will do nothing, presuming that the repos\n \/\/ are invalid, the internet is stuffed, the sky has fallen, etc...\n return fdroidActivity.updateEmptyRepos();\n }\n\n Date recentDate = calcMaxHistory();\n List availApps = new ArrayList();\n for (DB.App app : allApps) {\n\n \/\/ Add it to the list(s). Always to installed and updates, but\n \/\/ only to available if it's not filtered.\n if (!app.filtered && (showIncompatible || app.compatible)\n && isInCategory(app, currentCategory, recentDate)) {\n availApps.add(app);\n }\n if (app.installedVersion != null) {\n installedApps.addItem(app);\n if (app.toUpdate)\n canUpgradeApps.addItem(app);\n }\n }\n\n if (currentCategory.equals(categoryWhatsNew)) {\n Collections.sort(availApps, new WhatsNewComparator());\n } else if (currentCategory.equals(categoryRecentlyUpdated)) {\n Collections.sort(availApps, new RecentlyUpdatedComparator());\n }\n\n for (DB.App app : availApps)\n availableApps.addItem(app);\n\n return true;\n }\n\n public void setCurrentCategory(String currentCategory) {\n if (!this.currentCategory.equals(currentCategory)){\n this.currentCategory = currentCategory;\n repopulateLists();\n }\n }\n\n static class WhatsNewComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.added.compareTo(lhs.added);\n }\n }\n\n static class RecentlyUpdatedComparator implements Comparator {\n @Override\n public int compare(DB.App lhs, DB.App rhs) {\n return rhs.lastUpdated.compareTo(lhs.lastUpdated);\n }\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/alpenf\/fdroid-alpha\/commit\/04298f8886b2e857132a3bc9fed4cba9c755ee23","commit_message":"'\\\\\"DownloaderService: only broadcast progress when it actually changes\\\\n\\\\nOn a slow download","source_code":"package org.fdroid.fdroid.net;\n\nimport android.net.Uri;\nimport android.support.annotation.NonNull;\nimport android.text.format.DateUtils;\nimport org.fdroid.fdroid.ProgressListener;\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.ConnectException;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_CONNECTION_FAILED = \"org.fdroid.fdroid.net.Downloader.action.CONNECTION_FAILED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n public static final String EXTRA_ERROR_MESSAGE = \"org.fdroid.fdroid.net.Downloader.extra.ERROR_MESSAGE\";\n public static final String EXTRA_REPO_ID = \"org.fdroid.fdroid.net.Downloader.extra.REPO_ID\";\n public static final String EXTRA_CANONICAL_URL = \"org.fdroid.fdroid.net.Downloader.extra.CANONICAL_URL\";\n public static final String EXTRA_MIRROR_URL = \"org.fdroid.fdroid.net.Downloader.extra.MIRROR_URL\";\n\n public static final int DEFAULT_TIMEOUT = 10000;\n public static final int SECOND_TIMEOUT = (int) DateUtils.MINUTE_IN_MILLIS;\n public static final int LONGEST_TIMEOUT = 600000; \/\/ 10 minutes\n\n private volatile boolean cancelled = false;\n private volatile long bytesRead;\n private volatile long totalBytes;\n\n public final File outputFile;\n\n final String urlString;\n String cacheTag;\n boolean notFound;\n\n private volatile int timeout = DEFAULT_TIMEOUT;\n\n \/**\n * For sending download progress, should only be called in {@link #progressTask}\n *\/\n private volatile ProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(Uri uri, File destFile) {\n this.urlString = uri.toString();\n outputFile = destFile;\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(ProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n public void setTimeout(int ms) {\n timeout = ms;\n }\n\n public int getTimeout() {\n return timeout;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract long totalDownloadSize();\n\n public abstract void download() throws ConnectException, IOException, InterruptedException;\n\n \/**\n * @return whether the requested file was not found in the repo (e.g. HTTP 404 Not Found)\n *\/\n public boolean isNotFound() {\n return notFound;\n }\n\n void downloadFromStream(int bufferSize, boolean resumable) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n OutputStream outputStream = new FileOutputStream(outputFile, resumable);\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize, outputStream);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n *\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize, OutputStream output)\n throws IOException, InterruptedException {\n Timer timer = new Timer();\n try {\n bytesRead = 0;\n totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n timer.scheduleAtFixedRate(progressTask, 0, 100);\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n bytesRead += count;\n output.write(buffer, 0, count);\n }\n } finally {\n downloaderProgressListener = null;\n timer.cancel();\n timer.purge();\n output.flush();\n output.close();\n }\n }\n\n \/**\n * Send progress updates on a timer to avoid flooding receivers with pointless events.\n *\/\n private final TimerTask progressTask = new TimerTask() {\n @Override\n public void run() {\n if (downloaderProgressListener != null) {\n downloaderProgressListener.onProgress(bytesRead, totalBytes);\n }\n }\n };\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(@NonNull byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(@NonNull byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n","target_code":"package org.fdroid.fdroid.net;\n\nimport android.net.Uri;\nimport android.support.annotation.NonNull;\nimport android.text.format.DateUtils;\nimport org.fdroid.fdroid.ProgressListener;\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.ConnectException;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_CONNECTION_FAILED = \"org.fdroid.fdroid.net.Downloader.action.CONNECTION_FAILED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n public static final String EXTRA_ERROR_MESSAGE = \"org.fdroid.fdroid.net.Downloader.extra.ERROR_MESSAGE\";\n public static final String EXTRA_REPO_ID = \"org.fdroid.fdroid.net.Downloader.extra.REPO_ID\";\n public static final String EXTRA_CANONICAL_URL = \"org.fdroid.fdroid.net.Downloader.extra.CANONICAL_URL\";\n public static final String EXTRA_MIRROR_URL = \"org.fdroid.fdroid.net.Downloader.extra.MIRROR_URL\";\n\n public static final int DEFAULT_TIMEOUT = 10000;\n public static final int SECOND_TIMEOUT = (int) DateUtils.MINUTE_IN_MILLIS;\n public static final int LONGEST_TIMEOUT = 600000; \/\/ 10 minutes\n\n private volatile boolean cancelled = false;\n private volatile long bytesRead;\n private volatile long totalBytes;\n\n public final File outputFile;\n\n final String urlString;\n String cacheTag;\n boolean notFound;\n\n private volatile int timeout = DEFAULT_TIMEOUT;\n\n \/**\n * For sending download progress, should only be called in {@link #progressTask}\n *\/\n private volatile ProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(Uri uri, File destFile) {\n this.urlString = uri.toString();\n outputFile = destFile;\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(ProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n public void setTimeout(int ms) {\n timeout = ms;\n }\n\n public int getTimeout() {\n return timeout;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract long totalDownloadSize();\n\n public abstract void download() throws ConnectException, IOException, InterruptedException;\n\n \/**\n * @return whether the requested file was not found in the repo (e.g. HTTP 404 Not Found)\n *\/\n public boolean isNotFound() {\n return notFound;\n }\n\n void downloadFromStream(int bufferSize, boolean resumable) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n OutputStream outputStream = new FileOutputStream(outputFile, resumable);\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize, outputStream);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n *\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize, OutputStream output)\n throws IOException, InterruptedException {\n Timer timer = new Timer();\n try {\n bytesRead = 0;\n totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n timer.scheduleAtFixedRate(progressTask, 0, 100);\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n bytesRead += count;\n output.write(buffer, 0, count);\n }\n } finally {\n downloaderProgressListener = null;\n timer.cancel();\n timer.purge();\n output.flush();\n output.close();\n }\n }\n\n \/**\n * Send progress updates on a timer to avoid flooding receivers with pointless events.\n *\/\n private final TimerTask progressTask = new TimerTask() {\n private long lastBytesRead = Long.MIN_VALUE;\n private long lastTotalBytes = Long.MIN_VALUE;\n\n @Override\n public void run() {\n if (downloaderProgressListener != null\n && (bytesRead != lastBytesRead || totalBytes != lastTotalBytes)) {\n downloaderProgressListener.onProgress(bytesRead, totalBytes);\n lastBytesRead = bytesRead;\n lastTotalBytes = totalBytes;\n }\n }\n };\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(@NonNull byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(@NonNull byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid.net;\n\nimport android.net.Uri;\nimport android.support.annotation.NonNull;\nimport android.text.format.DateUtils;\nimport org.fdroid.fdroid.ProgressListener;\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.ConnectException;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_CONNECTION_FAILED = \"org.fdroid.fdroid.net.Downloader.action.CONNECTION_FAILED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n public static final String EXTRA_ERROR_MESSAGE = \"org.fdroid.fdroid.net.Downloader.extra.ERROR_MESSAGE\";\n public static final String EXTRA_REPO_ID = \"org.fdroid.fdroid.net.Downloader.extra.REPO_ID\";\n public static final String EXTRA_CANONICAL_URL = \"org.fdroid.fdroid.net.Downloader.extra.CANONICAL_URL\";\n public static final String EXTRA_MIRROR_URL = \"org.fdroid.fdroid.net.Downloader.extra.MIRROR_URL\";\n\n public static final int DEFAULT_TIMEOUT = 10000;\n public static final int SECOND_TIMEOUT = (int) DateUtils.MINUTE_IN_MILLIS;\n public static final int LONGEST_TIMEOUT = 600000; \/\/ 10 minutes\n\n private volatile boolean cancelled = false;\n private volatile long bytesRead;\n private volatile long totalBytes;\n\n public final File outputFile;\n\n final String urlString;\n String cacheTag;\n boolean notFound;\n\n private volatile int timeout = DEFAULT_TIMEOUT;\n\n \/**\n * For sending download progress, should only be called in {@link #progressTask}\n *\/\n private volatile ProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(Uri uri, File destFile) {\n this.urlString = uri.toString();\n outputFile = destFile;\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(ProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n public void setTimeout(int ms) {\n timeout = ms;\n }\n\n public int getTimeout() {\n return timeout;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract long totalDownloadSize();\n\n public abstract void download() throws ConnectException, IOException, InterruptedException;\n\n \/**\n * @return whether the requested file was not found in the repo (e.g. HTTP 404 Not Found)\n *\/\n public boolean isNotFound() {\n return notFound;\n }\n\n void downloadFromStream(int bufferSize, boolean resumable) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n OutputStream outputStream = new FileOutputStream(outputFile, resumable);\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize, outputStream);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n *\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize, OutputStream output)\n throws IOException, InterruptedException {\n Timer timer = new Timer();\n try {\n bytesRead = 0;\n totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n timer.scheduleAtFixedRate(progressTask, 0, 100);\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n bytesRead += count;\n output.write(buffer, 0, count);\n }\n } finally {\n downloaderProgressListener = null;\n timer.cancel();\n timer.purge();\n output.flush();\n output.close();\n }\n }\n\n \/**\n * Send progress updates on a timer to avoid flooding receivers with pointless events.\n *\/\n private final TimerTask progressTask = new TimerTask() {\n @Override\n public void run() {\n if (downloaderProgressListener != null) {\n downloaderProgressListener.onProgress(bytesRead, totalBytes);\n }\n }\n };\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(@NonNull byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(@NonNull byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid.net;\n\nimport android.net.Uri;\nimport android.support.annotation.NonNull;\nimport android.text.format.DateUtils;\nimport org.fdroid.fdroid.ProgressListener;\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.ConnectException;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_CONNECTION_FAILED = \"org.fdroid.fdroid.net.Downloader.action.CONNECTION_FAILED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n public static final String EXTRA_ERROR_MESSAGE = \"org.fdroid.fdroid.net.Downloader.extra.ERROR_MESSAGE\";\n public static final String EXTRA_REPO_ID = \"org.fdroid.fdroid.net.Downloader.extra.REPO_ID\";\n public static final String EXTRA_CANONICAL_URL = \"org.fdroid.fdroid.net.Downloader.extra.CANONICAL_URL\";\n public static final String EXTRA_MIRROR_URL = \"org.fdroid.fdroid.net.Downloader.extra.MIRROR_URL\";\n\n public static final int DEFAULT_TIMEOUT = 10000;\n public static final int SECOND_TIMEOUT = (int) DateUtils.MINUTE_IN_MILLIS;\n public static final int LONGEST_TIMEOUT = 600000; \/\/ 10 minutes\n\n private volatile boolean cancelled = false;\n private volatile long bytesRead;\n private volatile long totalBytes;\n\n public final File outputFile;\n\n final String urlString;\n String cacheTag;\n boolean notFound;\n\n private volatile int timeout = DEFAULT_TIMEOUT;\n\n \/**\n * For sending download progress, should only be called in {@link #progressTask}\n *\/\n private volatile ProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(Uri uri, File destFile) {\n this.urlString = uri.toString();\n outputFile = destFile;\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(ProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n public void setTimeout(int ms) {\n timeout = ms;\n }\n\n public int getTimeout() {\n return timeout;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract long totalDownloadSize();\n\n public abstract void download() throws ConnectException, IOException, InterruptedException;\n\n \/**\n * @return whether the requested file was not found in the repo (e.g. HTTP 404 Not Found)\n *\/\n public boolean isNotFound() {\n return notFound;\n }\n\n void downloadFromStream(int bufferSize, boolean resumable) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n OutputStream outputStream = new FileOutputStream(outputFile, resumable);\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize, outputStream);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n *\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize, OutputStream output)\n throws IOException, InterruptedException {\n Timer timer = new Timer();\n try {\n bytesRead = 0;\n totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n timer.scheduleAtFixedRate(progressTask, 0, 100);\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n bytesRead += count;\n output.write(buffer, 0, count);\n }\n } finally {\n downloaderProgressListener = null;\n timer.cancel();\n timer.purge();\n output.flush();\n output.close();\n }\n }\n\n \/**\n * Send progress updates on a timer to avoid flooding receivers with pointless events.\n *\/\n private final TimerTask progressTask = new TimerTask() {\n @Override\n public void run() {\n if (downloaderProgressListener != null) {\n downloaderProgressListener.onProgress(bytesRead, totalBytes);\n }\n }\n };\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(@NonNull byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(@NonNull byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage org.fdroid.fdroid.net;\n\nimport android.net.Uri;\nimport android.support.annotation.NonNull;\nimport android.text.format.DateUtils;\nimport org.fdroid.fdroid.ProgressListener;\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.ConnectException;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_CONNECTION_FAILED = \"org.fdroid.fdroid.net.Downloader.action.CONNECTION_FAILED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n public static final String EXTRA_ERROR_MESSAGE = \"org.fdroid.fdroid.net.Downloader.extra.ERROR_MESSAGE\";\n public static final String EXTRA_REPO_ID = \"org.fdroid.fdroid.net.Downloader.extra.REPO_ID\";\n public static final String EXTRA_CANONICAL_URL = \"org.fdroid.fdroid.net.Downloader.extra.CANONICAL_URL\";\n public static final String EXTRA_MIRROR_URL = \"org.fdroid.fdroid.net.Downloader.extra.MIRROR_URL\";\n\n public static final int DEFAULT_TIMEOUT = 10000;\n public static final int SECOND_TIMEOUT = (int) DateUtils.MINUTE_IN_MILLIS;\n public static final int LONGEST_TIMEOUT = 600000; \/\/ 10 minutes\n\n private volatile boolean cancelled = false;\n private volatile long bytesRead;\n private volatile long totalBytes;\n\n public final File outputFile;\n\n final String urlString;\n String cacheTag;\n boolean notFound;\n\n private volatile int timeout = DEFAULT_TIMEOUT;\n\n \/**\n * For sending download progress, should only be called in {@link #progressTask}\n *\/\n private volatile ProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(Uri uri, File destFile) {\n this.urlString = uri.toString();\n outputFile = destFile;\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(ProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n public void setTimeout(int ms) {\n timeout = ms;\n }\n\n public int getTimeout() {\n return timeout;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract long totalDownloadSize();\n\n public abstract void download() throws ConnectException, IOException, InterruptedException;\n\n \/**\n * @return whether the requested file was not found in the repo (e.g. HTTP 404 Not Found)\n *\/\n public boolean isNotFound() {\n return notFound;\n }\n\n void downloadFromStream(int bufferSize, boolean resumable) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n OutputStream outputStream = new FileOutputStream(outputFile, resumable);\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize, outputStream);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n *\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize, OutputStream output)\n throws IOException, InterruptedException {\n Timer timer = new Timer();\n try {\n bytesRead = 0;\n totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n timer.scheduleAtFixedRate(progressTask, 0, 100);\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n bytesRead += count;\n output.write(buffer, 0, count);\n }\n } finally {\n downloaderProgressListener = null;\n timer.cancel();\n timer.purge();\n output.flush();\n output.close();\n }\n }\n\n \/**\n * Send progress updates on a timer to avoid flooding receivers with pointless events.\n *\/\n private final TimerTask progressTask = new TimerTask() {\n @Override\n public void run() {\n if (downloaderProgressListener != null) {\n downloaderProgressListener.onProgress(bytesRead, totalBytes);\n }\n }\n };\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(@NonNull byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(@NonNull byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite downloader service to only broadcast progress when it actually changes. Write the entire code and no other text in the response.\n\n### Concepts:\n[in] TimerTask.run() function\n[in] TimerTask instance\n[hint] On a slow download, this code could send like 100+ updates even though no more data had been received.\n\n### Given program:\n```java\npackage org.fdroid.fdroid.net;\n\nimport android.net.Uri;\nimport android.support.annotation.NonNull;\nimport android.text.format.DateUtils;\nimport org.fdroid.fdroid.ProgressListener;\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.ConnectException;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_CONNECTION_FAILED = \"org.fdroid.fdroid.net.Downloader.action.CONNECTION_FAILED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n public static final String EXTRA_ERROR_MESSAGE = \"org.fdroid.fdroid.net.Downloader.extra.ERROR_MESSAGE\";\n public static final String EXTRA_REPO_ID = \"org.fdroid.fdroid.net.Downloader.extra.REPO_ID\";\n public static final String EXTRA_CANONICAL_URL = \"org.fdroid.fdroid.net.Downloader.extra.CANONICAL_URL\";\n public static final String EXTRA_MIRROR_URL = \"org.fdroid.fdroid.net.Downloader.extra.MIRROR_URL\";\n\n public static final int DEFAULT_TIMEOUT = 10000;\n public static final int SECOND_TIMEOUT = (int) DateUtils.MINUTE_IN_MILLIS;\n public static final int LONGEST_TIMEOUT = 600000; \/\/ 10 minutes\n\n private volatile boolean cancelled = false;\n private volatile long bytesRead;\n private volatile long totalBytes;\n\n public final File outputFile;\n\n final String urlString;\n String cacheTag;\n boolean notFound;\n\n private volatile int timeout = DEFAULT_TIMEOUT;\n\n \/**\n * For sending download progress, should only be called in {@link #progressTask}\n *\/\n private volatile ProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(Uri uri, File destFile) {\n this.urlString = uri.toString();\n outputFile = destFile;\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(ProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n public void setTimeout(int ms) {\n timeout = ms;\n }\n\n public int getTimeout() {\n return timeout;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract long totalDownloadSize();\n\n public abstract void download() throws ConnectException, IOException, InterruptedException;\n\n \/**\n * @return whether the requested file was not found in the repo (e.g. HTTP 404 Not Found)\n *\/\n public boolean isNotFound() {\n return notFound;\n }\n\n void downloadFromStream(int bufferSize, boolean resumable) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n OutputStream outputStream = new FileOutputStream(outputFile, resumable);\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize, outputStream);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n *\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize, OutputStream output)\n throws IOException, InterruptedException {\n Timer timer = new Timer();\n try {\n bytesRead = 0;\n totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n timer.scheduleAtFixedRate(progressTask, 0, 100);\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n bytesRead += count;\n output.write(buffer, 0, count);\n }\n } finally {\n downloaderProgressListener = null;\n timer.cancel();\n timer.purge();\n output.flush();\n output.close();\n }\n }\n\n \/**\n * Send progress updates on a timer to avoid flooding receivers with pointless events.\n *\/\n private final TimerTask progressTask = new TimerTask() {\n @Override\n public void run() {\n if (downloaderProgressListener != null) {\n downloaderProgressListener.onProgress(bytesRead, totalBytes);\n }\n }\n };\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(@NonNull byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(@NonNull byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/*\n * Copyright 2014 Chris Banes\n * Copyright 2016 Christophe Beyls\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage com.example.android.common.view;\n\nimport android.content.Context;\nimport android.content.res.ColorStateList;\nimport android.content.res.TypedArray;\nimport android.graphics.Typeface;\nimport android.os.Build;\nimport android.support.annotation.ColorInt;\nimport android.support.annotation.IdRes;\nimport android.support.annotation.LayoutRes;\nimport android.support.v4.view.PagerAdapter;\nimport android.support.v4.view.ViewPager;\nimport android.util.AttributeSet;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.widget.HorizontalScrollView;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\n\nimport be.digitalia.fosdem.R;\n\n\/**\n *\/\npublic class SlidingTabLayout extends HorizontalScrollView {\n\n\tpublic interface TabListener {\n\n\t\tvoid onTabSelected(int pos);\n\n\t\tvoid onTabReSelected(int pos);\n\n\t}\n\n\tprivate static final int[][] TAB_COLOR_STATES = new int[][]{SELECTED_STATE_SET, EMPTY_STATE_SET};\n\n\tprivate int mTitleOffset;\n\n\tprivate int mTabViewLayoutId;\n\tprivate int mTabViewTextViewId;\n\tprivate boolean mDistributeEvenly;\n\n\tprivate ColorStateList mTextColor;\n\n\tprivate ViewPager mViewPager;\n\n\tprivate TabListener mTabListener;\n\n\tprivate final SlidingTabStrip mTabStrip;\n\n\tpublic SlidingTabLayout(Context context) {\n\t\tthis(context, null);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs) {\n\t\tthis(context, attrs, 0);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {\n\t\tsuper(context, attrs, defStyle);\n\n\t\t\/\/ Disable the Scroll Bar\n\t\tsetHorizontalScrollBarEnabled(false);\n\t\t\/\/ Make sure that the Tab Strips fills this View\n\t\tsetFillViewport(true);\n\n\t\tmTabStrip = new SlidingTabStrip(context);\n\t\taddView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);\n\n\t\tTypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SlidingTabLayout,\n\t\t\t\tdefStyle, R.style.SlidingTabLayout);\n\n\t\tmTabStrip.setSelectedIndicatorHeight(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_indicatorHeight, 0));\n\t\tmTabStrip.setSelectedIndicatorColor(a.getColor(R.styleable.SlidingTabLayout_indicatorColor, 0));\n\t\tmTextColor = a.getColorStateList(R.styleable.SlidingTabLayout_textColor);\n\t\tif ((mTextColor != null) && a.hasValue(R.styleable.SlidingTabLayout_selectedTextColor)) {\n\t\t\tsetTabTextColors(mTextColor.getDefaultColor(), a.getColor(R.styleable.SlidingTabLayout_selectedTextColor, 0));\n\t\t}\n\t\tsetContentInsetStart(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_contentInsetStart, 0));\n\t\tsetDistributeEvenly(a.getBoolean(R.styleable.SlidingTabLayout_distributeEvenly, false));\n\n\t\ta.recycle();\n\t}\n\n\tpublic void setContentInsetStart(int offset) {\n\t\tmTitleOffset = offset;\n\t\tmTabStrip.setPadding(offset, 0, 0, 0);\n\t}\n\n\tpublic void setDistributeEvenly(boolean distributeEvenly) {\n\t\tmDistributeEvenly = distributeEvenly;\n\t}\n\n\t\/**\n\t * Sets the color to be used for indicating the selected tab.\n\t * This will override the style color.\n\t *\/\n\tpublic void setSelectedTabIndicatorColor(@ColorInt int color) {\n\t\tmTabStrip.setSelectedIndicatorColor(color);\n\t}\n\n\tpublic void setSelectedTabIndicatorHeight(int height) {\n\t\tmTabStrip.setSelectedIndicatorHeight(height);\n\t}\n\n\tpublic void setTabTextColors(ColorStateList color) {\n\t\tmTextColor = color;\n\t}\n\n\tpublic void setTabTextColors(@ColorInt int normalColor, @ColorInt int selectedColor) {\n\t\tmTextColor = createColorStateList(normalColor, selectedColor);\n\t}\n\n\tprivate static ColorStateList createColorStateList(int defaultColor, int selectedColor) {\n\t\tfinal int[] colors = new int[]{selectedColor, defaultColor};\n\t\treturn new ColorStateList(TAB_COLOR_STATES, colors);\n\t}\n\n\t\/**\n\t * Set the custom layout to be inflated for the tab views.\n\t *\n\t * @param layoutResId Layout id to be inflated\n\t * @param textViewId id of the {@link TextView} in the inflated view\n\t *\/\n\tpublic void setCustomTabView(@LayoutRes int layoutResId, @IdRes int textViewId) {\n\t\tmTabViewLayoutId = layoutResId;\n\t\tmTabViewTextViewId = textViewId;\n\t}\n\n\tpublic void setTabListener(TabListener tabListener) {\n\t\tmTabListener = tabListener;\n\t}\n\n\t\/**\n\t * Sets the associated view pager. Note that the assumption here is that the pager content\n\t * (number of tabs and tab titles) does not change after this call has been made.\n\t *\/\n\tpublic void setViewPager(ViewPager viewPager) {\n\t\tmViewPager = viewPager;\n\t\tif (viewPager != null) {\n\t\t\tviewPager.addOnPageChangeListener(new InternalViewPagerListener());\n\t\t}\n\t\tnotifyDataSetChanged();\n\t}\n\n\tpublic void notifyDataSetChanged() {\n\t\tmTabStrip.removeAllViews();\n\t\tif (mViewPager != null) {\n\t\t\tpopulateTabStrip();\n\t\t}\n\t}\n\n\tprivate void populateTabStrip() {\n\t\tfinal PagerAdapter adapter = mViewPager.getAdapter();\n\t\tfinal int adapterCount = adapter.getCount();\n\t\tfinal View.OnClickListener tabClickListener = new TabClickListener();\n\t\tfinal LayoutInflater inflater = LayoutInflater.from(getContext());\n\t\tfinal int currentItem = mViewPager.getCurrentItem();\n\n\t\tfor (int i = 0; i < adapterCount; i++) {\n\t\t\tView tabView;\n\t\t\tTextView tabTitleView;\n\n\t\t\tif (mTabViewLayoutId != 0) {\n\t\t\t\t\/\/ If there is a custom tab view layout id set, try and inflate it\n\t\t\t\ttabView = inflater.inflate(mTabViewLayoutId, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);\n\t\t\t\tif (tabTitleView == null) {\n\t\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ Inflate our default tab layout\n\t\t\t\ttabView = inflater.inflate(R.layout.widget_sliding_tab_layout_text, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\tif (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {\n\t\t\t\t\t\/\/ Emulate Roboto Medium in previous Android versions\n\t\t\t\t\ttabTitleView.setTypeface(Typeface.DEFAULT_BOLD);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (mTextColor != null) {\n\t\t\t\ttabTitleView.setTextColor(mTextColor);\n\t\t\t}\n\n\t\t\tif (mDistributeEvenly) {\n\t\t\t\tLinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();\n\t\t\t\tlp.width = 0;\n\t\t\t\tlp.weight = 1;\n\t\t\t}\n\n\t\t\ttabTitleView.setText(adapter.getPageTitle(i));\n\t\t\ttabView.setFocusable(true);\n\t\t\ttabView.setOnClickListener(tabClickListener);\n\n\t\t\tmTabStrip.addView(tabView);\n\t\t\tif (i == currentItem) {\n\t\t\t\ttabView.setSelected(true);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tprotected void onAttachedToWindow() {\n\t\tsuper.onAttachedToWindow();\n\n\t\tif (mViewPager != null) {\n\t\t\tscrollToTab(mViewPager.getCurrentItem(), 0);\n\t\t}\n\t}\n\n\tprivate void scrollToTab(int tabIndex, float positionOffset) {\n\t\tfinal int tabStripChildCount = mTabStrip.getChildCount();\n\t\tif (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {\n\t\t\treturn;\n\t\t}\n\n\t\tView selectedChild = mTabStrip.getChildAt(tabIndex);\n\t\tif (selectedChild != null) {\n\t\t\tint targetScrollX = selectedChild.getLeft() +\n\t\t\t\t\tMath.round(positionOffset * selectedChild.getWidth()) - mTitleOffset;\n\n\t\t\tscrollTo(targetScrollX, 0);\n\t\t}\n\t}\n\n\tprivate class InternalViewPagerListener implements ViewPager.OnPageChangeListener {\n\t\tprivate int mScrollState;\n\n\t\t@Override\n\t\tpublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n\t\t\tint tabStripChildCount = mTabStrip.getChildCount();\n\t\t\tif ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tmTabStrip.onViewPagerPageChanged(position, positionOffset);\n\n\n\t\t\tscrollToTab(position, positionOffset);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageScrollStateChanged(int state) {\n\t\t\tmScrollState = state;\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageSelected(int position) {\n\t\t\tif (mScrollState == ViewPager.SCROLL_STATE_IDLE) {\n\t\t\t\tmTabStrip.onViewPagerPageChanged(position, 0f);\n\t\t\t\tscrollToTab(position, 0);\n\t\t\t}\n\t\t\tfinal int childCount = mTabStrip.getChildCount();\n\t\t\tfor (int i = 0; i < childCount; i++) {\n\t\t\t\tmTabStrip.getChildAt(i).setSelected(position == i);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate class TabClickListener implements View.OnClickListener {\n\t\t@Override\n\t\tpublic void onClick(View v) {\n\t\t\tfinal int childCount = mTabStrip.getChildCount();\n\t\t\tfor (int i = 0; i < childCount; i++) {\n\t\t\t\tif (v == mTabStrip.getChildAt(i)) {\n\t\t\t\t\tfinal int previousPos = mViewPager.getCurrentItem();\n\t\t\t\t\tmViewPager.setCurrentItem(i);\n\n\t\t\t\t\tif (mTabListener != null) {\n\t\t\t\t\t\tif (previousPos != i) {\n\t\t\t\t\t\t\tmTabListener.onTabSelected(i);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tmTabListener.onTabReSelected(i);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nCode-B:\n\/*\n * Copyright 2014 Chris Banes\n * Copyright 2016 Christophe Beyls\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage com.example.android.common.view;\n\nimport android.content.Context;\nimport android.content.res.ColorStateList;\nimport android.content.res.TypedArray;\nimport android.graphics.Typeface;\nimport android.os.Build;\nimport android.support.annotation.ColorInt;\nimport android.support.annotation.IdRes;\nimport android.support.annotation.LayoutRes;\nimport android.support.v4.view.PagerAdapter;\nimport android.support.v4.view.ViewPager;\nimport android.util.AttributeSet;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.widget.HorizontalScrollView;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\n\nimport be.digitalia.fosdem.R;\n\n\/**\n *\/\npublic class SlidingTabLayout extends HorizontalScrollView {\n\n\tpublic interface TabListener {\n\n\t\tvoid onTabSelected(int pos);\n\n\t\tvoid onTabReSelected(int pos);\n\n\t}\n\n\tprivate static final int[][] TAB_COLOR_STATES = new int[][]{SELECTED_STATE_SET, EMPTY_STATE_SET};\n\n\tprivate int mTitleOffset;\n\n\tprivate int mTabViewLayoutId;\n\tprivate int mTabViewTextViewId;\n\tprivate boolean mDistributeEvenly;\n\n\tprivate ColorStateList mTextColor;\n\n\tprivate ViewPager mViewPager;\n\n\tprivate TabListener mTabListener;\n\n\tprivate final SlidingTabStrip mTabStrip;\n\n\tpublic SlidingTabLayout(Context context) {\n\t\tthis(context, null);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs) {\n\t\tthis(context, attrs, 0);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {\n\t\tsuper(context, attrs, defStyle);\n\n\t\t\/\/ Disable the Scroll Bar\n\t\tsetHorizontalScrollBarEnabled(false);\n\t\t\/\/ Make sure that the Tab Strips fills this View\n\t\tsetFillViewport(true);\n\n\t\tmTabStrip = new SlidingTabStrip(context);\n\t\taddView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);\n\n\t\tTypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SlidingTabLayout,\n\t\t\t\tdefStyle, R.style.SlidingTabLayout);\n\n\t\tmTabStrip.setSelectedIndicatorHeight(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_indicatorHeight, 0));\n\t\tmTabStrip.setSelectedIndicatorColor(a.getColor(R.styleable.SlidingTabLayout_indicatorColor, 0));\n\t\tmTextColor = a.getColorStateList(R.styleable.SlidingTabLayout_textColor);\n\t\tif ((mTextColor != null) && a.hasValue(R.styleable.SlidingTabLayout_selectedTextColor)) {\n\t\t\tsetTabTextColors(mTextColor.getDefaultColor(), a.getColor(R.styleable.SlidingTabLayout_selectedTextColor, 0));\n\t\t}\n\t\tsetContentInsetStart(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_contentInsetStart, 0));\n\t\tsetDistributeEvenly(a.getBoolean(R.styleable.SlidingTabLayout_distributeEvenly, false));\n\n\t\ta.recycle();\n\t}\n\n\tpublic void setContentInsetStart(int offset) {\n\t\tmTitleOffset = offset;\n\t\tmTabStrip.setPadding(offset, 0, 0, 0);\n\t}\n\n\tpublic void setDistributeEvenly(boolean distributeEvenly) {\n\t\tmDistributeEvenly = distributeEvenly;\n\t}\n\n\t\/**\n\t * Sets the color to be used for indicating the selected tab.\n\t * This will override the style color.\n\t *\/\n\tpublic void setSelectedTabIndicatorColor(@ColorInt int color) {\n\t\tmTabStrip.setSelectedIndicatorColor(color);\n\t}\n\n\tpublic void setSelectedTabIndicatorHeight(int height) {\n\t\tmTabStrip.setSelectedIndicatorHeight(height);\n\t}\n\n\tpublic void setTabTextColors(ColorStateList color) {\n\t\tmTextColor = color;\n\t}\n\n\tpublic void setTabTextColors(@ColorInt int normalColor, @ColorInt int selectedColor) {\n\t\tmTextColor = createColorStateList(normalColor, selectedColor);\n\t}\n\n\tprivate static ColorStateList createColorStateList(int defaultColor, int selectedColor) {\n\t\tfinal int[] colors = new int[]{selectedColor, defaultColor};\n\t\treturn new ColorStateList(TAB_COLOR_STATES, colors);\n\t}\n\n\t\/**\n\t * Set the custom layout to be inflated for the tab views.\n\t *\n\t * @param layoutResId Layout id to be inflated\n\t * @param textViewId id of the {@link TextView} in the inflated view\n\t *\/\n\tpublic void setCustomTabView(@LayoutRes int layoutResId, @IdRes int textViewId) {\n\t\tmTabViewLayoutId = layoutResId;\n\t\tmTabViewTextViewId = textViewId;\n\t}\n\n\tpublic void setTabListener(TabListener tabListener) {\n\t\tmTabListener = tabListener;\n\t}\n\n\t\/**\n\t * Sets the associated view pager. Note that the assumption here is that the pager content\n\t * (number of tabs and tab titles) does not change after this call has been made.\n\t *\/\n\tpublic void setViewPager(ViewPager viewPager) {\n\t\tmViewPager = viewPager;\n\t\tif (viewPager != null) {\n\t\t\tviewPager.addOnPageChangeListener(new InternalViewPagerListener());\n\t\t}\n\t\tnotifyDataSetChanged();\n\t}\n\n\tpublic void notifyDataSetChanged() {\n\t\tmTabStrip.removeAllViews();\n\t\tif (mViewPager != null) {\n\t\t\tpopulateTabStrip();\n\t\t}\n\t}\n\n\tprivate void populateTabStrip() {\n\t\tfinal PagerAdapter adapter = mViewPager.getAdapter();\n\t\tfinal View.OnClickListener tabClickListener = new TabClickListener();\n\t\tfinal LayoutInflater inflater = LayoutInflater.from(getContext());\n\t\tfinal int currentItem = mViewPager.getCurrentItem();\n\n\t\tfor (int i = 0; i < adapter.getCount(); i++) {\n\t\t\tView tabView;\n\t\t\tTextView tabTitleView;\n\n\t\t\tif (mTabViewLayoutId != 0) {\n\t\t\t\t\/\/ If there is a custom tab view layout id set, try and inflate it\n\t\t\t\ttabView = inflater.inflate(mTabViewLayoutId, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);\n\t\t\t\tif (tabTitleView == null) {\n\t\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ Inflate our default tab layout\n\t\t\t\ttabView = inflater.inflate(R.layout.widget_sliding_tab_layout_text, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\tif (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {\n\t\t\t\t\t\/\/ Emulate Roboto Medium in previous Android versions\n\t\t\t\t\ttabTitleView.setTypeface(Typeface.DEFAULT_BOLD);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (mTextColor != null) {\n\t\t\t\ttabTitleView.setTextColor(mTextColor);\n\t\t\t}\n\n\t\t\tif (mDistributeEvenly) {\n\t\t\t\tLinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();\n\t\t\t\tlp.width = 0;\n\t\t\t\tlp.weight = 1;\n\t\t\t}\n\n\t\t\ttabTitleView.setText(adapter.getPageTitle(i));\n\t\t\ttabView.setFocusable(true);\n\t\t\ttabView.setOnClickListener(tabClickListener);\n\n\t\t\tmTabStrip.addView(tabView);\n\t\t\tif (i == currentItem) {\n\t\t\t\ttabView.setSelected(true);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tprotected void onAttachedToWindow() {\n\t\tsuper.onAttachedToWindow();\n\n\t\tif (mViewPager != null) {\n\t\t\tscrollToTab(mViewPager.getCurrentItem(), 0);\n\t\t}\n\t}\n\n\tprivate void scrollToTab(int tabIndex, float positionOffset) {\n\t\tfinal int tabStripChildCount = mTabStrip.getChildCount();\n\t\tif (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {\n\t\t\treturn;\n\t\t}\n\n\t\tView selectedChild = mTabStrip.getChildAt(tabIndex);\n\t\tif (selectedChild != null) {\n\t\t\tint targetScrollX = selectedChild.getLeft() +\n\t\t\t\t\tMath.round(positionOffset * selectedChild.getWidth()) - mTitleOffset;\n\n\t\t\tscrollTo(targetScrollX, 0);\n\t\t}\n\t}\n\n\tprivate class InternalViewPagerListener implements ViewPager.OnPageChangeListener {\n\t\tprivate int mScrollState;\n\n\t\t@Override\n\t\tpublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n\t\t\tint tabStripChildCount = mTabStrip.getChildCount();\n\t\t\tif ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tmTabStrip.onViewPagerPageChanged(position, positionOffset);\n\n\n\t\t\tscrollToTab(position, positionOffset);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageScrollStateChanged(int state) {\n\t\t\tmScrollState = state;\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageSelected(int position) {\n\t\t\tif (mScrollState == ViewPager.SCROLL_STATE_IDLE) {\n\t\t\t\tmTabStrip.onViewPagerPageChanged(position, 0f);\n\t\t\t\tscrollToTab(position, 0);\n\t\t\t}\n\t\t\tfor (int i = 0; i < mTabStrip.getChildCount(); i++) {\n\t\t\t\tmTabStrip.getChildAt(i).setSelected(position == i);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate class TabClickListener implements View.OnClickListener {\n\t\t@Override\n\t\tpublic void onClick(View v) {\n\t\t\tfor (int i = 0; i < mTabStrip.getChildCount(); i++) {\n\t\t\t\tif (v == mTabStrip.getChildAt(i)) {\n\t\t\t\t\tfinal int previousPos = mViewPager.getCurrentItem();\n\t\t\t\t\tmViewPager.setCurrentItem(i);\n\n\t\t\t\t\tif (mTabListener != null) {\n\t\t\t\t\t\tif (previousPos != i) {\n\t\t\t\t\t\t\tmTabListener.onTabSelected(i);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tmTabListener.onTabReSelected(i);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/*\n * Copyright 2014 Chris Banes\n * Copyright 2016 Christophe Beyls\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage com.example.android.common.view;\n\nimport android.content.Context;\nimport android.content.res.ColorStateList;\nimport android.content.res.TypedArray;\nimport android.graphics.Typeface;\nimport android.os.Build;\nimport android.support.annotation.ColorInt;\nimport android.support.annotation.IdRes;\nimport android.support.annotation.LayoutRes;\nimport android.support.v4.view.PagerAdapter;\nimport android.support.v4.view.ViewPager;\nimport android.util.AttributeSet;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.widget.HorizontalScrollView;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\n\nimport be.digitalia.fosdem.R;\n\n\/**\n *\/\npublic class SlidingTabLayout extends HorizontalScrollView {\n\n\tpublic interface TabListener {\n\n\t\tvoid onTabSelected(int pos);\n\n\t\tvoid onTabReSelected(int pos);\n\n\t}\n\n\tprivate static final int[][] TAB_COLOR_STATES = new int[][]{SELECTED_STATE_SET, EMPTY_STATE_SET};\n\n\tprivate int mTitleOffset;\n\n\tprivate int mTabViewLayoutId;\n\tprivate int mTabViewTextViewId;\n\tprivate boolean mDistributeEvenly;\n\n\tprivate ColorStateList mTextColor;\n\n\tprivate ViewPager mViewPager;\n\n\tprivate TabListener mTabListener;\n\n\tprivate final SlidingTabStrip mTabStrip;\n\n\tpublic SlidingTabLayout(Context context) {\n\t\tthis(context, null);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs) {\n\t\tthis(context, attrs, 0);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {\n\t\tsuper(context, attrs, defStyle);\n\n\t\t\/\/ Disable the Scroll Bar\n\t\tsetHorizontalScrollBarEnabled(false);\n\t\t\/\/ Make sure that the Tab Strips fills this View\n\t\tsetFillViewport(true);\n\n\t\tmTabStrip = new SlidingTabStrip(context);\n\t\taddView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);\n\n\t\tTypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SlidingTabLayout,\n\t\t\t\tdefStyle, R.style.SlidingTabLayout);\n\n\t\tmTabStrip.setSelectedIndicatorHeight(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_indicatorHeight, 0));\n\t\tmTabStrip.setSelectedIndicatorColor(a.getColor(R.styleable.SlidingTabLayout_indicatorColor, 0));\n\t\tmTextColor = a.getColorStateList(R.styleable.SlidingTabLayout_textColor);\n\t\tif ((mTextColor != null) && a.hasValue(R.styleable.SlidingTabLayout_selectedTextColor)) {\n\t\t\tsetTabTextColors(mTextColor.getDefaultColor(), a.getColor(R.styleable.SlidingTabLayout_selectedTextColor, 0));\n\t\t}\n\t\tsetContentInsetStart(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_contentInsetStart, 0));\n\t\tsetDistributeEvenly(a.getBoolean(R.styleable.SlidingTabLayout_distributeEvenly, false));\n\n\t\ta.recycle();\n\t}\n\n\tpublic void setContentInsetStart(int offset) {\n\t\tmTitleOffset = offset;\n\t\tmTabStrip.setPadding(offset, 0, 0, 0);\n\t}\n\n\tpublic void setDistributeEvenly(boolean distributeEvenly) {\n\t\tmDistributeEvenly = distributeEvenly;\n\t}\n\n\t\/**\n\t * Sets the color to be used for indicating the selected tab.\n\t * This will override the style color.\n\t *\/\n\tpublic void setSelectedTabIndicatorColor(@ColorInt int color) {\n\t\tmTabStrip.setSelectedIndicatorColor(color);\n\t}\n\n\tpublic void setSelectedTabIndicatorHeight(int height) {\n\t\tmTabStrip.setSelectedIndicatorHeight(height);\n\t}\n\n\tpublic void setTabTextColors(ColorStateList color) {\n\t\tmTextColor = color;\n\t}\n\n\tpublic void setTabTextColors(@ColorInt int normalColor, @ColorInt int selectedColor) {\n\t\tmTextColor = createColorStateList(normalColor, selectedColor);\n\t}\n\n\tprivate static ColorStateList createColorStateList(int defaultColor, int selectedColor) {\n\t\tfinal int[] colors = new int[]{selectedColor, defaultColor};\n\t\treturn new ColorStateList(TAB_COLOR_STATES, colors);\n\t}\n\n\t\/**\n\t * Set the custom layout to be inflated for the tab views.\n\t *\n\t * @param layoutResId Layout id to be inflated\n\t * @param textViewId id of the {@link TextView} in the inflated view\n\t *\/\n\tpublic void setCustomTabView(@LayoutRes int layoutResId, @IdRes int textViewId) {\n\t\tmTabViewLayoutId = layoutResId;\n\t\tmTabViewTextViewId = textViewId;\n\t}\n\n\tpublic void setTabListener(TabListener tabListener) {\n\t\tmTabListener = tabListener;\n\t}\n\n\t\/**\n\t * Sets the associated view pager. Note that the assumption here is that the pager content\n\t * (number of tabs and tab titles) does not change after this call has been made.\n\t *\/\n\tpublic void setViewPager(ViewPager viewPager) {\n\t\tmViewPager = viewPager;\n\t\tif (viewPager != null) {\n\t\t\tviewPager.addOnPageChangeListener(new InternalViewPagerListener());\n\t\t}\n\t\tnotifyDataSetChanged();\n\t}\n\n\tpublic void notifyDataSetChanged() {\n\t\tmTabStrip.removeAllViews();\n\t\tif (mViewPager != null) {\n\t\t\tpopulateTabStrip();\n\t\t}\n\t}\n\n\tprivate void populateTabStrip() {\n\t\tfinal PagerAdapter adapter = mViewPager.getAdapter();\n\t\tfinal View.OnClickListener tabClickListener = new TabClickListener();\n\t\tfinal LayoutInflater inflater = LayoutInflater.from(getContext());\n\t\tfinal int currentItem = mViewPager.getCurrentItem();\n\n\t\tfor (int i = 0; i < adapter.getCount(); i++) {\n\t\t\tView tabView;\n\t\t\tTextView tabTitleView;\n\n\t\t\tif (mTabViewLayoutId != 0) {\n\t\t\t\t\/\/ If there is a custom tab view layout id set, try and inflate it\n\t\t\t\ttabView = inflater.inflate(mTabViewLayoutId, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);\n\t\t\t\tif (tabTitleView == null) {\n\t\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ Inflate our default tab layout\n\t\t\t\ttabView = inflater.inflate(R.layout.widget_sliding_tab_layout_text, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\tif (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {\n\t\t\t\t\t\/\/ Emulate Roboto Medium in previous Android versions\n\t\t\t\t\ttabTitleView.setTypeface(Typeface.DEFAULT_BOLD);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (mTextColor != null) {\n\t\t\t\ttabTitleView.setTextColor(mTextColor);\n\t\t\t}\n\n\t\t\tif (mDistributeEvenly) {\n\t\t\t\tLinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();\n\t\t\t\tlp.width = 0;\n\t\t\t\tlp.weight = 1;\n\t\t\t}\n\n\t\t\ttabTitleView.setText(adapter.getPageTitle(i));\n\t\t\ttabView.setFocusable(true);\n\t\t\ttabView.setOnClickListener(tabClickListener);\n\n\t\t\tmTabStrip.addView(tabView);\n\t\t\tif (i == currentItem) {\n\t\t\t\ttabView.setSelected(true);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tprotected void onAttachedToWindow() {\n\t\tsuper.onAttachedToWindow();\n\n\t\tif (mViewPager != null) {\n\t\t\tscrollToTab(mViewPager.getCurrentItem(), 0);\n\t\t}\n\t}\n\n\tprivate void scrollToTab(int tabIndex, float positionOffset) {\n\t\tfinal int tabStripChildCount = mTabStrip.getChildCount();\n\t\tif (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {\n\t\t\treturn;\n\t\t}\n\n\t\tView selectedChild = mTabStrip.getChildAt(tabIndex);\n\t\tif (selectedChild != null) {\n\t\t\tint targetScrollX = selectedChild.getLeft() +\n\t\t\t\t\tMath.round(positionOffset * selectedChild.getWidth()) - mTitleOffset;\n\n\t\t\tscrollTo(targetScrollX, 0);\n\t\t}\n\t}\n\n\tprivate class InternalViewPagerListener implements ViewPager.OnPageChangeListener {\n\t\tprivate int mScrollState;\n\n\t\t@Override\n\t\tpublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n\t\t\tint tabStripChildCount = mTabStrip.getChildCount();\n\t\t\tif ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tmTabStrip.onViewPagerPageChanged(position, positionOffset);\n\n\n\t\t\tscrollToTab(position, positionOffset);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageScrollStateChanged(int state) {\n\t\t\tmScrollState = state;\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageSelected(int position) {\n\t\t\tif (mScrollState == ViewPager.SCROLL_STATE_IDLE) {\n\t\t\t\tmTabStrip.onViewPagerPageChanged(position, 0f);\n\t\t\t\tscrollToTab(position, 0);\n\t\t\t}\n\t\t\tfor (int i = 0; i < mTabStrip.getChildCount(); i++) {\n\t\t\t\tmTabStrip.getChildAt(i).setSelected(position == i);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate class TabClickListener implements View.OnClickListener {\n\t\t@Override\n\t\tpublic void onClick(View v) {\n\t\t\tfor (int i = 0; i < mTabStrip.getChildCount(); i++) {\n\t\t\t\tif (v == mTabStrip.getChildAt(i)) {\n\t\t\t\t\tfinal int previousPos = mViewPager.getCurrentItem();\n\t\t\t\t\tmViewPager.setCurrentItem(i);\n\n\t\t\t\t\tif (mTabListener != null) {\n\t\t\t\t\t\tif (previousPos != i) {\n\t\t\t\t\t\t\tmTabListener.onTabSelected(i);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tmTabListener.onTabReSelected(i);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nCode-B:\n\/*\n * Copyright 2014 Chris Banes\n * Copyright 2016 Christophe Beyls\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage com.example.android.common.view;\n\nimport android.content.Context;\nimport android.content.res.ColorStateList;\nimport android.content.res.TypedArray;\nimport android.graphics.Typeface;\nimport android.os.Build;\nimport android.support.annotation.ColorInt;\nimport android.support.annotation.IdRes;\nimport android.support.annotation.LayoutRes;\nimport android.support.v4.view.PagerAdapter;\nimport android.support.v4.view.ViewPager;\nimport android.util.AttributeSet;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.widget.HorizontalScrollView;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\n\nimport be.digitalia.fosdem.R;\n\n\/**\n *\/\npublic class SlidingTabLayout extends HorizontalScrollView {\n\n\tpublic interface TabListener {\n\n\t\tvoid onTabSelected(int pos);\n\n\t\tvoid onTabReSelected(int pos);\n\n\t}\n\n\tprivate static final int[][] TAB_COLOR_STATES = new int[][]{SELECTED_STATE_SET, EMPTY_STATE_SET};\n\n\tprivate int mTitleOffset;\n\n\tprivate int mTabViewLayoutId;\n\tprivate int mTabViewTextViewId;\n\tprivate boolean mDistributeEvenly;\n\n\tprivate ColorStateList mTextColor;\n\n\tprivate ViewPager mViewPager;\n\n\tprivate TabListener mTabListener;\n\n\tprivate final SlidingTabStrip mTabStrip;\n\n\tpublic SlidingTabLayout(Context context) {\n\t\tthis(context, null);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs) {\n\t\tthis(context, attrs, 0);\n\t}\n\n\tpublic SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {\n\t\tsuper(context, attrs, defStyle);\n\n\t\t\/\/ Disable the Scroll Bar\n\t\tsetHorizontalScrollBarEnabled(false);\n\t\t\/\/ Make sure that the Tab Strips fills this View\n\t\tsetFillViewport(true);\n\n\t\tmTabStrip = new SlidingTabStrip(context);\n\t\taddView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);\n\n\t\tTypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SlidingTabLayout,\n\t\t\t\tdefStyle, R.style.SlidingTabLayout);\n\n\t\tmTabStrip.setSelectedIndicatorHeight(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_indicatorHeight, 0));\n\t\tmTabStrip.setSelectedIndicatorColor(a.getColor(R.styleable.SlidingTabLayout_indicatorColor, 0));\n\t\tmTextColor = a.getColorStateList(R.styleable.SlidingTabLayout_textColor);\n\t\tif ((mTextColor != null) && a.hasValue(R.styleable.SlidingTabLayout_selectedTextColor)) {\n\t\t\tsetTabTextColors(mTextColor.getDefaultColor(), a.getColor(R.styleable.SlidingTabLayout_selectedTextColor, 0));\n\t\t}\n\t\tsetContentInsetStart(a.getDimensionPixelSize(R.styleable.SlidingTabLayout_contentInsetStart, 0));\n\t\tsetDistributeEvenly(a.getBoolean(R.styleable.SlidingTabLayout_distributeEvenly, false));\n\n\t\ta.recycle();\n\t}\n\n\tpublic void setContentInsetStart(int offset) {\n\t\tmTitleOffset = offset;\n\t\tmTabStrip.setPadding(offset, 0, 0, 0);\n\t}\n\n\tpublic void setDistributeEvenly(boolean distributeEvenly) {\n\t\tmDistributeEvenly = distributeEvenly;\n\t}\n\n\t\/**\n\t * Sets the color to be used for indicating the selected tab.\n\t * This will override the style color.\n\t *\/\n\tpublic void setSelectedTabIndicatorColor(@ColorInt int color) {\n\t\tmTabStrip.setSelectedIndicatorColor(color);\n\t}\n\n\tpublic void setSelectedTabIndicatorHeight(int height) {\n\t\tmTabStrip.setSelectedIndicatorHeight(height);\n\t}\n\n\tpublic void setTabTextColors(ColorStateList color) {\n\t\tmTextColor = color;\n\t}\n\n\tpublic void setTabTextColors(@ColorInt int normalColor, @ColorInt int selectedColor) {\n\t\tmTextColor = createColorStateList(normalColor, selectedColor);\n\t}\n\n\tprivate static ColorStateList createColorStateList(int defaultColor, int selectedColor) {\n\t\tfinal int[] colors = new int[]{selectedColor, defaultColor};\n\t\treturn new ColorStateList(TAB_COLOR_STATES, colors);\n\t}\n\n\t\/**\n\t * Set the custom layout to be inflated for the tab views.\n\t *\n\t * @param layoutResId Layout id to be inflated\n\t * @param textViewId id of the {@link TextView} in the inflated view\n\t *\/\n\tpublic void setCustomTabView(@LayoutRes int layoutResId, @IdRes int textViewId) {\n\t\tmTabViewLayoutId = layoutResId;\n\t\tmTabViewTextViewId = textViewId;\n\t}\n\n\tpublic void setTabListener(TabListener tabListener) {\n\t\tmTabListener = tabListener;\n\t}\n\n\t\/**\n\t * Sets the associated view pager. Note that the assumption here is that the pager content\n\t * (number of tabs and tab titles) does not change after this call has been made.\n\t *\/\n\tpublic void setViewPager(ViewPager viewPager) {\n\t\tmViewPager = viewPager;\n\t\tif (viewPager != null) {\n\t\t\tviewPager.addOnPageChangeListener(new InternalViewPagerListener());\n\t\t}\n\t\tnotifyDataSetChanged();\n\t}\n\n\tpublic void notifyDataSetChanged() {\n\t\tmTabStrip.removeAllViews();\n\t\tif (mViewPager != null) {\n\t\t\tpopulateTabStrip();\n\t\t}\n\t}\n\n\tprivate void populateTabStrip() {\n\t\tfinal PagerAdapter adapter = mViewPager.getAdapter();\n\t\tfinal int adapterCount = adapter.getCount();\n\t\tfinal View.OnClickListener tabClickListener = new TabClickListener();\n\t\tfinal LayoutInflater inflater = LayoutInflater.from(getContext());\n\t\tfinal int currentItem = mViewPager.getCurrentItem();\n\n\t\tfor (int i = 0; i < adapterCount; i++) {\n\t\t\tView tabView;\n\t\t\tTextView tabTitleView;\n\n\t\t\tif (mTabViewLayoutId != 0) {\n\t\t\t\t\/\/ If there is a custom tab view layout id set, try and inflate it\n\t\t\t\ttabView = inflater.inflate(mTabViewLayoutId, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);\n\t\t\t\tif (tabTitleView == null) {\n\t\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ Inflate our default tab layout\n\t\t\t\ttabView = inflater.inflate(R.layout.widget_sliding_tab_layout_text, mTabStrip, false);\n\t\t\t\ttabTitleView = (TextView) tabView;\n\t\t\t\tif (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {\n\t\t\t\t\t\/\/ Emulate Roboto Medium in previous Android versions\n\t\t\t\t\ttabTitleView.setTypeface(Typeface.DEFAULT_BOLD);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (mTextColor != null) {\n\t\t\t\ttabTitleView.setTextColor(mTextColor);\n\t\t\t}\n\n\t\t\tif (mDistributeEvenly) {\n\t\t\t\tLinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();\n\t\t\t\tlp.width = 0;\n\t\t\t\tlp.weight = 1;\n\t\t\t}\n\n\t\t\ttabTitleView.setText(adapter.getPageTitle(i));\n\t\t\ttabView.setFocusable(true);\n\t\t\ttabView.setOnClickListener(tabClickListener);\n\n\t\t\tmTabStrip.addView(tabView);\n\t\t\tif (i == currentItem) {\n\t\t\t\ttabView.setSelected(true);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tprotected void onAttachedToWindow() {\n\t\tsuper.onAttachedToWindow();\n\n\t\tif (mViewPager != null) {\n\t\t\tscrollToTab(mViewPager.getCurrentItem(), 0);\n\t\t}\n\t}\n\n\tprivate void scrollToTab(int tabIndex, float positionOffset) {\n\t\tfinal int tabStripChildCount = mTabStrip.getChildCount();\n\t\tif (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {\n\t\t\treturn;\n\t\t}\n\n\t\tView selectedChild = mTabStrip.getChildAt(tabIndex);\n\t\tif (selectedChild != null) {\n\t\t\tint targetScrollX = selectedChild.getLeft() +\n\t\t\t\t\tMath.round(positionOffset * selectedChild.getWidth()) - mTitleOffset;\n\n\t\t\tscrollTo(targetScrollX, 0);\n\t\t}\n\t}\n\n\tprivate class InternalViewPagerListener implements ViewPager.OnPageChangeListener {\n\t\tprivate int mScrollState;\n\n\t\t@Override\n\t\tpublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n\t\t\tint tabStripChildCount = mTabStrip.getChildCount();\n\t\t\tif ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tmTabStrip.onViewPagerPageChanged(position, positionOffset);\n\n\n\t\t\tscrollToTab(position, positionOffset);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageScrollStateChanged(int state) {\n\t\t\tmScrollState = state;\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageSelected(int position) {\n\t\t\tif (mScrollState == ViewPager.SCROLL_STATE_IDLE) {\n\t\t\t\tmTabStrip.onViewPagerPageChanged(position, 0f);\n\t\t\t\tscrollToTab(position, 0);\n\t\t\t}\n\t\t\tfinal int childCount = mTabStrip.getChildCount();\n\t\t\tfor (int i = 0; i < childCount; i++) {\n\t\t\t\tmTabStrip.getChildAt(i).setSelected(position == i);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate class TabClickListener implements View.OnClickListener {\n\t\t@Override\n\t\tpublic void onClick(View v) {\n\t\t\tfinal int childCount = mTabStrip.getChildCount();\n\t\t\tfor (int i = 0; i < childCount; i++) {\n\t\t\t\tif (v == mTabStrip.getChildAt(i)) {\n\t\t\t\t\tfinal int previousPos = mViewPager.getCurrentItem();\n\t\t\t\t\tmViewPager.setCurrentItem(i);\n\n\t\t\t\t\tif (mTabListener != null) {\n\t\t\t\t\t\tif (previousPos != i) {\n\t\t\t\t\t\t\tmTabListener.onTabSelected(i);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tmTabListener.onTabReSelected(i);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/aaronjwood\/PortAuthority\/commit\/c8ff3a269fadad26c311a3a71b6da65a644a4176","commit_message":"'\\\\\"More optimizations\\\\n\\\\\"'","source_code":"package com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.ProgressDialog;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.net.NetworkInfo;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.Button;\nimport android.widget.ListAdapter;\nimport android.widget.ListView;\nimport android.widget.SimpleAdapter;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Discovery;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class MainActivity extends Activity implements MainAsyncResponse {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n private Discovery discovery = new Discovery();\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView internalIp;\n private TextView externalIp;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n private ProgressDialog scanProgressDialog;\n private Handler mHandler = new Handler();\n private BroadcastReceiver receiver;\n private IntentFilter intentFilter = new IntentFilter();\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.internalIp = (TextView) findViewById(R.id.internalIpAddress);\n this.externalIp = (TextView) findViewById(R.id.externalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n this.wifi = new Wireless(this);\n\n this.macAddress.setText(this.wifi.getMacAddress());\n\n this.receiver = new BroadcastReceiver() {\n\n \/**\n * Detect if a network connection has been lost or established\n * @param context\n * @param intent\n *\/\n @Override\n public void onReceive(Context context, Intent intent) {\n NetworkInfo info = intent.getParcelableExtra(wifi.getWifiManager().EXTRA_NETWORK_INFO);\n if(info != null) {\n if(info.isConnected()) {\n getNetworkInfo();\n }\n else {\n mHandler.removeCallbacksAndMessages(null);\n MainActivity.this.internalIp.setText(\"No WiFi connection\");\n externalIp.setText(\"No WiFi connection\");\n signalStrength.setText(\"No WiFi connection\");\n ssid.setText(\"No WiFi connection\");\n bssid.setText(\"No WiFi connection\");\n }\n }\n }\n };\n\n this.intentFilter.addAction(this.wifi.getWifiManager().NETWORK_STATE_CHANGED_ACTION);\n registerReceiver(receiver, this.intentFilter);\n\n this.discoverHosts.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler to perform host discovery\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n scanProgressDialog = new ProgressDialog(MainActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning For Hosts\");\n scanProgressDialog.setProgressStyle(scanProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(255);\n scanProgressDialog.show();\n\n discovery.scanHosts(wifi.getInternalIpAddress(), MainActivity.this);\n }\n });\n\n this.hostList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open the host activity for a specific host found on the network\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n HashMap map = (HashMap) hostList.getItemAtPosition(position);\n Intent intent = new Intent(MainActivity.this, HostActivity.class);\n String firstLine = map.get(\"First Line\");\n String secondLine = map.get(\"Second Line\");\n String macAddress = map.get(\"Second Line\").substring(secondLine.indexOf(\"[\") + 1, secondLine.indexOf(\"]\"));\n\n intent.putExtra(\"HOST\", firstLine);\n intent.putExtra(\"MAC\", macAddress);\n startActivity(intent);\n }\n });\n\n }\n\n \/**\n * Gets network information about the device and updates various UI elements\n *\/\n private void getNetworkInfo() {\n this.mHandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n this.internalIp.setText(this.wifi.getInternalIpAddress());\n this.wifi.getExternalIpAddress(this);\n this.ssid.setText(this.wifi.getSSID());\n this.bssid.setText(this.wifi.getBSSID());\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n unregisterReceiver(this.receiver);\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n this.scanProgressDialog = null;\n }\n\n \/**\n * Activity restarted\n *\/\n @Override\n public void onRestart() {\n super.onRestart();\n\n registerReceiver(this.receiver, this.intentFilter);\n }\n\n \/**\n * Save the state of an activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n ListAdapter adapter = this.hostList.getAdapter();\n if(adapter != null) {\n ArrayList> adapterData = new ArrayList<>();\n for(int i = 0; i < adapter.getCount(); i++) {\n HashMap item = (HashMap) adapter.getItem(i);\n adapterData.add(item);\n }\n savedState.putSerializable(\"hosts\", adapterData);\n }\n }\n\n \/**\n * Activity state restored\n *\n * @param savedState Saved data from the saved state\n *\/\n @Override\n public void onRestoreInstanceState(Bundle savedState) {\n super.onRestoreInstanceState(savedState);\n\n ArrayList> hosts = (ArrayList) savedState.getSerializable(\"hosts\");\n if(hosts != null) {\n SimpleAdapter newAdapter = new SimpleAdapter(this, hosts, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n this.hostList.setAdapter(newAdapter);\n }\n }\n\n \/**\n * Delegate to update the host list and dismiss the progress dialog\n * Gets called when host discovery has finished\n *\n * @param output The list of hosts to bind to the list view\n *\/\n @Override\n public void processFinish(ArrayList> output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n SimpleAdapter adapter = new SimpleAdapter(this, output, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n ListView hostList = (ListView) this.findViewById(R.id.hostList);\n hostList.setAdapter(adapter);\n this.scanProgressDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to update the progress of the host discovery scan\n *\n * @param output The amount of progress to increment by\n *\/\n @Override\n public void processFinish(int output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.incrementProgressBy(output);\n }\n }\n\n \/**\n * Delegate to handle setting the external IP in the UI\n *\n * @param output External IP\n *\/\n @Override\n public void processFinish(String output) {\n this.externalIp.setText(output);\n }\n}\n","target_code":"package com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.ProgressDialog;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.net.NetworkInfo;\nimport android.net.wifi.WifiManager;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.Button;\nimport android.widget.ListAdapter;\nimport android.widget.ListView;\nimport android.widget.SimpleAdapter;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Discovery;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class MainActivity extends Activity implements MainAsyncResponse {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n private Discovery discovery = new Discovery();\n private ListView hostList;\n private TextView internalIp;\n private TextView externalIp;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n private ProgressDialog scanProgressDialog;\n private Handler mHandler = new Handler();\n private BroadcastReceiver receiver;\n private IntentFilter intentFilter = new IntentFilter();\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n TextView macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.internalIp = (TextView) findViewById(R.id.internalIpAddress);\n this.externalIp = (TextView) findViewById(R.id.externalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n Button discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n this.wifi = new Wireless(this);\n\n macAddress.setText(this.wifi.getMacAddress());\n\n this.receiver = new BroadcastReceiver() {\n\n \/**\n * Detect if a network connection has been lost or established\n * @param context\n * @param intent\n *\/\n @Override\n public void onReceive(Context context, Intent intent) {\n NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);\n if(info != null) {\n if(info.isConnected()) {\n getNetworkInfo();\n }\n else {\n mHandler.removeCallbacksAndMessages(null);\n MainActivity.this.internalIp.setText(\"No WiFi connection\");\n externalIp.setText(\"No WiFi connection\");\n signalStrength.setText(\"No WiFi connection\");\n ssid.setText(\"No WiFi connection\");\n bssid.setText(\"No WiFi connection\");\n }\n }\n }\n };\n\n this.intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);\n registerReceiver(receiver, this.intentFilter);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler to perform host discovery\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n scanProgressDialog = new ProgressDialog(MainActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning For Hosts\");\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(255);\n scanProgressDialog.show();\n\n discovery.scanHosts(wifi.getInternalIpAddress(), MainActivity.this);\n }\n });\n\n this.hostList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open the host activity for a specific host found on the network\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n HashMap map = (HashMap) hostList.getItemAtPosition(position);\n Intent intent = new Intent(MainActivity.this, HostActivity.class);\n String firstLine = map.get(\"First Line\");\n String secondLine = map.get(\"Second Line\");\n String macAddress = map.get(\"Second Line\").substring(secondLine.indexOf(\"[\") + 1, secondLine.indexOf(\"]\"));\n\n intent.putExtra(\"HOST\", firstLine);\n intent.putExtra(\"MAC\", macAddress);\n startActivity(intent);\n }\n });\n\n }\n\n \/**\n * Gets network information about the device and updates various UI elements\n *\/\n private void getNetworkInfo() {\n this.mHandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n this.internalIp.setText(this.wifi.getInternalIpAddress());\n this.wifi.getExternalIpAddress(this);\n this.ssid.setText(this.wifi.getSSID());\n this.bssid.setText(this.wifi.getBSSID());\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n unregisterReceiver(this.receiver);\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n this.scanProgressDialog = null;\n }\n\n \/**\n * Activity restarted\n *\/\n @Override\n public void onRestart() {\n super.onRestart();\n\n registerReceiver(this.receiver, this.intentFilter);\n }\n\n \/**\n * Save the state of an activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n ListAdapter adapter = this.hostList.getAdapter();\n if(adapter != null) {\n ArrayList> adapterData = new ArrayList<>();\n for(int i = 0; i < adapter.getCount(); i++) {\n HashMap item = (HashMap) adapter.getItem(i);\n adapterData.add(item);\n }\n savedState.putSerializable(\"hosts\", adapterData);\n }\n }\n\n \/**\n * Activity state restored\n *\n * @param savedState Saved data from the saved state\n *\/\n @Override\n public void onRestoreInstanceState(Bundle savedState) {\n super.onRestoreInstanceState(savedState);\n\n ArrayList> hosts = (ArrayList) savedState.getSerializable(\"hosts\");\n if(hosts != null) {\n SimpleAdapter newAdapter = new SimpleAdapter(this, hosts, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n this.hostList.setAdapter(newAdapter);\n }\n }\n\n \/**\n * Delegate to update the host list and dismiss the progress dialog\n * Gets called when host discovery has finished\n *\n * @param output The list of hosts to bind to the list view\n *\/\n @Override\n public void processFinish(ArrayList> output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n SimpleAdapter adapter = new SimpleAdapter(this, output, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n ListView hostList = (ListView) this.findViewById(R.id.hostList);\n hostList.setAdapter(adapter);\n this.scanProgressDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to update the progress of the host discovery scan\n *\n * @param output The amount of progress to increment by\n *\/\n @Override\n public void processFinish(int output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.incrementProgressBy(output);\n }\n }\n\n \/**\n * Delegate to handle setting the external IP in the UI\n *\n * @param output External IP\n *\/\n @Override\n public void processFinish(String output) {\n this.externalIp.setText(output);\n }\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.ProgressDialog;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.net.NetworkInfo;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.Button;\nimport android.widget.ListAdapter;\nimport android.widget.ListView;\nimport android.widget.SimpleAdapter;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Discovery;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class MainActivity extends Activity implements MainAsyncResponse {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n private Discovery discovery = new Discovery();\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView internalIp;\n private TextView externalIp;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n private ProgressDialog scanProgressDialog;\n private Handler mHandler = new Handler();\n private BroadcastReceiver receiver;\n private IntentFilter intentFilter = new IntentFilter();\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.internalIp = (TextView) findViewById(R.id.internalIpAddress);\n this.externalIp = (TextView) findViewById(R.id.externalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n this.wifi = new Wireless(this);\n\n this.macAddress.setText(this.wifi.getMacAddress());\n\n this.receiver = new BroadcastReceiver() {\n\n \/**\n * Detect if a network connection has been lost or established\n * @param context\n * @param intent\n *\/\n @Override\n public void onReceive(Context context, Intent intent) {\n NetworkInfo info = intent.getParcelableExtra(wifi.getWifiManager().EXTRA_NETWORK_INFO);\n if(info != null) {\n if(info.isConnected()) {\n getNetworkInfo();\n }\n else {\n mHandler.removeCallbacksAndMessages(null);\n MainActivity.this.internalIp.setText(\"No WiFi connection\");\n externalIp.setText(\"No WiFi connection\");\n signalStrength.setText(\"No WiFi connection\");\n ssid.setText(\"No WiFi connection\");\n bssid.setText(\"No WiFi connection\");\n }\n }\n }\n };\n\n this.intentFilter.addAction(this.wifi.getWifiManager().NETWORK_STATE_CHANGED_ACTION);\n registerReceiver(receiver, this.intentFilter);\n\n this.discoverHosts.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler to perform host discovery\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n scanProgressDialog = new ProgressDialog(MainActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning For Hosts\");\n scanProgressDialog.setProgressStyle(scanProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(255);\n scanProgressDialog.show();\n\n discovery.scanHosts(wifi.getInternalIpAddress(), MainActivity.this);\n }\n });\n\n this.hostList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open the host activity for a specific host found on the network\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n HashMap map = (HashMap) hostList.getItemAtPosition(position);\n Intent intent = new Intent(MainActivity.this, HostActivity.class);\n String firstLine = map.get(\"First Line\");\n String secondLine = map.get(\"Second Line\");\n String macAddress = map.get(\"Second Line\").substring(secondLine.indexOf(\"[\") + 1, secondLine.indexOf(\"]\"));\n\n intent.putExtra(\"HOST\", firstLine);\n intent.putExtra(\"MAC\", macAddress);\n startActivity(intent);\n }\n });\n\n }\n\n \/**\n * Gets network information about the device and updates various UI elements\n *\/\n private void getNetworkInfo() {\n this.mHandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n this.internalIp.setText(this.wifi.getInternalIpAddress());\n this.wifi.getExternalIpAddress(this);\n this.ssid.setText(this.wifi.getSSID());\n this.bssid.setText(this.wifi.getBSSID());\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n unregisterReceiver(this.receiver);\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n this.scanProgressDialog = null;\n }\n\n \/**\n * Activity restarted\n *\/\n @Override\n public void onRestart() {\n super.onRestart();\n\n registerReceiver(this.receiver, this.intentFilter);\n }\n\n \/**\n * Save the state of an activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n ListAdapter adapter = this.hostList.getAdapter();\n if(adapter != null) {\n ArrayList> adapterData = new ArrayList<>();\n for(int i = 0; i < adapter.getCount(); i++) {\n HashMap item = (HashMap) adapter.getItem(i);\n adapterData.add(item);\n }\n savedState.putSerializable(\"hosts\", adapterData);\n }\n }\n\n \/**\n * Activity state restored\n *\n * @param savedState Saved data from the saved state\n *\/\n @Override\n public void onRestoreInstanceState(Bundle savedState) {\n super.onRestoreInstanceState(savedState);\n\n ArrayList> hosts = (ArrayList) savedState.getSerializable(\"hosts\");\n if(hosts != null) {\n SimpleAdapter newAdapter = new SimpleAdapter(this, hosts, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n this.hostList.setAdapter(newAdapter);\n }\n }\n\n \/**\n * Delegate to update the host list and dismiss the progress dialog\n * Gets called when host discovery has finished\n *\n * @param output The list of hosts to bind to the list view\n *\/\n @Override\n public void processFinish(ArrayList> output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n SimpleAdapter adapter = new SimpleAdapter(this, output, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n ListView hostList = (ListView) this.findViewById(R.id.hostList);\n hostList.setAdapter(adapter);\n this.scanProgressDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to update the progress of the host discovery scan\n *\n * @param output The amount of progress to increment by\n *\/\n @Override\n public void processFinish(int output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.incrementProgressBy(output);\n }\n }\n\n \/**\n * Delegate to handle setting the external IP in the UI\n *\n * @param output External IP\n *\/\n @Override\n public void processFinish(String output) {\n this.externalIp.setText(output);\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.ProgressDialog;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.net.NetworkInfo;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.Button;\nimport android.widget.ListAdapter;\nimport android.widget.ListView;\nimport android.widget.SimpleAdapter;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Discovery;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class MainActivity extends Activity implements MainAsyncResponse {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n private Discovery discovery = new Discovery();\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView internalIp;\n private TextView externalIp;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n private ProgressDialog scanProgressDialog;\n private Handler mHandler = new Handler();\n private BroadcastReceiver receiver;\n private IntentFilter intentFilter = new IntentFilter();\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.internalIp = (TextView) findViewById(R.id.internalIpAddress);\n this.externalIp = (TextView) findViewById(R.id.externalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n this.wifi = new Wireless(this);\n\n this.macAddress.setText(this.wifi.getMacAddress());\n\n this.receiver = new BroadcastReceiver() {\n\n \/**\n * Detect if a network connection has been lost or established\n * @param context\n * @param intent\n *\/\n @Override\n public void onReceive(Context context, Intent intent) {\n NetworkInfo info = intent.getParcelableExtra(wifi.getWifiManager().EXTRA_NETWORK_INFO);\n if(info != null) {\n if(info.isConnected()) {\n getNetworkInfo();\n }\n else {\n mHandler.removeCallbacksAndMessages(null);\n MainActivity.this.internalIp.setText(\"No WiFi connection\");\n externalIp.setText(\"No WiFi connection\");\n signalStrength.setText(\"No WiFi connection\");\n ssid.setText(\"No WiFi connection\");\n bssid.setText(\"No WiFi connection\");\n }\n }\n }\n };\n\n this.intentFilter.addAction(this.wifi.getWifiManager().NETWORK_STATE_CHANGED_ACTION);\n registerReceiver(receiver, this.intentFilter);\n\n this.discoverHosts.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler to perform host discovery\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n scanProgressDialog = new ProgressDialog(MainActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning For Hosts\");\n scanProgressDialog.setProgressStyle(scanProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(255);\n scanProgressDialog.show();\n\n discovery.scanHosts(wifi.getInternalIpAddress(), MainActivity.this);\n }\n });\n\n this.hostList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open the host activity for a specific host found on the network\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n HashMap map = (HashMap) hostList.getItemAtPosition(position);\n Intent intent = new Intent(MainActivity.this, HostActivity.class);\n String firstLine = map.get(\"First Line\");\n String secondLine = map.get(\"Second Line\");\n String macAddress = map.get(\"Second Line\").substring(secondLine.indexOf(\"[\") + 1, secondLine.indexOf(\"]\"));\n\n intent.putExtra(\"HOST\", firstLine);\n intent.putExtra(\"MAC\", macAddress);\n startActivity(intent);\n }\n });\n\n }\n\n \/**\n * Gets network information about the device and updates various UI elements\n *\/\n private void getNetworkInfo() {\n this.mHandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n this.internalIp.setText(this.wifi.getInternalIpAddress());\n this.wifi.getExternalIpAddress(this);\n this.ssid.setText(this.wifi.getSSID());\n this.bssid.setText(this.wifi.getBSSID());\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n unregisterReceiver(this.receiver);\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n this.scanProgressDialog = null;\n }\n\n \/**\n * Activity restarted\n *\/\n @Override\n public void onRestart() {\n super.onRestart();\n\n registerReceiver(this.receiver, this.intentFilter);\n }\n\n \/**\n * Save the state of an activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n ListAdapter adapter = this.hostList.getAdapter();\n if(adapter != null) {\n ArrayList> adapterData = new ArrayList<>();\n for(int i = 0; i < adapter.getCount(); i++) {\n HashMap item = (HashMap) adapter.getItem(i);\n adapterData.add(item);\n }\n savedState.putSerializable(\"hosts\", adapterData);\n }\n }\n\n \/**\n * Activity state restored\n *\n * @param savedState Saved data from the saved state\n *\/\n @Override\n public void onRestoreInstanceState(Bundle savedState) {\n super.onRestoreInstanceState(savedState);\n\n ArrayList> hosts = (ArrayList) savedState.getSerializable(\"hosts\");\n if(hosts != null) {\n SimpleAdapter newAdapter = new SimpleAdapter(this, hosts, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n this.hostList.setAdapter(newAdapter);\n }\n }\n\n \/**\n * Delegate to update the host list and dismiss the progress dialog\n * Gets called when host discovery has finished\n *\n * @param output The list of hosts to bind to the list view\n *\/\n @Override\n public void processFinish(ArrayList> output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n SimpleAdapter adapter = new SimpleAdapter(this, output, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n ListView hostList = (ListView) this.findViewById(R.id.hostList);\n hostList.setAdapter(adapter);\n this.scanProgressDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to update the progress of the host discovery scan\n *\n * @param output The amount of progress to increment by\n *\/\n @Override\n public void processFinish(int output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.incrementProgressBy(output);\n }\n }\n\n \/**\n * Delegate to handle setting the external IP in the UI\n *\n * @param output External IP\n *\/\n @Override\n public void processFinish(String output) {\n this.externalIp.setText(output);\n }\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.ProgressDialog;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.net.NetworkInfo;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.Button;\nimport android.widget.ListAdapter;\nimport android.widget.ListView;\nimport android.widget.SimpleAdapter;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Discovery;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class MainActivity extends Activity implements MainAsyncResponse {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n private Discovery discovery = new Discovery();\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView internalIp;\n private TextView externalIp;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n private ProgressDialog scanProgressDialog;\n private Handler mHandler = new Handler();\n private BroadcastReceiver receiver;\n private IntentFilter intentFilter = new IntentFilter();\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.internalIp = (TextView) findViewById(R.id.internalIpAddress);\n this.externalIp = (TextView) findViewById(R.id.externalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n this.wifi = new Wireless(this);\n\n this.macAddress.setText(this.wifi.getMacAddress());\n\n this.receiver = new BroadcastReceiver() {\n\n \/**\n * Detect if a network connection has been lost or established\n * @param context\n * @param intent\n *\/\n @Override\n public void onReceive(Context context, Intent intent) {\n NetworkInfo info = intent.getParcelableExtra(wifi.getWifiManager().EXTRA_NETWORK_INFO);\n if(info != null) {\n if(info.isConnected()) {\n getNetworkInfo();\n }\n else {\n mHandler.removeCallbacksAndMessages(null);\n MainActivity.this.internalIp.setText(\"No WiFi connection\");\n externalIp.setText(\"No WiFi connection\");\n signalStrength.setText(\"No WiFi connection\");\n ssid.setText(\"No WiFi connection\");\n bssid.setText(\"No WiFi connection\");\n }\n }\n }\n };\n\n this.intentFilter.addAction(this.wifi.getWifiManager().NETWORK_STATE_CHANGED_ACTION);\n registerReceiver(receiver, this.intentFilter);\n\n this.discoverHosts.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler to perform host discovery\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n scanProgressDialog = new ProgressDialog(MainActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning For Hosts\");\n scanProgressDialog.setProgressStyle(scanProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(255);\n scanProgressDialog.show();\n\n discovery.scanHosts(wifi.getInternalIpAddress(), MainActivity.this);\n }\n });\n\n this.hostList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open the host activity for a specific host found on the network\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n HashMap map = (HashMap) hostList.getItemAtPosition(position);\n Intent intent = new Intent(MainActivity.this, HostActivity.class);\n String firstLine = map.get(\"First Line\");\n String secondLine = map.get(\"Second Line\");\n String macAddress = map.get(\"Second Line\").substring(secondLine.indexOf(\"[\") + 1, secondLine.indexOf(\"]\"));\n\n intent.putExtra(\"HOST\", firstLine);\n intent.putExtra(\"MAC\", macAddress);\n startActivity(intent);\n }\n });\n\n }\n\n \/**\n * Gets network information about the device and updates various UI elements\n *\/\n private void getNetworkInfo() {\n this.mHandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n this.internalIp.setText(this.wifi.getInternalIpAddress());\n this.wifi.getExternalIpAddress(this);\n this.ssid.setText(this.wifi.getSSID());\n this.bssid.setText(this.wifi.getBSSID());\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n unregisterReceiver(this.receiver);\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n this.scanProgressDialog = null;\n }\n\n \/**\n * Activity restarted\n *\/\n @Override\n public void onRestart() {\n super.onRestart();\n\n registerReceiver(this.receiver, this.intentFilter);\n }\n\n \/**\n * Save the state of an activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n ListAdapter adapter = this.hostList.getAdapter();\n if(adapter != null) {\n ArrayList> adapterData = new ArrayList<>();\n for(int i = 0; i < adapter.getCount(); i++) {\n HashMap item = (HashMap) adapter.getItem(i);\n adapterData.add(item);\n }\n savedState.putSerializable(\"hosts\", adapterData);\n }\n }\n\n \/**\n * Activity state restored\n *\n * @param savedState Saved data from the saved state\n *\/\n @Override\n public void onRestoreInstanceState(Bundle savedState) {\n super.onRestoreInstanceState(savedState);\n\n ArrayList> hosts = (ArrayList) savedState.getSerializable(\"hosts\");\n if(hosts != null) {\n SimpleAdapter newAdapter = new SimpleAdapter(this, hosts, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n this.hostList.setAdapter(newAdapter);\n }\n }\n\n \/**\n * Delegate to update the host list and dismiss the progress dialog\n * Gets called when host discovery has finished\n *\n * @param output The list of hosts to bind to the list view\n *\/\n @Override\n public void processFinish(ArrayList> output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n SimpleAdapter adapter = new SimpleAdapter(this, output, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n ListView hostList = (ListView) this.findViewById(R.id.hostList);\n hostList.setAdapter(adapter);\n this.scanProgressDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to update the progress of the host discovery scan\n *\n * @param output The amount of progress to increment by\n *\/\n @Override\n public void processFinish(int output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.incrementProgressBy(output);\n }\n }\n\n \/**\n * Delegate to handle setting the external IP in the UI\n *\n * @param output External IP\n *\/\n @Override\n public void processFinish(String output) {\n this.externalIp.setText(output);\n }\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nOptimize MainActivity class for execution time. Write the entire code and no other text in the response.\n\n### Concepts:\n[-] getWifiManager()\n[+] android.net.wifi.WifiManager;\n\n### Given program:\n```java\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.ProgressDialog;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.net.NetworkInfo;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.Button;\nimport android.widget.ListAdapter;\nimport android.widget.ListView;\nimport android.widget.SimpleAdapter;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Discovery;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class MainActivity extends Activity implements MainAsyncResponse {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n private Discovery discovery = new Discovery();\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView internalIp;\n private TextView externalIp;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n private ProgressDialog scanProgressDialog;\n private Handler mHandler = new Handler();\n private BroadcastReceiver receiver;\n private IntentFilter intentFilter = new IntentFilter();\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.internalIp = (TextView) findViewById(R.id.internalIpAddress);\n this.externalIp = (TextView) findViewById(R.id.externalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n this.wifi = new Wireless(this);\n\n this.macAddress.setText(this.wifi.getMacAddress());\n\n this.receiver = new BroadcastReceiver() {\n\n \/**\n * Detect if a network connection has been lost or established\n * @param context\n * @param intent\n *\/\n @Override\n public void onReceive(Context context, Intent intent) {\n NetworkInfo info = intent.getParcelableExtra(wifi.getWifiManager().EXTRA_NETWORK_INFO);\n if(info != null) {\n if(info.isConnected()) {\n getNetworkInfo();\n }\n else {\n mHandler.removeCallbacksAndMessages(null);\n MainActivity.this.internalIp.setText(\"No WiFi connection\");\n externalIp.setText(\"No WiFi connection\");\n signalStrength.setText(\"No WiFi connection\");\n ssid.setText(\"No WiFi connection\");\n bssid.setText(\"No WiFi connection\");\n }\n }\n }\n };\n\n this.intentFilter.addAction(this.wifi.getWifiManager().NETWORK_STATE_CHANGED_ACTION);\n registerReceiver(receiver, this.intentFilter);\n\n this.discoverHosts.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler to perform host discovery\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n scanProgressDialog = new ProgressDialog(MainActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning For Hosts\");\n scanProgressDialog.setProgressStyle(scanProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(255);\n scanProgressDialog.show();\n\n discovery.scanHosts(wifi.getInternalIpAddress(), MainActivity.this);\n }\n });\n\n this.hostList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open the host activity for a specific host found on the network\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n HashMap map = (HashMap) hostList.getItemAtPosition(position);\n Intent intent = new Intent(MainActivity.this, HostActivity.class);\n String firstLine = map.get(\"First Line\");\n String secondLine = map.get(\"Second Line\");\n String macAddress = map.get(\"Second Line\").substring(secondLine.indexOf(\"[\") + 1, secondLine.indexOf(\"]\"));\n\n intent.putExtra(\"HOST\", firstLine);\n intent.putExtra(\"MAC\", macAddress);\n startActivity(intent);\n }\n });\n\n }\n\n \/**\n * Gets network information about the device and updates various UI elements\n *\/\n private void getNetworkInfo() {\n this.mHandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n this.internalIp.setText(this.wifi.getInternalIpAddress());\n this.wifi.getExternalIpAddress(this);\n this.ssid.setText(this.wifi.getSSID());\n this.bssid.setText(this.wifi.getBSSID());\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n unregisterReceiver(this.receiver);\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n this.scanProgressDialog = null;\n }\n\n \/**\n * Activity restarted\n *\/\n @Override\n public void onRestart() {\n super.onRestart();\n\n registerReceiver(this.receiver, this.intentFilter);\n }\n\n \/**\n * Save the state of an activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n ListAdapter adapter = this.hostList.getAdapter();\n if(adapter != null) {\n ArrayList> adapterData = new ArrayList<>();\n for(int i = 0; i < adapter.getCount(); i++) {\n HashMap item = (HashMap) adapter.getItem(i);\n adapterData.add(item);\n }\n savedState.putSerializable(\"hosts\", adapterData);\n }\n }\n\n \/**\n * Activity state restored\n *\n * @param savedState Saved data from the saved state\n *\/\n @Override\n public void onRestoreInstanceState(Bundle savedState) {\n super.onRestoreInstanceState(savedState);\n\n ArrayList> hosts = (ArrayList) savedState.getSerializable(\"hosts\");\n if(hosts != null) {\n SimpleAdapter newAdapter = new SimpleAdapter(this, hosts, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n this.hostList.setAdapter(newAdapter);\n }\n }\n\n \/**\n * Delegate to update the host list and dismiss the progress dialog\n * Gets called when host discovery has finished\n *\n * @param output The list of hosts to bind to the list view\n *\/\n @Override\n public void processFinish(ArrayList> output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n SimpleAdapter adapter = new SimpleAdapter(this, output, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n ListView hostList = (ListView) this.findViewById(R.id.hostList);\n hostList.setAdapter(adapter);\n this.scanProgressDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to update the progress of the host discovery scan\n *\n * @param output The amount of progress to increment by\n *\/\n @Override\n public void processFinish(int output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.incrementProgressBy(output);\n }\n }\n\n \/**\n * Delegate to handle setting the external IP in the UI\n *\n * @param output External IP\n *\/\n @Override\n public void processFinish(String output) {\n this.externalIp.setText(output);\n }\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport java.io.File;\nimport java.lang.Runtime;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.Semaphore;\n\nimport android.os.Build;\nimport android.app.Application;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Bitmap;\n\nimport com.nostra13.universalimageloader.utils.StorageUtils;\nimport com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;\nimport com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;\nimport com.nostra13.universalimageloader.core.assist.ImageScaleType;\nimport com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;\nimport com.nostra13.universalimageloader.core.DisplayImageOptions;\nimport com.nostra13.universalimageloader.core.ImageLoader;\nimport com.nostra13.universalimageloader.core.ImageLoaderConfiguration;\n\npublic class FDroidApp extends Application {\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n \/\/ Needs to be setup before anything else tries to access it.\n \/\/ Perhaps the constructor is a better place, but then again,\n \/\/ it is more deterministic as to when this gets called...\n Preferences.setup(this);\n\n \/\/ Clear cached apk files. We used to just remove them after they'd\n \/\/ been installed, but this causes problems for proprietary gapps\n \/\/ users since the introduction of verification (on pre-4.2 Android),\n \/\/ because the install intent says it's finished when it hasn't.\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(getBaseContext());\n showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n if (!prefs.getBoolean(\"cacheDownloaded\", false)) {\n\n File local_path = DB.getDataPath(this);\n \/\/ Things can be null if the SD card is not ready - we'll just\n \/\/ ignore that and do it next time.\n if(local_path != null) {\n File[] files = local_path.listFiles();\n if(files != null) {\n for(File f : files) {\n if(f.getName().endsWith(\".apk\")) {\n f.delete();\n }\n }\n }\n }\n }\n\n apps = null;\n invalidApps = new ArrayList();\n ctx = getApplicationContext();\n DB.initDB(ctx);\n UpdateService.schedule(ctx);\n\n DisplayImageOptions defaultOptions;\n int threads;\n\n \/\/ Parameters for 2.2 and below\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.color.transparent)\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = 1;\n }\n \/\/ Parameters for 2.3 and above\n else {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.color.transparent)\n .displayer(new FadeInBitmapDisplayer(200, true, true, false))\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = Runtime.getRuntime().availableProcessors() * 2;\n }\n\n ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx)\n .discCache(new UnlimitedDiscCache(\n new File(StorageUtils.getCacheDirectory(ctx), \"icons\"),\n new FileNameGenerator() {\n public String generate(String imageUri) {\n return imageUri.substring(\n imageUri.lastIndexOf('\/') + 1);\n } } ))\n .defaultDisplayImageOptions(defaultOptions)\n .threadPoolSize(threads)\n .build();\n ImageLoader.getInstance().init(config);\n Log.d(\"FDroid\", \"Universal Image Loader started with \"\n + threads + \" threads\");\n }\n\n Context ctx;\n\n \/\/ Global list of all known applications.\n private List apps;\n\n private boolean showIncompatible;\n\n \/\/ Set when something has changed (database or installed apps) so we know\n \/\/ we should invalidate the apps.\n private volatile boolean appsAllInvalid = false;\n private Semaphore appsInvalidLock = new Semaphore(1, false);\n private List invalidApps;\n\n \/\/ Set apps invalid. Call this when the database has been updated with\n \/\/ new app information, or when the installed packages have changed.\n public void invalidateAllApps() {\n try {\n appsInvalidLock.acquire();\n appsAllInvalid = true;\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n }\n\n \/\/ Invalidate a single app\n public void invalidateApp(String id) {\n Log.d(\"FDroid\", \"Invalidating \"+id);\n invalidApps.add(id);\n }\n\n \/\/ Get a list of all known applications. Should not be called when the\n \/\/ database is locked (i.e. between DB.getDB() and db.releaseDB(). The\n \/\/ contents should never be modified, it's for reading only.\n public List getApps() {\n\n boolean invalid = false;\n try {\n appsInvalidLock.acquire();\n invalid = appsAllInvalid;\n if (invalid) {\n appsAllInvalid = false;\n Log.d(\"FDroid\", \"Dropping cached app data\");\n }\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n\n if (apps == null || invalid) {\n try {\n DB db = DB.getDB();\n apps = db.getApps(true);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n } finally {\n DB.releaseDB();\n }\n } else if (!invalidApps.isEmpty()) {\n try {\n DB db = DB.getDB();\n apps = db.refreshApps(apps, invalidApps);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n if (!invalidApps.contains(app.id)) continue;\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n invalidApps.clear();\n } finally {\n DB.releaseDB();\n }\n }\n if (apps == null)\n return new ArrayList();\n filterApps();\n return apps;\n }\n\n public void filterApps() {\n AppFilter appFilter = new AppFilter(ctx);\n for (DB.App app : apps) {\n app.filtered = appFilter.filter(app);\n\n app.toUpdate = (app.hasUpdates\n && !app.ignoreAllUpdates\n && app.curApk.vercode > app.ignoreThisUpdate\n && !app.filtered\n && (showIncompatible || app.compatible));\n }\n }\n\n}\n\n\nCode-B:\n\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport java.io.File;\nimport java.lang.Runtime;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.Semaphore;\n\nimport android.os.Build;\nimport android.app.Application;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Bitmap;\n\nimport com.nostra13.universalimageloader.utils.StorageUtils;\nimport com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;\nimport com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;\nimport com.nostra13.universalimageloader.core.assist.ImageScaleType;\nimport com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;\nimport com.nostra13.universalimageloader.core.DisplayImageOptions;\nimport com.nostra13.universalimageloader.core.ImageLoader;\nimport com.nostra13.universalimageloader.core.ImageLoaderConfiguration;\n\npublic class FDroidApp extends Application {\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n \/\/ Needs to be setup before anything else tries to access it.\n \/\/ Perhaps the constructor is a better place, but then again,\n \/\/ it is more deterministic as to when this gets called...\n Preferences.setup(this);\n\n \/\/ Clear cached apk files. We used to just remove them after they'd\n \/\/ been installed, but this causes problems for proprietary gapps\n \/\/ users since the introduction of verification (on pre-4.2 Android),\n \/\/ because the install intent says it's finished when it hasn't.\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(getBaseContext());\n showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n if (!prefs.getBoolean(\"cacheDownloaded\", false)) {\n\n File local_path = DB.getDataPath(this);\n \/\/ Things can be null if the SD card is not ready - we'll just\n \/\/ ignore that and do it next time.\n if(local_path != null) {\n File[] files = local_path.listFiles();\n if(files != null) {\n for(File f : files) {\n if(f.getName().endsWith(\".apk\")) {\n f.delete();\n }\n }\n }\n }\n }\n\n apps = null;\n invalidApps = new ArrayList();\n ctx = getApplicationContext();\n DB.initDB(ctx);\n UpdateService.schedule(ctx);\n\n DisplayImageOptions defaultOptions;\n int threads;\n\n \/\/ Parameters for 2.2 and below\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.drawable.sym_def_app_icon)\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = 1;\n }\n \/\/ Parameters for 2.3 and above\n else {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.drawable.sym_def_app_icon)\n .displayer(new FadeInBitmapDisplayer(250, true, true, false))\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = Runtime.getRuntime().availableProcessors() * 2;\n }\n\n ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx)\n .discCache(new UnlimitedDiscCache(\n new File(StorageUtils.getCacheDirectory(ctx), \"icons\"),\n new FileNameGenerator() {\n public String generate(String imageUri) {\n return imageUri.substring(\n imageUri.lastIndexOf('\/') + 1);\n } } ))\n .defaultDisplayImageOptions(defaultOptions)\n .threadPoolSize(threads)\n .build();\n ImageLoader.getInstance().init(config);\n Log.d(\"FDroid\", \"Universal Image Loader started with \"\n + threads + \" threads\");\n }\n\n Context ctx;\n\n \/\/ Global list of all known applications.\n private List apps;\n\n private boolean showIncompatible;\n\n \/\/ Set when something has changed (database or installed apps) so we know\n \/\/ we should invalidate the apps.\n private volatile boolean appsAllInvalid = false;\n private Semaphore appsInvalidLock = new Semaphore(1, false);\n private List invalidApps;\n\n \/\/ Set apps invalid. Call this when the database has been updated with\n \/\/ new app information, or when the installed packages have changed.\n public void invalidateAllApps() {\n try {\n appsInvalidLock.acquire();\n appsAllInvalid = true;\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n }\n\n \/\/ Invalidate a single app\n public void invalidateApp(String id) {\n Log.d(\"FDroid\", \"Invalidating \"+id);\n invalidApps.add(id);\n }\n\n \/\/ Get a list of all known applications. Should not be called when the\n \/\/ database is locked (i.e. between DB.getDB() and db.releaseDB(). The\n \/\/ contents should never be modified, it's for reading only.\n public List getApps() {\n\n boolean invalid = false;\n try {\n appsInvalidLock.acquire();\n invalid = appsAllInvalid;\n if (invalid) {\n appsAllInvalid = false;\n Log.d(\"FDroid\", \"Dropping cached app data\");\n }\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n\n if (apps == null || invalid) {\n try {\n DB db = DB.getDB();\n apps = db.getApps(true);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n } finally {\n DB.releaseDB();\n }\n } else if (!invalidApps.isEmpty()) {\n try {\n DB db = DB.getDB();\n apps = db.refreshApps(apps, invalidApps);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n if (!invalidApps.contains(app.id)) continue;\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n invalidApps.clear();\n } finally {\n DB.releaseDB();\n }\n }\n if (apps == null)\n return new ArrayList();\n filterApps();\n return apps;\n }\n\n public void filterApps() {\n AppFilter appFilter = new AppFilter(ctx);\n for (DB.App app : apps) {\n app.filtered = appFilter.filter(app);\n\n app.toUpdate = (app.hasUpdates\n && !app.ignoreAllUpdates\n && app.curApk.vercode > app.ignoreThisUpdate\n && !app.filtered\n && (showIncompatible || app.compatible));\n }\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport java.io.File;\nimport java.lang.Runtime;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.Semaphore;\n\nimport android.os.Build;\nimport android.app.Application;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Bitmap;\n\nimport com.nostra13.universalimageloader.utils.StorageUtils;\nimport com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;\nimport com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;\nimport com.nostra13.universalimageloader.core.assist.ImageScaleType;\nimport com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;\nimport com.nostra13.universalimageloader.core.DisplayImageOptions;\nimport com.nostra13.universalimageloader.core.ImageLoader;\nimport com.nostra13.universalimageloader.core.ImageLoaderConfiguration;\n\npublic class FDroidApp extends Application {\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n \/\/ Needs to be setup before anything else tries to access it.\n \/\/ Perhaps the constructor is a better place, but then again,\n \/\/ it is more deterministic as to when this gets called...\n Preferences.setup(this);\n\n \/\/ Clear cached apk files. We used to just remove them after they'd\n \/\/ been installed, but this causes problems for proprietary gapps\n \/\/ users since the introduction of verification (on pre-4.2 Android),\n \/\/ because the install intent says it's finished when it hasn't.\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(getBaseContext());\n showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n if (!prefs.getBoolean(\"cacheDownloaded\", false)) {\n\n File local_path = DB.getDataPath(this);\n \/\/ Things can be null if the SD card is not ready - we'll just\n \/\/ ignore that and do it next time.\n if(local_path != null) {\n File[] files = local_path.listFiles();\n if(files != null) {\n for(File f : files) {\n if(f.getName().endsWith(\".apk\")) {\n f.delete();\n }\n }\n }\n }\n }\n\n apps = null;\n invalidApps = new ArrayList();\n ctx = getApplicationContext();\n DB.initDB(ctx);\n UpdateService.schedule(ctx);\n\n DisplayImageOptions defaultOptions;\n int threads;\n\n \/\/ Parameters for 2.2 and below\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.drawable.sym_def_app_icon)\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = 1;\n }\n \/\/ Parameters for 2.3 and above\n else {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.drawable.sym_def_app_icon)\n .displayer(new FadeInBitmapDisplayer(250, true, true, false))\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = Runtime.getRuntime().availableProcessors() * 2;\n }\n\n ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx)\n .discCache(new UnlimitedDiscCache(\n new File(StorageUtils.getCacheDirectory(ctx), \"icons\"),\n new FileNameGenerator() {\n public String generate(String imageUri) {\n return imageUri.substring(\n imageUri.lastIndexOf('\/') + 1);\n } } ))\n .defaultDisplayImageOptions(defaultOptions)\n .threadPoolSize(threads)\n .build();\n ImageLoader.getInstance().init(config);\n Log.d(\"FDroid\", \"Universal Image Loader started with \"\n + threads + \" threads\");\n }\n\n Context ctx;\n\n \/\/ Global list of all known applications.\n private List apps;\n\n private boolean showIncompatible;\n\n \/\/ Set when something has changed (database or installed apps) so we know\n \/\/ we should invalidate the apps.\n private volatile boolean appsAllInvalid = false;\n private Semaphore appsInvalidLock = new Semaphore(1, false);\n private List invalidApps;\n\n \/\/ Set apps invalid. Call this when the database has been updated with\n \/\/ new app information, or when the installed packages have changed.\n public void invalidateAllApps() {\n try {\n appsInvalidLock.acquire();\n appsAllInvalid = true;\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n }\n\n \/\/ Invalidate a single app\n public void invalidateApp(String id) {\n Log.d(\"FDroid\", \"Invalidating \"+id);\n invalidApps.add(id);\n }\n\n \/\/ Get a list of all known applications. Should not be called when the\n \/\/ database is locked (i.e. between DB.getDB() and db.releaseDB(). The\n \/\/ contents should never be modified, it's for reading only.\n public List getApps() {\n\n boolean invalid = false;\n try {\n appsInvalidLock.acquire();\n invalid = appsAllInvalid;\n if (invalid) {\n appsAllInvalid = false;\n Log.d(\"FDroid\", \"Dropping cached app data\");\n }\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n\n if (apps == null || invalid) {\n try {\n DB db = DB.getDB();\n apps = db.getApps(true);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n } finally {\n DB.releaseDB();\n }\n } else if (!invalidApps.isEmpty()) {\n try {\n DB db = DB.getDB();\n apps = db.refreshApps(apps, invalidApps);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n if (!invalidApps.contains(app.id)) continue;\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n invalidApps.clear();\n } finally {\n DB.releaseDB();\n }\n }\n if (apps == null)\n return new ArrayList();\n filterApps();\n return apps;\n }\n\n public void filterApps() {\n AppFilter appFilter = new AppFilter(ctx);\n for (DB.App app : apps) {\n app.filtered = appFilter.filter(app);\n\n app.toUpdate = (app.hasUpdates\n && !app.ignoreAllUpdates\n && app.curApk.vercode > app.ignoreThisUpdate\n && !app.filtered\n && (showIncompatible || app.compatible));\n }\n }\n\n}\n\n\nCode-B:\n\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport java.io.File;\nimport java.lang.Runtime;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.Semaphore;\n\nimport android.os.Build;\nimport android.app.Application;\nimport android.preference.PreferenceManager;\nimport android.util.Log;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.graphics.Bitmap;\n\nimport com.nostra13.universalimageloader.utils.StorageUtils;\nimport com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;\nimport com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;\nimport com.nostra13.universalimageloader.core.assist.ImageScaleType;\nimport com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;\nimport com.nostra13.universalimageloader.core.DisplayImageOptions;\nimport com.nostra13.universalimageloader.core.ImageLoader;\nimport com.nostra13.universalimageloader.core.ImageLoaderConfiguration;\n\npublic class FDroidApp extends Application {\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n \/\/ Needs to be setup before anything else tries to access it.\n \/\/ Perhaps the constructor is a better place, but then again,\n \/\/ it is more deterministic as to when this gets called...\n Preferences.setup(this);\n\n \/\/ Clear cached apk files. We used to just remove them after they'd\n \/\/ been installed, but this causes problems for proprietary gapps\n \/\/ users since the introduction of verification (on pre-4.2 Android),\n \/\/ because the install intent says it's finished when it hasn't.\n SharedPreferences prefs = PreferenceManager\n .getDefaultSharedPreferences(getBaseContext());\n showIncompatible = prefs.getBoolean(\"showIncompatible\", false);\n if (!prefs.getBoolean(\"cacheDownloaded\", false)) {\n\n File local_path = DB.getDataPath(this);\n \/\/ Things can be null if the SD card is not ready - we'll just\n \/\/ ignore that and do it next time.\n if(local_path != null) {\n File[] files = local_path.listFiles();\n if(files != null) {\n for(File f : files) {\n if(f.getName().endsWith(\".apk\")) {\n f.delete();\n }\n }\n }\n }\n }\n\n apps = null;\n invalidApps = new ArrayList();\n ctx = getApplicationContext();\n DB.initDB(ctx);\n UpdateService.schedule(ctx);\n\n DisplayImageOptions defaultOptions;\n int threads;\n\n \/\/ Parameters for 2.2 and below\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.color.transparent)\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = 1;\n }\n \/\/ Parameters for 2.3 and above\n else {\n defaultOptions = new DisplayImageOptions.Builder()\n .cacheInMemory(true)\n .cacheOnDisc(true)\n .showImageOnLoading(android.R.color.transparent)\n .displayer(new FadeInBitmapDisplayer(200, true, true, false))\n .bitmapConfig(Bitmap.Config.RGB_565)\n .imageScaleType(ImageScaleType.NONE)\n .build();\n threads = Runtime.getRuntime().availableProcessors() * 2;\n }\n\n ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx)\n .discCache(new UnlimitedDiscCache(\n new File(StorageUtils.getCacheDirectory(ctx), \"icons\"),\n new FileNameGenerator() {\n public String generate(String imageUri) {\n return imageUri.substring(\n imageUri.lastIndexOf('\/') + 1);\n } } ))\n .defaultDisplayImageOptions(defaultOptions)\n .threadPoolSize(threads)\n .build();\n ImageLoader.getInstance().init(config);\n Log.d(\"FDroid\", \"Universal Image Loader started with \"\n + threads + \" threads\");\n }\n\n Context ctx;\n\n \/\/ Global list of all known applications.\n private List apps;\n\n private boolean showIncompatible;\n\n \/\/ Set when something has changed (database or installed apps) so we know\n \/\/ we should invalidate the apps.\n private volatile boolean appsAllInvalid = false;\n private Semaphore appsInvalidLock = new Semaphore(1, false);\n private List invalidApps;\n\n \/\/ Set apps invalid. Call this when the database has been updated with\n \/\/ new app information, or when the installed packages have changed.\n public void invalidateAllApps() {\n try {\n appsInvalidLock.acquire();\n appsAllInvalid = true;\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n }\n\n \/\/ Invalidate a single app\n public void invalidateApp(String id) {\n Log.d(\"FDroid\", \"Invalidating \"+id);\n invalidApps.add(id);\n }\n\n \/\/ Get a list of all known applications. Should not be called when the\n \/\/ database is locked (i.e. between DB.getDB() and db.releaseDB(). The\n \/\/ contents should never be modified, it's for reading only.\n public List getApps() {\n\n boolean invalid = false;\n try {\n appsInvalidLock.acquire();\n invalid = appsAllInvalid;\n if (invalid) {\n appsAllInvalid = false;\n Log.d(\"FDroid\", \"Dropping cached app data\");\n }\n } catch (InterruptedException e) {\n \/\/ Don't care\n } finally {\n appsInvalidLock.release();\n }\n\n if (apps == null || invalid) {\n try {\n DB db = DB.getDB();\n apps = db.getApps(true);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n } finally {\n DB.releaseDB();\n }\n } else if (!invalidApps.isEmpty()) {\n try {\n DB db = DB.getDB();\n apps = db.refreshApps(apps, invalidApps);\n\n List repos = db.getRepos();\n for (DB.App app : apps) {\n if (!invalidApps.contains(app.id)) continue;\n for (DB.Repo repo : repos) {\n DB.Apk bestApk = app.apks.get(0);\n if (repo.id == bestApk.repo) {\n app.iconUrl = repo.address + \"\/icons\/\" + app.icon;\n break;\n }\n }\n }\n\n invalidApps.clear();\n } finally {\n DB.releaseDB();\n }\n }\n if (apps == null)\n return new ArrayList();\n filterApps();\n return apps;\n }\n\n public void filterApps() {\n AppFilter appFilter = new AppFilter(ctx);\n for (DB.App app : apps) {\n app.filtered = appFilter.filter(app);\n\n app.toUpdate = (app.hasUpdates\n && !app.ignoreAllUpdates\n && app.curApk.vercode > app.ignoreThisUpdate\n && !app.filtered\n && (showIncompatible || app.compatible));\n }\n }\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/leonardbos\/FirefoxFocusASV\/commit\/71c289ea70ad002feb0dcb55f5122087abf72bb4","commit_message":"'\\\\\"Switch categoryPrefMap from HashMap to ArrayMap\\\\n\\\\nWe only ever iterate over the entries","source_code":"\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\npackage org.mozilla.focus.webkit.matcher;\n\n\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.annotation.VisibleForTesting;\nimport android.util.JsonReader;\n\nimport org.mozilla.focus.R;\nimport org.mozilla.focus.webkit.matcher.util.FocusString;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.nio.charset.StandardCharsets;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class UrlMatcher implements SharedPreferences.OnSharedPreferenceChangeListener {\n \/**\n * Map of pref to blocking category (preference key -> Blocklist category name).\n *\/\n private final Map categoryPrefMap;\n\n private static final String[] WEBFONT_EXTENSIONS = new String[]{\n \".woff2\",\n \".woff\",\n \".eot\",\n \".ttf\",\n \".otf\"\n };\n\n private static final String WEBFONTS = \"Webfonts\";\n\n private static Map loadDefaultPrefMap(final Context context) {\n Map tempMap = new HashMap<>(5);\n\n tempMap.put(context.getString(R.string.pref_key_privacy_block_ads), \"Advertising\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_analytics), \"Analytics\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_social), \"Social\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_other), \"Content\");\n\n \/\/ This is a \"fake\" category - webfont handling is independent of the blocklists\n tempMap.put(context.getString(R.string.pref_key_performance_block_webfonts), WEBFONTS);\n\n return Collections.unmodifiableMap(tempMap);\n }\n\n private final Map categories;\n private final Set enabledCategories = new HashSet<>();\n\n private final EntityList entityList;\n \/\/ A cached list of previously matched URLs. This MUST be cleared whenever items are removed from enabledCategories.\n private final HashSet previouslyMatched = new HashSet<>();\n \/\/ A cahced list of previously approved URLs. This MUST be cleared whenever items are added to enabledCategories.\n private final HashSet previouslyUnmatched = new HashSet<>();\n\n private boolean blockWebfonts = true;\n\n public static UrlMatcher loadMatcher(final Context context, final int blockListFile, final int[] blockListOverrides, final int entityListFile) {\n final Map categoryPrefMap = loadDefaultPrefMap(context);\n\n final Map categoryMap = new HashMap<>(5);\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListFile), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.BASE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse blacklist\");\n }\n\n if (blockListOverrides != null) {\n for (int i = 0; i < blockListOverrides.length; i++) {\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListOverrides[i]), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.OVERRIDE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse override blacklist\");\n }\n }\n }\n\n final EntityList entityList;\n try (final JsonReader jsonReader = new JsonReader(new InputStreamReader(context.getResources().openRawResource(entityListFile), StandardCharsets.UTF_8))){\n entityList = EntityListProcessor.getEntityMapFromJSON(jsonReader);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse entity list\");\n }\n\n return new UrlMatcher(context, categoryPrefMap, categoryMap, entityList);\n }\n\n \/* package-private *\/ UrlMatcher(final Context context,\n @NonNull final Map categoryPrefMap,\n @NonNull final Map categoryMap,\n @Nullable final EntityList entityList) {\n this.categoryPrefMap = categoryPrefMap;\n this.entityList = entityList;\n this.categories = categoryMap;\n\n \/\/ Ensure all categories have been declared, and enable by default (loadPrefs() will then\n \/\/ enabled\/disable categories that have actually been configured).\n for (final Map.Entry entry: categoryMap.entrySet()) {\n if (!categoryPrefMap.values().contains(entry.getKey())) {\n throw new IllegalArgumentException(\"categoryMap contains undeclared category\");\n }\n\n \/\/ Failsafe: enable all categories (we load preferences in the next step anyway)\n enabledCategories.add(entry.getKey());\n }\n\n loadPrefs(context);\n\n PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(this);\n }\n\n @Override\n public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String prefName) {\n final String categoryName = categoryPrefMap.get(prefName);\n\n if (categoryName != null) {\n final boolean prefValue = sharedPreferences.getBoolean(prefName, false);\n\n setCategoryEnabled(categoryName, prefValue);\n }\n }\n\n private void loadPrefs(final Context context) {\n final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n for (final Map.Entry entry : categoryPrefMap.entrySet()) {\n final boolean prefValue = prefs.getBoolean(entry.getKey(), true);\n setCategoryEnabled(entry.getValue(), prefValue);\n }\n }\n\n @VisibleForTesting UrlMatcher(final String[] patterns) {\n final Map map = new HashMap<>();\n map.put(\"default\", \"default\");\n categoryPrefMap = Collections.unmodifiableMap(map);\n\n categories = new HashMap<>();\n\n buildMatcher(patterns);\n\n entityList = null;\n }\n\n \/**\n * Only used for testing - uses a list of urls to populate a \"default\" category.\n * @param patterns\n *\/\n private void buildMatcher(String[] patterns) {\n final Trie defaultCategory;\n if (!categories.containsKey(\"default\")) {\n defaultCategory = Trie.createRootNode();\n categories.put(\"default\", defaultCategory);\n } else {\n defaultCategory = categories.get(\"default\");\n }\n\n for (final String pattern : patterns) {\n defaultCategory.put(FocusString.create(pattern).reverse());\n }\n\n enabledCategories.add(\"default\");\n }\n\n public Set getCategories() {\n return categories.keySet();\n }\n\n public void setCategoryEnabled(final String category, final boolean enabled) {\n if (WEBFONTS.equals(category)) {\n blockWebfonts = enabled;\n return;\n }\n\n if (!getCategories().contains(category)) {\n throw new IllegalArgumentException(\"Can't enable\/disable inexistant category\");\n }\n\n if (enabled) {\n if (enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already enabled\n return;\n } else {\n enabledCategories.add(category);\n previouslyUnmatched.clear();\n }\n } else {\n if (!enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already disabled\n return;\n } else {\n enabledCategories.remove(category);\n previouslyMatched.clear();\n }\n\n }\n }\n\n public boolean matches(final Uri resourceURI, final Uri pageURI) {\n final String path = resourceURI.getPath();\n\n if (path == null) {\n return false;\n }\n\n \/\/ We need to handle webfonts first: if they are blocked, then whitelists don't matter.\n \/\/ If they aren't blocked we still need to check domain blacklists below.\n if (blockWebfonts) {\n for (final String extension : WEBFONT_EXTENSIONS) {\n if (path.endsWith(extension)) {\n return true;\n }\n }\n }\n\n final String resourceURLString = resourceURI.toString();\n\n \/\/ Cached whitelisted items can be permitted now (but blacklisted needs to wait for the override \/ entity list)\n if (previouslyUnmatched.contains(resourceURLString)) {\n return false;\n }\n\n if (entityList != null &&\n entityList.isWhiteListed(pageURI, resourceURI)) {\n \/\/ We must not cache entityList items (and\/or if we did, we'd have to clear the cache\n \/\/ on every single location change)\n return false;\n }\n\n final String resourceHost = resourceURI.getHost();\n final String pageHost = pageURI.getHost();\n\n if (pageHost != null && pageHost.equals(resourceHost)) {\n return false;\n }\n\n if (previouslyMatched.contains(resourceURLString)) {\n return true;\n }\n\n final FocusString revhost = FocusString.create(resourceHost).reverse();\n\n for (final Map.Entry category : categories.entrySet()) {\n if (enabledCategories.contains(category.getKey())) {\n if (category.getValue().findNode(revhost) != null) {\n previouslyMatched.add(resourceURLString);\n return true;\n }\n }\n }\n\n previouslyUnmatched.add(resourceURLString);\n return false;\n }\n}\n","target_code":"\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\npackage org.mozilla.focus.webkit.matcher;\n\n\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.annotation.VisibleForTesting;\nimport android.support.v4.util.ArrayMap;\nimport android.util.JsonReader;\n\nimport org.mozilla.focus.R;\nimport org.mozilla.focus.webkit.matcher.util.FocusString;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.nio.charset.StandardCharsets;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class UrlMatcher implements SharedPreferences.OnSharedPreferenceChangeListener {\n \/**\n * Map of pref to blocking category (preference key -> Blocklist category name).\n *\/\n private final Map categoryPrefMap;\n\n private static final String[] WEBFONT_EXTENSIONS = new String[]{\n \".woff2\",\n \".woff\",\n \".eot\",\n \".ttf\",\n \".otf\"\n };\n\n private static final String WEBFONTS = \"Webfonts\";\n\n private static Map loadDefaultPrefMap(final Context context) {\n Map tempMap = new ArrayMap<>();\n\n tempMap.put(context.getString(R.string.pref_key_privacy_block_ads), \"Advertising\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_analytics), \"Analytics\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_social), \"Social\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_other), \"Content\");\n\n \/\/ This is a \"fake\" category - webfont handling is independent of the blocklists\n tempMap.put(context.getString(R.string.pref_key_performance_block_webfonts), WEBFONTS);\n\n return Collections.unmodifiableMap(tempMap);\n }\n\n private final Map categories;\n private final Set enabledCategories = new HashSet<>();\n\n private final EntityList entityList;\n \/\/ A cached list of previously matched URLs. This MUST be cleared whenever items are removed from enabledCategories.\n private final HashSet previouslyMatched = new HashSet<>();\n \/\/ A cahced list of previously approved URLs. This MUST be cleared whenever items are added to enabledCategories.\n private final HashSet previouslyUnmatched = new HashSet<>();\n\n private boolean blockWebfonts = true;\n\n public static UrlMatcher loadMatcher(final Context context, final int blockListFile, final int[] blockListOverrides, final int entityListFile) {\n final Map categoryPrefMap = loadDefaultPrefMap(context);\n\n final Map categoryMap = new HashMap<>(5);\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListFile), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.BASE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse blacklist\");\n }\n\n if (blockListOverrides != null) {\n for (int i = 0; i < blockListOverrides.length; i++) {\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListOverrides[i]), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.OVERRIDE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse override blacklist\");\n }\n }\n }\n\n final EntityList entityList;\n try (final JsonReader jsonReader = new JsonReader(new InputStreamReader(context.getResources().openRawResource(entityListFile), StandardCharsets.UTF_8))){\n entityList = EntityListProcessor.getEntityMapFromJSON(jsonReader);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse entity list\");\n }\n\n return new UrlMatcher(context, categoryPrefMap, categoryMap, entityList);\n }\n\n \/* package-private *\/ UrlMatcher(final Context context,\n @NonNull final Map categoryPrefMap,\n @NonNull final Map categoryMap,\n @Nullable final EntityList entityList) {\n this.categoryPrefMap = categoryPrefMap;\n this.entityList = entityList;\n this.categories = categoryMap;\n\n \/\/ Ensure all categories have been declared, and enable by default (loadPrefs() will then\n \/\/ enabled\/disable categories that have actually been configured).\n for (final Map.Entry entry: categoryMap.entrySet()) {\n if (!categoryPrefMap.values().contains(entry.getKey())) {\n throw new IllegalArgumentException(\"categoryMap contains undeclared category\");\n }\n\n \/\/ Failsafe: enable all categories (we load preferences in the next step anyway)\n enabledCategories.add(entry.getKey());\n }\n\n loadPrefs(context);\n\n PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(this);\n }\n\n @Override\n public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String prefName) {\n final String categoryName = categoryPrefMap.get(prefName);\n\n if (categoryName != null) {\n final boolean prefValue = sharedPreferences.getBoolean(prefName, false);\n\n setCategoryEnabled(categoryName, prefValue);\n }\n }\n\n private void loadPrefs(final Context context) {\n final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n for (final Map.Entry entry : categoryPrefMap.entrySet()) {\n final boolean prefValue = prefs.getBoolean(entry.getKey(), true);\n setCategoryEnabled(entry.getValue(), prefValue);\n }\n }\n\n @VisibleForTesting UrlMatcher(final String[] patterns) {\n final Map map = new HashMap<>();\n map.put(\"default\", \"default\");\n categoryPrefMap = Collections.unmodifiableMap(map);\n\n categories = new HashMap<>();\n\n buildMatcher(patterns);\n\n entityList = null;\n }\n\n \/**\n * Only used for testing - uses a list of urls to populate a \"default\" category.\n * @param patterns\n *\/\n private void buildMatcher(String[] patterns) {\n final Trie defaultCategory;\n if (!categories.containsKey(\"default\")) {\n defaultCategory = Trie.createRootNode();\n categories.put(\"default\", defaultCategory);\n } else {\n defaultCategory = categories.get(\"default\");\n }\n\n for (final String pattern : patterns) {\n defaultCategory.put(FocusString.create(pattern).reverse());\n }\n\n enabledCategories.add(\"default\");\n }\n\n public Set getCategories() {\n return categories.keySet();\n }\n\n public void setCategoryEnabled(final String category, final boolean enabled) {\n if (WEBFONTS.equals(category)) {\n blockWebfonts = enabled;\n return;\n }\n\n if (!getCategories().contains(category)) {\n throw new IllegalArgumentException(\"Can't enable\/disable inexistant category\");\n }\n\n if (enabled) {\n if (enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already enabled\n return;\n } else {\n enabledCategories.add(category);\n previouslyUnmatched.clear();\n }\n } else {\n if (!enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already disabled\n return;\n } else {\n enabledCategories.remove(category);\n previouslyMatched.clear();\n }\n\n }\n }\n\n public boolean matches(final Uri resourceURI, final Uri pageURI) {\n final String path = resourceURI.getPath();\n\n if (path == null) {\n return false;\n }\n\n \/\/ We need to handle webfonts first: if they are blocked, then whitelists don't matter.\n \/\/ If they aren't blocked we still need to check domain blacklists below.\n if (blockWebfonts) {\n for (final String extension : WEBFONT_EXTENSIONS) {\n if (path.endsWith(extension)) {\n return true;\n }\n }\n }\n\n final String resourceURLString = resourceURI.toString();\n\n \/\/ Cached whitelisted items can be permitted now (but blacklisted needs to wait for the override \/ entity list)\n if (previouslyUnmatched.contains(resourceURLString)) {\n return false;\n }\n\n if (entityList != null &&\n entityList.isWhiteListed(pageURI, resourceURI)) {\n \/\/ We must not cache entityList items (and\/or if we did, we'd have to clear the cache\n \/\/ on every single location change)\n return false;\n }\n\n final String resourceHost = resourceURI.getHost();\n final String pageHost = pageURI.getHost();\n\n if (pageHost != null && pageHost.equals(resourceHost)) {\n return false;\n }\n\n if (previouslyMatched.contains(resourceURLString)) {\n return true;\n }\n\n final FocusString revhost = FocusString.create(resourceHost).reverse();\n\n for (final Map.Entry category : categories.entrySet()) {\n if (enabledCategories.contains(category.getKey())) {\n if (category.getValue().findNode(revhost) != null) {\n previouslyMatched.add(resourceURLString);\n return true;\n }\n }\n }\n\n previouslyUnmatched.add(resourceURLString);\n return false;\n }\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\npackage org.mozilla.focus.webkit.matcher;\n\n\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.annotation.VisibleForTesting;\nimport android.util.JsonReader;\n\nimport org.mozilla.focus.R;\nimport org.mozilla.focus.webkit.matcher.util.FocusString;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.nio.charset.StandardCharsets;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class UrlMatcher implements SharedPreferences.OnSharedPreferenceChangeListener {\n \/**\n * Map of pref to blocking category (preference key -> Blocklist category name).\n *\/\n private final Map categoryPrefMap;\n\n private static final String[] WEBFONT_EXTENSIONS = new String[]{\n \".woff2\",\n \".woff\",\n \".eot\",\n \".ttf\",\n \".otf\"\n };\n\n private static final String WEBFONTS = \"Webfonts\";\n\n private static Map loadDefaultPrefMap(final Context context) {\n Map tempMap = new HashMap<>(5);\n\n tempMap.put(context.getString(R.string.pref_key_privacy_block_ads), \"Advertising\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_analytics), \"Analytics\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_social), \"Social\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_other), \"Content\");\n\n \/\/ This is a \"fake\" category - webfont handling is independent of the blocklists\n tempMap.put(context.getString(R.string.pref_key_performance_block_webfonts), WEBFONTS);\n\n return Collections.unmodifiableMap(tempMap);\n }\n\n private final Map categories;\n private final Set enabledCategories = new HashSet<>();\n\n private final EntityList entityList;\n \/\/ A cached list of previously matched URLs. This MUST be cleared whenever items are removed from enabledCategories.\n private final HashSet previouslyMatched = new HashSet<>();\n \/\/ A cahced list of previously approved URLs. This MUST be cleared whenever items are added to enabledCategories.\n private final HashSet previouslyUnmatched = new HashSet<>();\n\n private boolean blockWebfonts = true;\n\n public static UrlMatcher loadMatcher(final Context context, final int blockListFile, final int[] blockListOverrides, final int entityListFile) {\n final Map categoryPrefMap = loadDefaultPrefMap(context);\n\n final Map categoryMap = new HashMap<>(5);\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListFile), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.BASE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse blacklist\");\n }\n\n if (blockListOverrides != null) {\n for (int i = 0; i < blockListOverrides.length; i++) {\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListOverrides[i]), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.OVERRIDE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse override blacklist\");\n }\n }\n }\n\n final EntityList entityList;\n try (final JsonReader jsonReader = new JsonReader(new InputStreamReader(context.getResources().openRawResource(entityListFile), StandardCharsets.UTF_8))){\n entityList = EntityListProcessor.getEntityMapFromJSON(jsonReader);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse entity list\");\n }\n\n return new UrlMatcher(context, categoryPrefMap, categoryMap, entityList);\n }\n\n \/* package-private *\/ UrlMatcher(final Context context,\n @NonNull final Map categoryPrefMap,\n @NonNull final Map categoryMap,\n @Nullable final EntityList entityList) {\n this.categoryPrefMap = categoryPrefMap;\n this.entityList = entityList;\n this.categories = categoryMap;\n\n \/\/ Ensure all categories have been declared, and enable by default (loadPrefs() will then\n \/\/ enabled\/disable categories that have actually been configured).\n for (final Map.Entry entry: categoryMap.entrySet()) {\n if (!categoryPrefMap.values().contains(entry.getKey())) {\n throw new IllegalArgumentException(\"categoryMap contains undeclared category\");\n }\n\n \/\/ Failsafe: enable all categories (we load preferences in the next step anyway)\n enabledCategories.add(entry.getKey());\n }\n\n loadPrefs(context);\n\n PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(this);\n }\n\n @Override\n public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String prefName) {\n final String categoryName = categoryPrefMap.get(prefName);\n\n if (categoryName != null) {\n final boolean prefValue = sharedPreferences.getBoolean(prefName, false);\n\n setCategoryEnabled(categoryName, prefValue);\n }\n }\n\n private void loadPrefs(final Context context) {\n final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n for (final Map.Entry entry : categoryPrefMap.entrySet()) {\n final boolean prefValue = prefs.getBoolean(entry.getKey(), true);\n setCategoryEnabled(entry.getValue(), prefValue);\n }\n }\n\n @VisibleForTesting UrlMatcher(final String[] patterns) {\n final Map map = new HashMap<>();\n map.put(\"default\", \"default\");\n categoryPrefMap = Collections.unmodifiableMap(map);\n\n categories = new HashMap<>();\n\n buildMatcher(patterns);\n\n entityList = null;\n }\n\n \/**\n * Only used for testing - uses a list of urls to populate a \"default\" category.\n * @param patterns\n *\/\n private void buildMatcher(String[] patterns) {\n final Trie defaultCategory;\n if (!categories.containsKey(\"default\")) {\n defaultCategory = Trie.createRootNode();\n categories.put(\"default\", defaultCategory);\n } else {\n defaultCategory = categories.get(\"default\");\n }\n\n for (final String pattern : patterns) {\n defaultCategory.put(FocusString.create(pattern).reverse());\n }\n\n enabledCategories.add(\"default\");\n }\n\n public Set getCategories() {\n return categories.keySet();\n }\n\n public void setCategoryEnabled(final String category, final boolean enabled) {\n if (WEBFONTS.equals(category)) {\n blockWebfonts = enabled;\n return;\n }\n\n if (!getCategories().contains(category)) {\n throw new IllegalArgumentException(\"Can't enable\/disable inexistant category\");\n }\n\n if (enabled) {\n if (enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already enabled\n return;\n } else {\n enabledCategories.add(category);\n previouslyUnmatched.clear();\n }\n } else {\n if (!enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already disabled\n return;\n } else {\n enabledCategories.remove(category);\n previouslyMatched.clear();\n }\n\n }\n }\n\n public boolean matches(final Uri resourceURI, final Uri pageURI) {\n final String path = resourceURI.getPath();\n\n if (path == null) {\n return false;\n }\n\n \/\/ We need to handle webfonts first: if they are blocked, then whitelists don't matter.\n \/\/ If they aren't blocked we still need to check domain blacklists below.\n if (blockWebfonts) {\n for (final String extension : WEBFONT_EXTENSIONS) {\n if (path.endsWith(extension)) {\n return true;\n }\n }\n }\n\n final String resourceURLString = resourceURI.toString();\n\n \/\/ Cached whitelisted items can be permitted now (but blacklisted needs to wait for the override \/ entity list)\n if (previouslyUnmatched.contains(resourceURLString)) {\n return false;\n }\n\n if (entityList != null &&\n entityList.isWhiteListed(pageURI, resourceURI)) {\n \/\/ We must not cache entityList items (and\/or if we did, we'd have to clear the cache\n \/\/ on every single location change)\n return false;\n }\n\n final String resourceHost = resourceURI.getHost();\n final String pageHost = pageURI.getHost();\n\n if (pageHost != null && pageHost.equals(resourceHost)) {\n return false;\n }\n\n if (previouslyMatched.contains(resourceURLString)) {\n return true;\n }\n\n final FocusString revhost = FocusString.create(resourceHost).reverse();\n\n for (final Map.Entry category : categories.entrySet()) {\n if (enabledCategories.contains(category.getKey())) {\n if (category.getValue().findNode(revhost) != null) {\n previouslyMatched.add(resourceURLString);\n return true;\n }\n }\n }\n\n previouslyUnmatched.add(resourceURLString);\n return false;\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\npackage org.mozilla.focus.webkit.matcher;\n\n\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.annotation.VisibleForTesting;\nimport android.util.JsonReader;\n\nimport org.mozilla.focus.R;\nimport org.mozilla.focus.webkit.matcher.util.FocusString;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.nio.charset.StandardCharsets;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class UrlMatcher implements SharedPreferences.OnSharedPreferenceChangeListener {\n \/**\n * Map of pref to blocking category (preference key -> Blocklist category name).\n *\/\n private final Map categoryPrefMap;\n\n private static final String[] WEBFONT_EXTENSIONS = new String[]{\n \".woff2\",\n \".woff\",\n \".eot\",\n \".ttf\",\n \".otf\"\n };\n\n private static final String WEBFONTS = \"Webfonts\";\n\n private static Map loadDefaultPrefMap(final Context context) {\n Map tempMap = new HashMap<>(5);\n\n tempMap.put(context.getString(R.string.pref_key_privacy_block_ads), \"Advertising\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_analytics), \"Analytics\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_social), \"Social\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_other), \"Content\");\n\n \/\/ This is a \"fake\" category - webfont handling is independent of the blocklists\n tempMap.put(context.getString(R.string.pref_key_performance_block_webfonts), WEBFONTS);\n\n return Collections.unmodifiableMap(tempMap);\n }\n\n private final Map categories;\n private final Set enabledCategories = new HashSet<>();\n\n private final EntityList entityList;\n \/\/ A cached list of previously matched URLs. This MUST be cleared whenever items are removed from enabledCategories.\n private final HashSet previouslyMatched = new HashSet<>();\n \/\/ A cahced list of previously approved URLs. This MUST be cleared whenever items are added to enabledCategories.\n private final HashSet previouslyUnmatched = new HashSet<>();\n\n private boolean blockWebfonts = true;\n\n public static UrlMatcher loadMatcher(final Context context, final int blockListFile, final int[] blockListOverrides, final int entityListFile) {\n final Map categoryPrefMap = loadDefaultPrefMap(context);\n\n final Map categoryMap = new HashMap<>(5);\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListFile), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.BASE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse blacklist\");\n }\n\n if (blockListOverrides != null) {\n for (int i = 0; i < blockListOverrides.length; i++) {\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListOverrides[i]), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.OVERRIDE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse override blacklist\");\n }\n }\n }\n\n final EntityList entityList;\n try (final JsonReader jsonReader = new JsonReader(new InputStreamReader(context.getResources().openRawResource(entityListFile), StandardCharsets.UTF_8))){\n entityList = EntityListProcessor.getEntityMapFromJSON(jsonReader);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse entity list\");\n }\n\n return new UrlMatcher(context, categoryPrefMap, categoryMap, entityList);\n }\n\n \/* package-private *\/ UrlMatcher(final Context context,\n @NonNull final Map categoryPrefMap,\n @NonNull final Map categoryMap,\n @Nullable final EntityList entityList) {\n this.categoryPrefMap = categoryPrefMap;\n this.entityList = entityList;\n this.categories = categoryMap;\n\n \/\/ Ensure all categories have been declared, and enable by default (loadPrefs() will then\n \/\/ enabled\/disable categories that have actually been configured).\n for (final Map.Entry entry: categoryMap.entrySet()) {\n if (!categoryPrefMap.values().contains(entry.getKey())) {\n throw new IllegalArgumentException(\"categoryMap contains undeclared category\");\n }\n\n \/\/ Failsafe: enable all categories (we load preferences in the next step anyway)\n enabledCategories.add(entry.getKey());\n }\n\n loadPrefs(context);\n\n PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(this);\n }\n\n @Override\n public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String prefName) {\n final String categoryName = categoryPrefMap.get(prefName);\n\n if (categoryName != null) {\n final boolean prefValue = sharedPreferences.getBoolean(prefName, false);\n\n setCategoryEnabled(categoryName, prefValue);\n }\n }\n\n private void loadPrefs(final Context context) {\n final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n for (final Map.Entry entry : categoryPrefMap.entrySet()) {\n final boolean prefValue = prefs.getBoolean(entry.getKey(), true);\n setCategoryEnabled(entry.getValue(), prefValue);\n }\n }\n\n @VisibleForTesting UrlMatcher(final String[] patterns) {\n final Map map = new HashMap<>();\n map.put(\"default\", \"default\");\n categoryPrefMap = Collections.unmodifiableMap(map);\n\n categories = new HashMap<>();\n\n buildMatcher(patterns);\n\n entityList = null;\n }\n\n \/**\n * Only used for testing - uses a list of urls to populate a \"default\" category.\n * @param patterns\n *\/\n private void buildMatcher(String[] patterns) {\n final Trie defaultCategory;\n if (!categories.containsKey(\"default\")) {\n defaultCategory = Trie.createRootNode();\n categories.put(\"default\", defaultCategory);\n } else {\n defaultCategory = categories.get(\"default\");\n }\n\n for (final String pattern : patterns) {\n defaultCategory.put(FocusString.create(pattern).reverse());\n }\n\n enabledCategories.add(\"default\");\n }\n\n public Set getCategories() {\n return categories.keySet();\n }\n\n public void setCategoryEnabled(final String category, final boolean enabled) {\n if (WEBFONTS.equals(category)) {\n blockWebfonts = enabled;\n return;\n }\n\n if (!getCategories().contains(category)) {\n throw new IllegalArgumentException(\"Can't enable\/disable inexistant category\");\n }\n\n if (enabled) {\n if (enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already enabled\n return;\n } else {\n enabledCategories.add(category);\n previouslyUnmatched.clear();\n }\n } else {\n if (!enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already disabled\n return;\n } else {\n enabledCategories.remove(category);\n previouslyMatched.clear();\n }\n\n }\n }\n\n public boolean matches(final Uri resourceURI, final Uri pageURI) {\n final String path = resourceURI.getPath();\n\n if (path == null) {\n return false;\n }\n\n \/\/ We need to handle webfonts first: if they are blocked, then whitelists don't matter.\n \/\/ If they aren't blocked we still need to check domain blacklists below.\n if (blockWebfonts) {\n for (final String extension : WEBFONT_EXTENSIONS) {\n if (path.endsWith(extension)) {\n return true;\n }\n }\n }\n\n final String resourceURLString = resourceURI.toString();\n\n \/\/ Cached whitelisted items can be permitted now (but blacklisted needs to wait for the override \/ entity list)\n if (previouslyUnmatched.contains(resourceURLString)) {\n return false;\n }\n\n if (entityList != null &&\n entityList.isWhiteListed(pageURI, resourceURI)) {\n \/\/ We must not cache entityList items (and\/or if we did, we'd have to clear the cache\n \/\/ on every single location change)\n return false;\n }\n\n final String resourceHost = resourceURI.getHost();\n final String pageHost = pageURI.getHost();\n\n if (pageHost != null && pageHost.equals(resourceHost)) {\n return false;\n }\n\n if (previouslyMatched.contains(resourceURLString)) {\n return true;\n }\n\n final FocusString revhost = FocusString.create(resourceHost).reverse();\n\n for (final Map.Entry category : categories.entrySet()) {\n if (enabledCategories.contains(category.getKey())) {\n if (category.getValue().findNode(revhost) != null) {\n previouslyMatched.add(resourceURLString);\n return true;\n }\n }\n }\n\n previouslyUnmatched.add(resourceURLString);\n return false;\n }\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\npackage org.mozilla.focus.webkit.matcher;\n\n\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.annotation.VisibleForTesting;\nimport android.util.JsonReader;\n\nimport org.mozilla.focus.R;\nimport org.mozilla.focus.webkit.matcher.util.FocusString;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.nio.charset.StandardCharsets;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class UrlMatcher implements SharedPreferences.OnSharedPreferenceChangeListener {\n \/**\n * Map of pref to blocking category (preference key -> Blocklist category name).\n *\/\n private final Map categoryPrefMap;\n\n private static final String[] WEBFONT_EXTENSIONS = new String[]{\n \".woff2\",\n \".woff\",\n \".eot\",\n \".ttf\",\n \".otf\"\n };\n\n private static final String WEBFONTS = \"Webfonts\";\n\n private static Map loadDefaultPrefMap(final Context context) {\n Map tempMap = new HashMap<>(5);\n\n tempMap.put(context.getString(R.string.pref_key_privacy_block_ads), \"Advertising\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_analytics), \"Analytics\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_social), \"Social\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_other), \"Content\");\n\n \/\/ This is a \"fake\" category - webfont handling is independent of the blocklists\n tempMap.put(context.getString(R.string.pref_key_performance_block_webfonts), WEBFONTS);\n\n return Collections.unmodifiableMap(tempMap);\n }\n\n private final Map categories;\n private final Set enabledCategories = new HashSet<>();\n\n private final EntityList entityList;\n \/\/ A cached list of previously matched URLs. This MUST be cleared whenever items are removed from enabledCategories.\n private final HashSet previouslyMatched = new HashSet<>();\n \/\/ A cahced list of previously approved URLs. This MUST be cleared whenever items are added to enabledCategories.\n private final HashSet previouslyUnmatched = new HashSet<>();\n\n private boolean blockWebfonts = true;\n\n public static UrlMatcher loadMatcher(final Context context, final int blockListFile, final int[] blockListOverrides, final int entityListFile) {\n final Map categoryPrefMap = loadDefaultPrefMap(context);\n\n final Map categoryMap = new HashMap<>(5);\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListFile), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.BASE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse blacklist\");\n }\n\n if (blockListOverrides != null) {\n for (int i = 0; i < blockListOverrides.length; i++) {\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListOverrides[i]), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.OVERRIDE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse override blacklist\");\n }\n }\n }\n\n final EntityList entityList;\n try (final JsonReader jsonReader = new JsonReader(new InputStreamReader(context.getResources().openRawResource(entityListFile), StandardCharsets.UTF_8))){\n entityList = EntityListProcessor.getEntityMapFromJSON(jsonReader);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse entity list\");\n }\n\n return new UrlMatcher(context, categoryPrefMap, categoryMap, entityList);\n }\n\n \/* package-private *\/ UrlMatcher(final Context context,\n @NonNull final Map categoryPrefMap,\n @NonNull final Map categoryMap,\n @Nullable final EntityList entityList) {\n this.categoryPrefMap = categoryPrefMap;\n this.entityList = entityList;\n this.categories = categoryMap;\n\n \/\/ Ensure all categories have been declared, and enable by default (loadPrefs() will then\n \/\/ enabled\/disable categories that have actually been configured).\n for (final Map.Entry entry: categoryMap.entrySet()) {\n if (!categoryPrefMap.values().contains(entry.getKey())) {\n throw new IllegalArgumentException(\"categoryMap contains undeclared category\");\n }\n\n \/\/ Failsafe: enable all categories (we load preferences in the next step anyway)\n enabledCategories.add(entry.getKey());\n }\n\n loadPrefs(context);\n\n PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(this);\n }\n\n @Override\n public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String prefName) {\n final String categoryName = categoryPrefMap.get(prefName);\n\n if (categoryName != null) {\n final boolean prefValue = sharedPreferences.getBoolean(prefName, false);\n\n setCategoryEnabled(categoryName, prefValue);\n }\n }\n\n private void loadPrefs(final Context context) {\n final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n for (final Map.Entry entry : categoryPrefMap.entrySet()) {\n final boolean prefValue = prefs.getBoolean(entry.getKey(), true);\n setCategoryEnabled(entry.getValue(), prefValue);\n }\n }\n\n @VisibleForTesting UrlMatcher(final String[] patterns) {\n final Map map = new HashMap<>();\n map.put(\"default\", \"default\");\n categoryPrefMap = Collections.unmodifiableMap(map);\n\n categories = new HashMap<>();\n\n buildMatcher(patterns);\n\n entityList = null;\n }\n\n \/**\n * Only used for testing - uses a list of urls to populate a \"default\" category.\n * @param patterns\n *\/\n private void buildMatcher(String[] patterns) {\n final Trie defaultCategory;\n if (!categories.containsKey(\"default\")) {\n defaultCategory = Trie.createRootNode();\n categories.put(\"default\", defaultCategory);\n } else {\n defaultCategory = categories.get(\"default\");\n }\n\n for (final String pattern : patterns) {\n defaultCategory.put(FocusString.create(pattern).reverse());\n }\n\n enabledCategories.add(\"default\");\n }\n\n public Set getCategories() {\n return categories.keySet();\n }\n\n public void setCategoryEnabled(final String category, final boolean enabled) {\n if (WEBFONTS.equals(category)) {\n blockWebfonts = enabled;\n return;\n }\n\n if (!getCategories().contains(category)) {\n throw new IllegalArgumentException(\"Can't enable\/disable inexistant category\");\n }\n\n if (enabled) {\n if (enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already enabled\n return;\n } else {\n enabledCategories.add(category);\n previouslyUnmatched.clear();\n }\n } else {\n if (!enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already disabled\n return;\n } else {\n enabledCategories.remove(category);\n previouslyMatched.clear();\n }\n\n }\n }\n\n public boolean matches(final Uri resourceURI, final Uri pageURI) {\n final String path = resourceURI.getPath();\n\n if (path == null) {\n return false;\n }\n\n \/\/ We need to handle webfonts first: if they are blocked, then whitelists don't matter.\n \/\/ If they aren't blocked we still need to check domain blacklists below.\n if (blockWebfonts) {\n for (final String extension : WEBFONT_EXTENSIONS) {\n if (path.endsWith(extension)) {\n return true;\n }\n }\n }\n\n final String resourceURLString = resourceURI.toString();\n\n \/\/ Cached whitelisted items can be permitted now (but blacklisted needs to wait for the override \/ entity list)\n if (previouslyUnmatched.contains(resourceURLString)) {\n return false;\n }\n\n if (entityList != null &&\n entityList.isWhiteListed(pageURI, resourceURI)) {\n \/\/ We must not cache entityList items (and\/or if we did, we'd have to clear the cache\n \/\/ on every single location change)\n return false;\n }\n\n final String resourceHost = resourceURI.getHost();\n final String pageHost = pageURI.getHost();\n\n if (pageHost != null && pageHost.equals(resourceHost)) {\n return false;\n }\n\n if (previouslyMatched.contains(resourceURLString)) {\n return true;\n }\n\n final FocusString revhost = FocusString.create(resourceHost).reverse();\n\n for (final Map.Entry category : categories.entrySet()) {\n if (enabledCategories.contains(category.getKey())) {\n if (category.getValue().findNode(revhost) != null) {\n previouslyMatched.add(resourceURLString);\n return true;\n }\n }\n }\n\n previouslyUnmatched.add(resourceURLString);\n return false;\n }\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite loadDefaultPrefMap to improve execution time. Write the entire code and no other text in the response.\n\n### Concepts:\n[in] loadDefaultPrefMap function\n[+] android.support.v4.util.ArrayMap\n[-] HashMap\n\n### Given program:\n```java\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\npackage org.mozilla.focus.webkit.matcher;\n\n\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.annotation.VisibleForTesting;\nimport android.util.JsonReader;\n\nimport org.mozilla.focus.R;\nimport org.mozilla.focus.webkit.matcher.util.FocusString;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.nio.charset.StandardCharsets;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class UrlMatcher implements SharedPreferences.OnSharedPreferenceChangeListener {\n \/**\n * Map of pref to blocking category (preference key -> Blocklist category name).\n *\/\n private final Map categoryPrefMap;\n\n private static final String[] WEBFONT_EXTENSIONS = new String[]{\n \".woff2\",\n \".woff\",\n \".eot\",\n \".ttf\",\n \".otf\"\n };\n\n private static final String WEBFONTS = \"Webfonts\";\n\n private static Map loadDefaultPrefMap(final Context context) {\n Map tempMap = new HashMap<>(5);\n\n tempMap.put(context.getString(R.string.pref_key_privacy_block_ads), \"Advertising\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_analytics), \"Analytics\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_social), \"Social\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_other), \"Content\");\n\n \/\/ This is a \"fake\" category - webfont handling is independent of the blocklists\n tempMap.put(context.getString(R.string.pref_key_performance_block_webfonts), WEBFONTS);\n\n return Collections.unmodifiableMap(tempMap);\n }\n\n private final Map categories;\n private final Set enabledCategories = new HashSet<>();\n\n private final EntityList entityList;\n \/\/ A cached list of previously matched URLs. This MUST be cleared whenever items are removed from enabledCategories.\n private final HashSet previouslyMatched = new HashSet<>();\n \/\/ A cahced list of previously approved URLs. This MUST be cleared whenever items are added to enabledCategories.\n private final HashSet previouslyUnmatched = new HashSet<>();\n\n private boolean blockWebfonts = true;\n\n public static UrlMatcher loadMatcher(final Context context, final int blockListFile, final int[] blockListOverrides, final int entityListFile) {\n final Map categoryPrefMap = loadDefaultPrefMap(context);\n\n final Map categoryMap = new HashMap<>(5);\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListFile), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.BASE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse blacklist\");\n }\n\n if (blockListOverrides != null) {\n for (int i = 0; i < blockListOverrides.length; i++) {\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListOverrides[i]), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.OVERRIDE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse override blacklist\");\n }\n }\n }\n\n final EntityList entityList;\n try (final JsonReader jsonReader = new JsonReader(new InputStreamReader(context.getResources().openRawResource(entityListFile), StandardCharsets.UTF_8))){\n entityList = EntityListProcessor.getEntityMapFromJSON(jsonReader);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse entity list\");\n }\n\n return new UrlMatcher(context, categoryPrefMap, categoryMap, entityList);\n }\n\n \/* package-private *\/ UrlMatcher(final Context context,\n @NonNull final Map categoryPrefMap,\n @NonNull final Map categoryMap,\n @Nullable final EntityList entityList) {\n this.categoryPrefMap = categoryPrefMap;\n this.entityList = entityList;\n this.categories = categoryMap;\n\n \/\/ Ensure all categories have been declared, and enable by default (loadPrefs() will then\n \/\/ enabled\/disable categories that have actually been configured).\n for (final Map.Entry entry: categoryMap.entrySet()) {\n if (!categoryPrefMap.values().contains(entry.getKey())) {\n throw new IllegalArgumentException(\"categoryMap contains undeclared category\");\n }\n\n \/\/ Failsafe: enable all categories (we load preferences in the next step anyway)\n enabledCategories.add(entry.getKey());\n }\n\n loadPrefs(context);\n\n PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(this);\n }\n\n @Override\n public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String prefName) {\n final String categoryName = categoryPrefMap.get(prefName);\n\n if (categoryName != null) {\n final boolean prefValue = sharedPreferences.getBoolean(prefName, false);\n\n setCategoryEnabled(categoryName, prefValue);\n }\n }\n\n private void loadPrefs(final Context context) {\n final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n for (final Map.Entry entry : categoryPrefMap.entrySet()) {\n final boolean prefValue = prefs.getBoolean(entry.getKey(), true);\n setCategoryEnabled(entry.getValue(), prefValue);\n }\n }\n\n @VisibleForTesting UrlMatcher(final String[] patterns) {\n final Map map = new HashMap<>();\n map.put(\"default\", \"default\");\n categoryPrefMap = Collections.unmodifiableMap(map);\n\n categories = new HashMap<>();\n\n buildMatcher(patterns);\n\n entityList = null;\n }\n\n \/**\n * Only used for testing - uses a list of urls to populate a \"default\" category.\n * @param patterns\n *\/\n private void buildMatcher(String[] patterns) {\n final Trie defaultCategory;\n if (!categories.containsKey(\"default\")) {\n defaultCategory = Trie.createRootNode();\n categories.put(\"default\", defaultCategory);\n } else {\n defaultCategory = categories.get(\"default\");\n }\n\n for (final String pattern : patterns) {\n defaultCategory.put(FocusString.create(pattern).reverse());\n }\n\n enabledCategories.add(\"default\");\n }\n\n public Set getCategories() {\n return categories.keySet();\n }\n\n public void setCategoryEnabled(final String category, final boolean enabled) {\n if (WEBFONTS.equals(category)) {\n blockWebfonts = enabled;\n return;\n }\n\n if (!getCategories().contains(category)) {\n throw new IllegalArgumentException(\"Can't enable\/disable inexistant category\");\n }\n\n if (enabled) {\n if (enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already enabled\n return;\n } else {\n enabledCategories.add(category);\n previouslyUnmatched.clear();\n }\n } else {\n if (!enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already disabled\n return;\n } else {\n enabledCategories.remove(category);\n previouslyMatched.clear();\n }\n\n }\n }\n\n public boolean matches(final Uri resourceURI, final Uri pageURI) {\n final String path = resourceURI.getPath();\n\n if (path == null) {\n return false;\n }\n\n \/\/ We need to handle webfonts first: if they are blocked, then whitelists don't matter.\n \/\/ If they aren't blocked we still need to check domain blacklists below.\n if (blockWebfonts) {\n for (final String extension : WEBFONT_EXTENSIONS) {\n if (path.endsWith(extension)) {\n return true;\n }\n }\n }\n\n final String resourceURLString = resourceURI.toString();\n\n \/\/ Cached whitelisted items can be permitted now (but blacklisted needs to wait for the override \/ entity list)\n if (previouslyUnmatched.contains(resourceURLString)) {\n return false;\n }\n\n if (entityList != null &&\n entityList.isWhiteListed(pageURI, resourceURI)) {\n \/\/ We must not cache entityList items (and\/or if we did, we'd have to clear the cache\n \/\/ on every single location change)\n return false;\n }\n\n final String resourceHost = resourceURI.getHost();\n final String pageHost = pageURI.getHost();\n\n if (pageHost != null && pageHost.equals(resourceHost)) {\n return false;\n }\n\n if (previouslyMatched.contains(resourceURLString)) {\n return true;\n }\n\n final FocusString revhost = FocusString.create(resourceHost).reverse();\n\n for (final Map.Entry category : categories.entrySet()) {\n if (enabledCategories.contains(category.getKey())) {\n if (category.getValue().findNode(revhost) != null) {\n previouslyMatched.add(resourceURLString);\n return true;\n }\n }\n }\n\n previouslyUnmatched.add(resourceURLString);\n return false;\n }\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage org.fdroid.fdroid.net;\n\nimport android.net.Uri;\nimport android.support.annotation.NonNull;\nimport android.text.format.DateUtils;\nimport org.fdroid.fdroid.ProgressListener;\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.ConnectException;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_CONNECTION_FAILED = \"org.fdroid.fdroid.net.Downloader.action.CONNECTION_FAILED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n public static final String EXTRA_ERROR_MESSAGE = \"org.fdroid.fdroid.net.Downloader.extra.ERROR_MESSAGE\";\n public static final String EXTRA_REPO_ID = \"org.fdroid.fdroid.net.Downloader.extra.REPO_ID\";\n public static final String EXTRA_CANONICAL_URL = \"org.fdroid.fdroid.net.Downloader.extra.CANONICAL_URL\";\n public static final String EXTRA_MIRROR_URL = \"org.fdroid.fdroid.net.Downloader.extra.MIRROR_URL\";\n\n public static final int DEFAULT_TIMEOUT = 10000;\n public static final int SECOND_TIMEOUT = (int) DateUtils.MINUTE_IN_MILLIS;\n public static final int LONGEST_TIMEOUT = 600000; \/\/ 10 minutes\n\n private volatile boolean cancelled = false;\n private volatile long bytesRead;\n private volatile long totalBytes;\n\n public final File outputFile;\n\n final String urlString;\n String cacheTag;\n boolean notFound;\n\n private volatile int timeout = DEFAULT_TIMEOUT;\n\n \/**\n * For sending download progress, should only be called in {@link #progressTask}\n *\/\n private volatile ProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(Uri uri, File destFile) {\n this.urlString = uri.toString();\n outputFile = destFile;\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(ProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n public void setTimeout(int ms) {\n timeout = ms;\n }\n\n public int getTimeout() {\n return timeout;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract long totalDownloadSize();\n\n public abstract void download() throws ConnectException, IOException, InterruptedException;\n\n \/**\n * @return whether the requested file was not found in the repo (e.g. HTTP 404 Not Found)\n *\/\n public boolean isNotFound() {\n return notFound;\n }\n\n void downloadFromStream(int bufferSize, boolean resumable) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n OutputStream outputStream = new FileOutputStream(outputFile, resumable);\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize, outputStream);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n *\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize, OutputStream output)\n throws IOException, InterruptedException {\n Timer timer = new Timer();\n try {\n bytesRead = 0;\n totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n timer.scheduleAtFixedRate(progressTask, 0, 100);\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n bytesRead += count;\n output.write(buffer, 0, count);\n }\n } finally {\n downloaderProgressListener = null;\n timer.cancel();\n timer.purge();\n output.flush();\n output.close();\n }\n }\n\n \/**\n * Send progress updates on a timer to avoid flooding receivers with pointless events.\n *\/\n private final TimerTask progressTask = new TimerTask() {\n private long lastBytesRead = Long.MIN_VALUE;\n private long lastTotalBytes = Long.MIN_VALUE;\n\n @Override\n public void run() {\n if (downloaderProgressListener != null\n && (bytesRead != lastBytesRead || totalBytes != lastTotalBytes)) {\n downloaderProgressListener.onProgress(bytesRead, totalBytes);\n lastBytesRead = bytesRead;\n lastTotalBytes = totalBytes;\n }\n }\n };\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(@NonNull byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(@NonNull byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n\n\nCode-B:\npackage org.fdroid.fdroid.net;\n\nimport android.net.Uri;\nimport android.support.annotation.NonNull;\nimport android.text.format.DateUtils;\nimport org.fdroid.fdroid.ProgressListener;\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.ConnectException;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_CONNECTION_FAILED = \"org.fdroid.fdroid.net.Downloader.action.CONNECTION_FAILED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n public static final String EXTRA_ERROR_MESSAGE = \"org.fdroid.fdroid.net.Downloader.extra.ERROR_MESSAGE\";\n public static final String EXTRA_REPO_ID = \"org.fdroid.fdroid.net.Downloader.extra.REPO_ID\";\n public static final String EXTRA_CANONICAL_URL = \"org.fdroid.fdroid.net.Downloader.extra.CANONICAL_URL\";\n public static final String EXTRA_MIRROR_URL = \"org.fdroid.fdroid.net.Downloader.extra.MIRROR_URL\";\n\n public static final int DEFAULT_TIMEOUT = 10000;\n public static final int SECOND_TIMEOUT = (int) DateUtils.MINUTE_IN_MILLIS;\n public static final int LONGEST_TIMEOUT = 600000; \/\/ 10 minutes\n\n private volatile boolean cancelled = false;\n private volatile long bytesRead;\n private volatile long totalBytes;\n\n public final File outputFile;\n\n final String urlString;\n String cacheTag;\n boolean notFound;\n\n private volatile int timeout = DEFAULT_TIMEOUT;\n\n \/**\n * For sending download progress, should only be called in {@link #progressTask}\n *\/\n private volatile ProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(Uri uri, File destFile) {\n this.urlString = uri.toString();\n outputFile = destFile;\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(ProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n public void setTimeout(int ms) {\n timeout = ms;\n }\n\n public int getTimeout() {\n return timeout;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract long totalDownloadSize();\n\n public abstract void download() throws ConnectException, IOException, InterruptedException;\n\n \/**\n * @return whether the requested file was not found in the repo (e.g. HTTP 404 Not Found)\n *\/\n public boolean isNotFound() {\n return notFound;\n }\n\n void downloadFromStream(int bufferSize, boolean resumable) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n OutputStream outputStream = new FileOutputStream(outputFile, resumable);\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize, outputStream);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n *\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize, OutputStream output)\n throws IOException, InterruptedException {\n Timer timer = new Timer();\n try {\n bytesRead = 0;\n totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n timer.scheduleAtFixedRate(progressTask, 0, 100);\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n bytesRead += count;\n output.write(buffer, 0, count);\n }\n } finally {\n downloaderProgressListener = null;\n timer.cancel();\n timer.purge();\n output.flush();\n output.close();\n }\n }\n\n \/**\n * Send progress updates on a timer to avoid flooding receivers with pointless events.\n *\/\n private final TimerTask progressTask = new TimerTask() {\n @Override\n public void run() {\n if (downloaderProgressListener != null) {\n downloaderProgressListener.onProgress(bytesRead, totalBytes);\n }\n }\n };\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(@NonNull byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(@NonNull byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage org.fdroid.fdroid.net;\n\nimport android.net.Uri;\nimport android.support.annotation.NonNull;\nimport android.text.format.DateUtils;\nimport org.fdroid.fdroid.ProgressListener;\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.ConnectException;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_CONNECTION_FAILED = \"org.fdroid.fdroid.net.Downloader.action.CONNECTION_FAILED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n public static final String EXTRA_ERROR_MESSAGE = \"org.fdroid.fdroid.net.Downloader.extra.ERROR_MESSAGE\";\n public static final String EXTRA_REPO_ID = \"org.fdroid.fdroid.net.Downloader.extra.REPO_ID\";\n public static final String EXTRA_CANONICAL_URL = \"org.fdroid.fdroid.net.Downloader.extra.CANONICAL_URL\";\n public static final String EXTRA_MIRROR_URL = \"org.fdroid.fdroid.net.Downloader.extra.MIRROR_URL\";\n\n public static final int DEFAULT_TIMEOUT = 10000;\n public static final int SECOND_TIMEOUT = (int) DateUtils.MINUTE_IN_MILLIS;\n public static final int LONGEST_TIMEOUT = 600000; \/\/ 10 minutes\n\n private volatile boolean cancelled = false;\n private volatile long bytesRead;\n private volatile long totalBytes;\n\n public final File outputFile;\n\n final String urlString;\n String cacheTag;\n boolean notFound;\n\n private volatile int timeout = DEFAULT_TIMEOUT;\n\n \/**\n * For sending download progress, should only be called in {@link #progressTask}\n *\/\n private volatile ProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(Uri uri, File destFile) {\n this.urlString = uri.toString();\n outputFile = destFile;\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(ProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n public void setTimeout(int ms) {\n timeout = ms;\n }\n\n public int getTimeout() {\n return timeout;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract long totalDownloadSize();\n\n public abstract void download() throws ConnectException, IOException, InterruptedException;\n\n \/**\n * @return whether the requested file was not found in the repo (e.g. HTTP 404 Not Found)\n *\/\n public boolean isNotFound() {\n return notFound;\n }\n\n void downloadFromStream(int bufferSize, boolean resumable) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n OutputStream outputStream = new FileOutputStream(outputFile, resumable);\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize, outputStream);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n *\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize, OutputStream output)\n throws IOException, InterruptedException {\n Timer timer = new Timer();\n try {\n bytesRead = 0;\n totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n timer.scheduleAtFixedRate(progressTask, 0, 100);\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n bytesRead += count;\n output.write(buffer, 0, count);\n }\n } finally {\n downloaderProgressListener = null;\n timer.cancel();\n timer.purge();\n output.flush();\n output.close();\n }\n }\n\n \/**\n * Send progress updates on a timer to avoid flooding receivers with pointless events.\n *\/\n private final TimerTask progressTask = new TimerTask() {\n @Override\n public void run() {\n if (downloaderProgressListener != null) {\n downloaderProgressListener.onProgress(bytesRead, totalBytes);\n }\n }\n };\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(@NonNull byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(@NonNull byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n\n\nCode-B:\npackage org.fdroid.fdroid.net;\n\nimport android.net.Uri;\nimport android.support.annotation.NonNull;\nimport android.text.format.DateUtils;\nimport org.fdroid.fdroid.ProgressListener;\nimport org.fdroid.fdroid.Utils;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.ConnectException;\nimport java.util.Timer;\nimport java.util.TimerTask;\n\npublic abstract class Downloader {\n\n private static final String TAG = \"Downloader\";\n\n public static final String ACTION_STARTED = \"org.fdroid.fdroid.net.Downloader.action.STARTED\";\n public static final String ACTION_PROGRESS = \"org.fdroid.fdroid.net.Downloader.action.PROGRESS\";\n public static final String ACTION_INTERRUPTED = \"org.fdroid.fdroid.net.Downloader.action.INTERRUPTED\";\n public static final String ACTION_CONNECTION_FAILED = \"org.fdroid.fdroid.net.Downloader.action.CONNECTION_FAILED\";\n public static final String ACTION_COMPLETE = \"org.fdroid.fdroid.net.Downloader.action.COMPLETE\";\n\n public static final String EXTRA_DOWNLOAD_PATH = \"org.fdroid.fdroid.net.Downloader.extra.DOWNLOAD_PATH\";\n public static final String EXTRA_BYTES_READ = \"org.fdroid.fdroid.net.Downloader.extra.BYTES_READ\";\n public static final String EXTRA_TOTAL_BYTES = \"org.fdroid.fdroid.net.Downloader.extra.TOTAL_BYTES\";\n public static final String EXTRA_ERROR_MESSAGE = \"org.fdroid.fdroid.net.Downloader.extra.ERROR_MESSAGE\";\n public static final String EXTRA_REPO_ID = \"org.fdroid.fdroid.net.Downloader.extra.REPO_ID\";\n public static final String EXTRA_CANONICAL_URL = \"org.fdroid.fdroid.net.Downloader.extra.CANONICAL_URL\";\n public static final String EXTRA_MIRROR_URL = \"org.fdroid.fdroid.net.Downloader.extra.MIRROR_URL\";\n\n public static final int DEFAULT_TIMEOUT = 10000;\n public static final int SECOND_TIMEOUT = (int) DateUtils.MINUTE_IN_MILLIS;\n public static final int LONGEST_TIMEOUT = 600000; \/\/ 10 minutes\n\n private volatile boolean cancelled = false;\n private volatile long bytesRead;\n private volatile long totalBytes;\n\n public final File outputFile;\n\n final String urlString;\n String cacheTag;\n boolean notFound;\n\n private volatile int timeout = DEFAULT_TIMEOUT;\n\n \/**\n * For sending download progress, should only be called in {@link #progressTask}\n *\/\n private volatile ProgressListener downloaderProgressListener;\n\n protected abstract InputStream getDownloadersInputStream() throws IOException;\n\n protected abstract void close();\n\n Downloader(Uri uri, File destFile) {\n this.urlString = uri.toString();\n outputFile = destFile;\n }\n\n public final InputStream getInputStream() throws IOException {\n return new WrappedInputStream(getDownloadersInputStream());\n }\n\n public void setListener(ProgressListener listener) {\n this.downloaderProgressListener = listener;\n }\n\n public void setTimeout(int ms) {\n timeout = ms;\n }\n\n public int getTimeout() {\n return timeout;\n }\n\n \/**\n * If you ask for the cacheTag before calling download(), you will get the\n * same one you passed in (if any). If you call it after download(), you\n * will get the new cacheTag from the server, or null if there was none.\n *\/\n public String getCacheTag() {\n return cacheTag;\n }\n\n \/**\n * If this cacheTag matches that returned by the server, then no download will\n * take place, and a status code of 304 will be returned by download().\n *\/\n public void setCacheTag(String cacheTag) {\n this.cacheTag = cacheTag;\n }\n\n public abstract boolean hasChanged();\n\n protected abstract long totalDownloadSize();\n\n public abstract void download() throws ConnectException, IOException, InterruptedException;\n\n \/**\n * @return whether the requested file was not found in the repo (e.g. HTTP 404 Not Found)\n *\/\n public boolean isNotFound() {\n return notFound;\n }\n\n void downloadFromStream(int bufferSize, boolean resumable) throws IOException, InterruptedException {\n Utils.debugLog(TAG, \"Downloading from stream\");\n InputStream input = null;\n OutputStream outputStream = new FileOutputStream(outputFile, resumable);\n try {\n input = getInputStream();\n\n \/\/ Getting the input stream is slow(ish) for HTTP downloads, so we'll check if\n \/\/ we were interrupted before proceeding to the download.\n throwExceptionIfInterrupted();\n\n copyInputToOutputStream(input, bufferSize, outputStream);\n } finally {\n Utils.closeQuietly(outputStream);\n Utils.closeQuietly(input);\n }\n\n \/\/ Even if we have completely downloaded the file, we should probably respect\n \/\/ the wishes of the user who wanted to cancel us.\n throwExceptionIfInterrupted();\n }\n\n \/**\n * After every network operation that could take a while, we will check if an\n * interrupt occured during that blocking operation. The goal is to ensure we\n * don't move onto another slow, network operation if we have cancelled the\n * download.\n *\n * @throws InterruptedException\n *\/\n private void throwExceptionIfInterrupted() throws InterruptedException {\n if (cancelled) {\n Utils.debugLog(TAG, \"Received interrupt, cancelling download\");\n throw new InterruptedException();\n }\n }\n\n \/**\n * Cancel a running download, triggering an {@link InterruptedException}\n *\/\n public void cancelDownload() {\n cancelled = true;\n }\n\n \/**\n * This copies the downloaded data from the InputStream to the OutputStream,\n * keeping track of the number of bytes that have flowed through for the\n * progress counter.\n *\/\n private void copyInputToOutputStream(InputStream input, int bufferSize, OutputStream output)\n throws IOException, InterruptedException {\n Timer timer = new Timer();\n try {\n bytesRead = 0;\n totalBytes = totalDownloadSize();\n byte[] buffer = new byte[bufferSize];\n\n timer.scheduleAtFixedRate(progressTask, 0, 100);\n\n \/\/ Getting the total download size could potentially take time, depending on how\n \/\/ it is implemented, so we may as well check this before we proceed.\n throwExceptionIfInterrupted();\n\n while (true) {\n\n int count;\n if (input.available() > 0) {\n int readLength = Math.min(input.available(), buffer.length);\n count = input.read(buffer, 0, readLength);\n } else {\n count = input.read(buffer);\n }\n\n throwExceptionIfInterrupted();\n\n if (count == -1) {\n Utils.debugLog(TAG, \"Finished downloading from stream\");\n break;\n }\n bytesRead += count;\n output.write(buffer, 0, count);\n }\n } finally {\n downloaderProgressListener = null;\n timer.cancel();\n timer.purge();\n output.flush();\n output.close();\n }\n }\n\n \/**\n * Send progress updates on a timer to avoid flooding receivers with pointless events.\n *\/\n private final TimerTask progressTask = new TimerTask() {\n private long lastBytesRead = Long.MIN_VALUE;\n private long lastTotalBytes = Long.MIN_VALUE;\n\n @Override\n public void run() {\n if (downloaderProgressListener != null\n && (bytesRead != lastBytesRead || totalBytes != lastTotalBytes)) {\n downloaderProgressListener.onProgress(bytesRead, totalBytes);\n lastBytesRead = bytesRead;\n lastTotalBytes = totalBytes;\n }\n }\n };\n\n \/**\n * Overrides every method in {@link InputStream} and delegates to the wrapped stream.\n * The only difference is that when we call the {@link WrappedInputStream#close()} method,\n * after delegating to the wrapped stream we invoke the {@link Downloader#close()} method\n * on the {@link Downloader} which created this.\n *\/\n private class WrappedInputStream extends InputStream {\n\n private final InputStream toWrap;\n\n WrappedInputStream(InputStream toWrap) {\n super();\n this.toWrap = toWrap;\n }\n\n @Override\n public void close() throws IOException {\n toWrap.close();\n Downloader.this.close();\n }\n\n @Override\n public int available() throws IOException {\n return toWrap.available();\n }\n\n @Override\n public void mark(int readlimit) {\n toWrap.mark(readlimit);\n }\n\n @Override\n public boolean markSupported() {\n return toWrap.markSupported();\n }\n\n @Override\n public int read(@NonNull byte[] buffer) throws IOException {\n return toWrap.read(buffer);\n }\n\n @Override\n public int read(@NonNull byte[] buffer, int byteOffset, int byteCount) throws IOException {\n return toWrap.read(buffer, byteOffset, byteCount);\n }\n\n @Override\n public synchronized void reset() throws IOException {\n toWrap.reset();\n }\n\n @Override\n public long skip(long byteCount) throws IOException {\n return toWrap.skip(byteCount);\n }\n\n @Override\n public int read() throws IOException {\n return toWrap.read();\n }\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/erikusaj\/fdroidTvClient\/commit\/0e47ac690053a8fddc2b1e3d75557f63629610c9","commit_message":"'\\\\\"Slightly speed up getAndroidVersionName by using a static array\\\\n\\\\\"'","source_code":"\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport android.content.Context;\n\nimport android.content.pm.PackageInfo;\nimport android.text.TextUtils;\nimport android.util.DisplayMetrics;\nimport android.util.Log;\nimport com.nostra13.universalimageloader.utils.StorageUtils;\n\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.security.cert.Certificate;\nimport java.security.cert.CertificateEncodingException;\nimport java.text.SimpleDateFormat;\nimport java.security.MessageDigest;\nimport java.util.*;\n\npublic final class Utils {\n\n public static final int BUFFER_SIZE = 4096;\n\n \/\/ The date format used for storing dates (e.g. lastupdated, added) in the\n \/\/ database.\n public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.ENGLISH);\n\n private static final String[] FRIENDLY_SIZE_FORMAT = {\n \"%.0f B\", \"%.0f KiB\", \"%.1f MiB\", \"%.2f GiB\" };\n\n public static final SimpleDateFormat LOG_DATE_FORMAT =\n new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.ENGLISH);\n\n public static String getIconsDir(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n String iconsDir;\n if (metrics.densityDpi >= 640) {\n iconsDir = \"\/icons-640\/\";\n } else if (metrics.densityDpi >= 480) {\n iconsDir = \"\/icons-480\/\";\n } else if (metrics.densityDpi >= 320) {\n iconsDir = \"\/icons-320\/\";\n } else if (metrics.densityDpi >= 240) {\n iconsDir = \"\/icons-240\/\";\n } else if (metrics.densityDpi >= 160) {\n iconsDir = \"\/icons-160\/\";\n } else {\n iconsDir = \"\/icons-120\/\";\n }\n return iconsDir;\n }\n\n public static void copy(InputStream input, OutputStream output)\n throws IOException {\n copy(input, output, null, null);\n }\n\n public static void copy(InputStream input, OutputStream output,\n ProgressListener progressListener,\n ProgressListener.Event templateProgressEvent)\n throws IOException {\n byte[] buffer = new byte[BUFFER_SIZE];\n int bytesRead = 0;\n while (true) {\n int count = input.read(buffer);\n if (count == -1) {\n break;\n }\n if (progressListener != null) {\n bytesRead += count;\n templateProgressEvent.progress = bytesRead;\n progressListener.onProgress(templateProgressEvent);\n }\n output.write(buffer, 0, count);\n }\n output.flush();\n }\n\n public static void closeQuietly(Closeable closeable) {\n if (closeable == null) {\n return;\n }\n try {\n closeable.close();\n } catch (IOException ioe) {\n \/\/ ignore\n }\n }\n\n public static String getFriendlySize(int size) {\n double s = size;\n int i = 0;\n while (i < FRIENDLY_SIZE_FORMAT.length - 1 && s >= 1024) {\n s = (100 * s \/ 1024) \/ 100.0;\n i++;\n }\n return String.format(FRIENDLY_SIZE_FORMAT[i], s);\n }\n\n public static String getAndroidVersionName(int sdkLevel) {\n if (sdkLevel < 1) return null;\n switch (sdkLevel) {\n case 19: return \"4.4\";\n case 18: return \"4.3\";\n case 17: return \"4.2\";\n case 16: return \"4.1\";\n case 15: return \"4.0.3\";\n case 14: return \"4.0\";\n case 13: return \"3.2\";\n case 12: return \"3.1\";\n case 11: return \"3.0\";\n case 10: return \"2.3.3\";\n case 9: return \"2.3\";\n case 8: return \"2.2\";\n case 7: return \"2.1\";\n case 6: return \"2.0.1\";\n case 5: return \"2.0\";\n case 4: return \"1.6\";\n case 3: return \"1.5\";\n case 2: return \"1.1\";\n case 1: return \"1.0\";\n default: return \"?\";\n }\n }\n\n public static int countSubstringOccurrence(File file, String substring) throws IOException {\n int count = 0;\n FileReader input = null;\n try {\n int currentSubstringIndex = 0;\n char[] buffer = new char[4096];\n\n input = new FileReader(file);\n int numRead = input.read(buffer);\n while(numRead != -1) {\n\n for (char c : buffer) {\n if (c == substring.charAt(currentSubstringIndex)) {\n currentSubstringIndex ++;\n if (currentSubstringIndex == substring.length()) {\n count ++;\n currentSubstringIndex = 0;\n }\n } else {\n currentSubstringIndex = 0;\n }\n }\n numRead = input.read(buffer);\n }\n } finally {\n closeQuietly(input);\n }\n return count;\n }\n\n \/\/ return a fingerprint formatted for display\n public static String formatFingerprint(String fingerprint) {\n if (fingerprint.length() != 62) \/\/ SHA-256 is 62 hex chars\n return \"BAD FINGERPRINT\";\n String displayFP = fingerprint.substring(0, 2);\n for (int i = 2; i < fingerprint.length(); i = i + 2)\n displayFP += \" \" + fingerprint.substring(i, i + 2);\n return displayFP;\n }\n\n public static File getApkCacheDir(Context context) {\n File apkCacheDir = new File(\n StorageUtils.getCacheDirectory(context, true), \"apks\");\n if (!apkCacheDir.exists()) {\n apkCacheDir.mkdir();\n }\n return apkCacheDir;\n }\n\n public static Map getInstalledApps(Context context) {\n return installedApkCache.getApks(context);\n }\n\n public static void clearInstalledApksCache() {\n installedApkCache.emptyCache();\n }\n\n public static String calcFingerprint(String keyHexString) {\n if (TextUtils.isEmpty(keyHexString))\n return null;\n else\n return calcFingerprint(Hasher.unhex(keyHexString));\n }\n\n public static String calcFingerprint(Certificate cert) {\n try {\n return calcFingerprint(cert.getEncoded());\n } catch (CertificateEncodingException e) {\n return null;\n }\n }\n\n public static String calcFingerprint(byte[] key) {\n String ret = null;\n try {\n \/\/ keytool -list -v gives you the SHA-256 fingerprint\n MessageDigest digest = MessageDigest.getInstance(\"SHA-256\");\n digest.update(key);\n byte[] fingerprint = digest.digest();\n Formatter formatter = new Formatter(new StringBuilder());\n for (int i = 1; i < fingerprint.length; i++) {\n formatter.format(\"%02X\", fingerprint[i]);\n }\n ret = formatter.toString();\n formatter.close();\n } catch (Exception e) {\n Log.w(\"FDroid\", \"Unable to get certificate fingerprint.\\n\"\n + Log.getStackTraceString(e));\n }\n return ret;\n }\n\n public static class CommaSeparatedList implements Iterable {\n private String value;\n\n private CommaSeparatedList(String list) {\n value = list;\n }\n\n public static CommaSeparatedList make(List list) {\n if (list == null || list.size() == 0)\n return null;\n else {\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < list.size(); i ++) {\n if (i > 0) {\n sb.append(',');\n }\n sb.append(list.get(i));\n }\n return new CommaSeparatedList(sb.toString());\n }\n }\n\n public static CommaSeparatedList make(String list) {\n if (list == null || list.length() == 0)\n return null;\n else\n return new CommaSeparatedList(list);\n }\n\n public static String str(CommaSeparatedList instance) {\n return (instance == null ? null : instance.toString());\n }\n\n @Override\n public String toString() {\n return value;\n }\n\n public String toPrettyString() {\n return value.replaceAll(\",\", \", \");\n }\n\n @Override\n public Iterator iterator() {\n TextUtils.SimpleStringSplitter splitter = new TextUtils.SimpleStringSplitter(',');\n splitter.setString(value);\n return splitter.iterator();\n }\n\n public boolean contains(String v) {\n for (String s : this) {\n if (s.equals(v))\n return true;\n }\n return false;\n }\n }\n\n private static InstalledApkCache installedApkCache = null;\n\n \/**\n * We do a lot of querying of the installed app's. As a result, we like\n * to cache this information quite heavily (and flush the cache when new\n * apps are installed). The caching implementation needs to be setup like\n * this so that it is possible to mock for testing purposes.\n *\/\n public static void setupInstalledApkCache(InstalledApkCache cache) {\n installedApkCache = cache;\n }\n\n public static class InstalledApkCache {\n\n protected Map installedApks = null;\n\n protected Map buildAppList(Context context) {\n Map info = new HashMap();\n Log.d(\"FDroid\", \"Reading installed packages\");\n List installedPackages = context.getPackageManager().getInstalledPackages(0);\n for (PackageInfo appInfo : installedPackages) {\n info.put(appInfo.packageName, appInfo);\n }\n return info;\n }\n\n public Map getApks(Context context) {\n if (installedApks == null) {\n installedApks = buildAppList(context);\n }\n return installedApks;\n }\n\n public void emptyCache() {\n installedApks = null;\n }\n\n }\n\n\n}\n","target_code":"\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport android.content.Context;\n\nimport android.content.pm.PackageInfo;\nimport android.text.TextUtils;\nimport android.util.DisplayMetrics;\nimport android.util.Log;\nimport com.nostra13.universalimageloader.utils.StorageUtils;\n\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.security.cert.Certificate;\nimport java.security.cert.CertificateEncodingException;\nimport java.text.SimpleDateFormat;\nimport java.security.MessageDigest;\nimport java.util.*;\n\npublic final class Utils {\n\n public static final int BUFFER_SIZE = 4096;\n\n \/\/ The date format used for storing dates (e.g. lastupdated, added) in the\n \/\/ database.\n public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.ENGLISH);\n\n private static final String[] FRIENDLY_SIZE_FORMAT = {\n \"%.0f B\", \"%.0f KiB\", \"%.1f MiB\", \"%.2f GiB\" };\n\n public static final SimpleDateFormat LOG_DATE_FORMAT =\n new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.ENGLISH);\n\n public static String getIconsDir(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n String iconsDir;\n if (metrics.densityDpi >= 640) {\n iconsDir = \"\/icons-640\/\";\n } else if (metrics.densityDpi >= 480) {\n iconsDir = \"\/icons-480\/\";\n } else if (metrics.densityDpi >= 320) {\n iconsDir = \"\/icons-320\/\";\n } else if (metrics.densityDpi >= 240) {\n iconsDir = \"\/icons-240\/\";\n } else if (metrics.densityDpi >= 160) {\n iconsDir = \"\/icons-160\/\";\n } else {\n iconsDir = \"\/icons-120\/\";\n }\n return iconsDir;\n }\n\n public static void copy(InputStream input, OutputStream output)\n throws IOException {\n copy(input, output, null, null);\n }\n\n public static void copy(InputStream input, OutputStream output,\n ProgressListener progressListener,\n ProgressListener.Event templateProgressEvent)\n throws IOException {\n byte[] buffer = new byte[BUFFER_SIZE];\n int bytesRead = 0;\n while (true) {\n int count = input.read(buffer);\n if (count == -1) {\n break;\n }\n if (progressListener != null) {\n bytesRead += count;\n templateProgressEvent.progress = bytesRead;\n progressListener.onProgress(templateProgressEvent);\n }\n output.write(buffer, 0, count);\n }\n output.flush();\n }\n\n public static void closeQuietly(Closeable closeable) {\n if (closeable == null) {\n return;\n }\n try {\n closeable.close();\n } catch (IOException ioe) {\n \/\/ ignore\n }\n }\n\n public static String getFriendlySize(int size) {\n double s = size;\n int i = 0;\n while (i < FRIENDLY_SIZE_FORMAT.length - 1 && s >= 1024) {\n s = (100 * s \/ 1024) \/ 100.0;\n i++;\n }\n return String.format(FRIENDLY_SIZE_FORMAT[i], s);\n }\n\n private static final String[] androidVersionNames = {\n \"?\", \/\/ 0, undefined\n \"1.0\", \/\/ 1\n \"1.1\", \/\/ 2\n \"1.5\", \/\/ 3\n \"1.6\", \/\/ 4\n \"2.0\", \/\/ 5\n \"2.0.1\", \/\/ 6\n \"2.1\", \/\/ 7\n \"2.2\", \/\/ 8\n \"2.3\", \/\/ 9\n \"2.3.3\", \/\/ 10\n \"3.0\", \/\/ 11\n \"3.1\", \/\/ 12\n \"3.2\", \/\/ 13\n \"4.0\", \/\/ 14\n \"4.0.3\", \/\/ 15\n \"4.1\", \/\/ 16\n \"4.2\", \/\/ 17\n \"4.3\", \/\/ 18\n \"4.4\" \/\/ 19\n };\n\n public static String getAndroidVersionName(int sdkLevel) {\n if (sdkLevel < 0 || sdkLevel > 19) return androidVersionNames[0];\n return androidVersionNames[sdkLevel];\n }\n\n public static int countSubstringOccurrence(File file, String substring) throws IOException {\n int count = 0;\n FileReader input = null;\n try {\n int currentSubstringIndex = 0;\n char[] buffer = new char[4096];\n\n input = new FileReader(file);\n int numRead = input.read(buffer);\n while(numRead != -1) {\n\n for (char c : buffer) {\n if (c == substring.charAt(currentSubstringIndex)) {\n currentSubstringIndex ++;\n if (currentSubstringIndex == substring.length()) {\n count ++;\n currentSubstringIndex = 0;\n }\n } else {\n currentSubstringIndex = 0;\n }\n }\n numRead = input.read(buffer);\n }\n } finally {\n closeQuietly(input);\n }\n return count;\n }\n\n \/\/ return a fingerprint formatted for display\n public static String formatFingerprint(String fingerprint) {\n if (fingerprint.length() != 62) \/\/ SHA-256 is 62 hex chars\n return \"BAD FINGERPRINT\";\n String displayFP = fingerprint.substring(0, 2);\n for (int i = 2; i < fingerprint.length(); i = i + 2)\n displayFP += \" \" + fingerprint.substring(i, i + 2);\n return displayFP;\n }\n\n public static File getApkCacheDir(Context context) {\n File apkCacheDir = new File(\n StorageUtils.getCacheDirectory(context, true), \"apks\");\n if (!apkCacheDir.exists()) {\n apkCacheDir.mkdir();\n }\n return apkCacheDir;\n }\n\n public static Map getInstalledApps(Context context) {\n return installedApkCache.getApks(context);\n }\n\n public static void clearInstalledApksCache() {\n installedApkCache.emptyCache();\n }\n\n public static String calcFingerprint(String keyHexString) {\n if (TextUtils.isEmpty(keyHexString))\n return null;\n else\n return calcFingerprint(Hasher.unhex(keyHexString));\n }\n\n public static String calcFingerprint(Certificate cert) {\n try {\n return calcFingerprint(cert.getEncoded());\n } catch (CertificateEncodingException e) {\n return null;\n }\n }\n\n public static String calcFingerprint(byte[] key) {\n String ret = null;\n try {\n \/\/ keytool -list -v gives you the SHA-256 fingerprint\n MessageDigest digest = MessageDigest.getInstance(\"SHA-256\");\n digest.update(key);\n byte[] fingerprint = digest.digest();\n Formatter formatter = new Formatter(new StringBuilder());\n for (int i = 1; i < fingerprint.length; i++) {\n formatter.format(\"%02X\", fingerprint[i]);\n }\n ret = formatter.toString();\n formatter.close();\n } catch (Exception e) {\n Log.w(\"FDroid\", \"Unable to get certificate fingerprint.\\n\"\n + Log.getStackTraceString(e));\n }\n return ret;\n }\n\n public static class CommaSeparatedList implements Iterable {\n private String value;\n\n private CommaSeparatedList(String list) {\n value = list;\n }\n\n public static CommaSeparatedList make(List list) {\n if (list == null || list.size() == 0)\n return null;\n else {\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < list.size(); i ++) {\n if (i > 0) {\n sb.append(',');\n }\n sb.append(list.get(i));\n }\n return new CommaSeparatedList(sb.toString());\n }\n }\n\n public static CommaSeparatedList make(String list) {\n if (list == null || list.length() == 0)\n return null;\n else\n return new CommaSeparatedList(list);\n }\n\n public static String str(CommaSeparatedList instance) {\n return (instance == null ? null : instance.toString());\n }\n\n @Override\n public String toString() {\n return value;\n }\n\n public String toPrettyString() {\n return value.replaceAll(\",\", \", \");\n }\n\n @Override\n public Iterator iterator() {\n TextUtils.SimpleStringSplitter splitter = new TextUtils.SimpleStringSplitter(',');\n splitter.setString(value);\n return splitter.iterator();\n }\n\n public boolean contains(String v) {\n for (String s : this) {\n if (s.equals(v))\n return true;\n }\n return false;\n }\n }\n\n private static InstalledApkCache installedApkCache = null;\n\n \/**\n * We do a lot of querying of the installed app's. As a result, we like\n * to cache this information quite heavily (and flush the cache when new\n * apps are installed). The caching implementation needs to be setup like\n * this so that it is possible to mock for testing purposes.\n *\/\n public static void setupInstalledApkCache(InstalledApkCache cache) {\n installedApkCache = cache;\n }\n\n public static class InstalledApkCache {\n\n protected Map installedApks = null;\n\n protected Map buildAppList(Context context) {\n Map info = new HashMap();\n Log.d(\"FDroid\", \"Reading installed packages\");\n List installedPackages = context.getPackageManager().getInstalledPackages(0);\n for (PackageInfo appInfo : installedPackages) {\n info.put(appInfo.packageName, appInfo);\n }\n return info;\n }\n\n public Map getApks(Context context) {\n if (installedApks == null) {\n installedApks = buildAppList(context);\n }\n return installedApks;\n }\n\n public void emptyCache() {\n installedApks = null;\n }\n\n }\n\n\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport android.content.Context;\n\nimport android.content.pm.PackageInfo;\nimport android.text.TextUtils;\nimport android.util.DisplayMetrics;\nimport android.util.Log;\nimport com.nostra13.universalimageloader.utils.StorageUtils;\n\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.security.cert.Certificate;\nimport java.security.cert.CertificateEncodingException;\nimport java.text.SimpleDateFormat;\nimport java.security.MessageDigest;\nimport java.util.*;\n\npublic final class Utils {\n\n public static final int BUFFER_SIZE = 4096;\n\n \/\/ The date format used for storing dates (e.g. lastupdated, added) in the\n \/\/ database.\n public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.ENGLISH);\n\n private static final String[] FRIENDLY_SIZE_FORMAT = {\n \"%.0f B\", \"%.0f KiB\", \"%.1f MiB\", \"%.2f GiB\" };\n\n public static final SimpleDateFormat LOG_DATE_FORMAT =\n new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.ENGLISH);\n\n public static String getIconsDir(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n String iconsDir;\n if (metrics.densityDpi >= 640) {\n iconsDir = \"\/icons-640\/\";\n } else if (metrics.densityDpi >= 480) {\n iconsDir = \"\/icons-480\/\";\n } else if (metrics.densityDpi >= 320) {\n iconsDir = \"\/icons-320\/\";\n } else if (metrics.densityDpi >= 240) {\n iconsDir = \"\/icons-240\/\";\n } else if (metrics.densityDpi >= 160) {\n iconsDir = \"\/icons-160\/\";\n } else {\n iconsDir = \"\/icons-120\/\";\n }\n return iconsDir;\n }\n\n public static void copy(InputStream input, OutputStream output)\n throws IOException {\n copy(input, output, null, null);\n }\n\n public static void copy(InputStream input, OutputStream output,\n ProgressListener progressListener,\n ProgressListener.Event templateProgressEvent)\n throws IOException {\n byte[] buffer = new byte[BUFFER_SIZE];\n int bytesRead = 0;\n while (true) {\n int count = input.read(buffer);\n if (count == -1) {\n break;\n }\n if (progressListener != null) {\n bytesRead += count;\n templateProgressEvent.progress = bytesRead;\n progressListener.onProgress(templateProgressEvent);\n }\n output.write(buffer, 0, count);\n }\n output.flush();\n }\n\n public static void closeQuietly(Closeable closeable) {\n if (closeable == null) {\n return;\n }\n try {\n closeable.close();\n } catch (IOException ioe) {\n \/\/ ignore\n }\n }\n\n public static String getFriendlySize(int size) {\n double s = size;\n int i = 0;\n while (i < FRIENDLY_SIZE_FORMAT.length - 1 && s >= 1024) {\n s = (100 * s \/ 1024) \/ 100.0;\n i++;\n }\n return String.format(FRIENDLY_SIZE_FORMAT[i], s);\n }\n\n public static String getAndroidVersionName(int sdkLevel) {\n if (sdkLevel < 1) return null;\n switch (sdkLevel) {\n case 19: return \"4.4\";\n case 18: return \"4.3\";\n case 17: return \"4.2\";\n case 16: return \"4.1\";\n case 15: return \"4.0.3\";\n case 14: return \"4.0\";\n case 13: return \"3.2\";\n case 12: return \"3.1\";\n case 11: return \"3.0\";\n case 10: return \"2.3.3\";\n case 9: return \"2.3\";\n case 8: return \"2.2\";\n case 7: return \"2.1\";\n case 6: return \"2.0.1\";\n case 5: return \"2.0\";\n case 4: return \"1.6\";\n case 3: return \"1.5\";\n case 2: return \"1.1\";\n case 1: return \"1.0\";\n default: return \"?\";\n }\n }\n\n public static int countSubstringOccurrence(File file, String substring) throws IOException {\n int count = 0;\n FileReader input = null;\n try {\n int currentSubstringIndex = 0;\n char[] buffer = new char[4096];\n\n input = new FileReader(file);\n int numRead = input.read(buffer);\n while(numRead != -1) {\n\n for (char c : buffer) {\n if (c == substring.charAt(currentSubstringIndex)) {\n currentSubstringIndex ++;\n if (currentSubstringIndex == substring.length()) {\n count ++;\n currentSubstringIndex = 0;\n }\n } else {\n currentSubstringIndex = 0;\n }\n }\n numRead = input.read(buffer);\n }\n } finally {\n closeQuietly(input);\n }\n return count;\n }\n\n \/\/ return a fingerprint formatted for display\n public static String formatFingerprint(String fingerprint) {\n if (fingerprint.length() != 62) \/\/ SHA-256 is 62 hex chars\n return \"BAD FINGERPRINT\";\n String displayFP = fingerprint.substring(0, 2);\n for (int i = 2; i < fingerprint.length(); i = i + 2)\n displayFP += \" \" + fingerprint.substring(i, i + 2);\n return displayFP;\n }\n\n public static File getApkCacheDir(Context context) {\n File apkCacheDir = new File(\n StorageUtils.getCacheDirectory(context, true), \"apks\");\n if (!apkCacheDir.exists()) {\n apkCacheDir.mkdir();\n }\n return apkCacheDir;\n }\n\n public static Map getInstalledApps(Context context) {\n return installedApkCache.getApks(context);\n }\n\n public static void clearInstalledApksCache() {\n installedApkCache.emptyCache();\n }\n\n public static String calcFingerprint(String keyHexString) {\n if (TextUtils.isEmpty(keyHexString))\n return null;\n else\n return calcFingerprint(Hasher.unhex(keyHexString));\n }\n\n public static String calcFingerprint(Certificate cert) {\n try {\n return calcFingerprint(cert.getEncoded());\n } catch (CertificateEncodingException e) {\n return null;\n }\n }\n\n public static String calcFingerprint(byte[] key) {\n String ret = null;\n try {\n \/\/ keytool -list -v gives you the SHA-256 fingerprint\n MessageDigest digest = MessageDigest.getInstance(\"SHA-256\");\n digest.update(key);\n byte[] fingerprint = digest.digest();\n Formatter formatter = new Formatter(new StringBuilder());\n for (int i = 1; i < fingerprint.length; i++) {\n formatter.format(\"%02X\", fingerprint[i]);\n }\n ret = formatter.toString();\n formatter.close();\n } catch (Exception e) {\n Log.w(\"FDroid\", \"Unable to get certificate fingerprint.\\n\"\n + Log.getStackTraceString(e));\n }\n return ret;\n }\n\n public static class CommaSeparatedList implements Iterable {\n private String value;\n\n private CommaSeparatedList(String list) {\n value = list;\n }\n\n public static CommaSeparatedList make(List list) {\n if (list == null || list.size() == 0)\n return null;\n else {\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < list.size(); i ++) {\n if (i > 0) {\n sb.append(',');\n }\n sb.append(list.get(i));\n }\n return new CommaSeparatedList(sb.toString());\n }\n }\n\n public static CommaSeparatedList make(String list) {\n if (list == null || list.length() == 0)\n return null;\n else\n return new CommaSeparatedList(list);\n }\n\n public static String str(CommaSeparatedList instance) {\n return (instance == null ? null : instance.toString());\n }\n\n @Override\n public String toString() {\n return value;\n }\n\n public String toPrettyString() {\n return value.replaceAll(\",\", \", \");\n }\n\n @Override\n public Iterator iterator() {\n TextUtils.SimpleStringSplitter splitter = new TextUtils.SimpleStringSplitter(',');\n splitter.setString(value);\n return splitter.iterator();\n }\n\n public boolean contains(String v) {\n for (String s : this) {\n if (s.equals(v))\n return true;\n }\n return false;\n }\n }\n\n private static InstalledApkCache installedApkCache = null;\n\n \/**\n * We do a lot of querying of the installed app's. As a result, we like\n * to cache this information quite heavily (and flush the cache when new\n * apps are installed). The caching implementation needs to be setup like\n * this so that it is possible to mock for testing purposes.\n *\/\n public static void setupInstalledApkCache(InstalledApkCache cache) {\n installedApkCache = cache;\n }\n\n public static class InstalledApkCache {\n\n protected Map installedApks = null;\n\n protected Map buildAppList(Context context) {\n Map info = new HashMap();\n Log.d(\"FDroid\", \"Reading installed packages\");\n List installedPackages = context.getPackageManager().getInstalledPackages(0);\n for (PackageInfo appInfo : installedPackages) {\n info.put(appInfo.packageName, appInfo);\n }\n return info;\n }\n\n public Map getApks(Context context) {\n if (installedApks == null) {\n installedApks = buildAppList(context);\n }\n return installedApks;\n }\n\n public void emptyCache() {\n installedApks = null;\n }\n\n }\n\n\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport android.content.Context;\n\nimport android.content.pm.PackageInfo;\nimport android.text.TextUtils;\nimport android.util.DisplayMetrics;\nimport android.util.Log;\nimport com.nostra13.universalimageloader.utils.StorageUtils;\n\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.security.cert.Certificate;\nimport java.security.cert.CertificateEncodingException;\nimport java.text.SimpleDateFormat;\nimport java.security.MessageDigest;\nimport java.util.*;\n\npublic final class Utils {\n\n public static final int BUFFER_SIZE = 4096;\n\n \/\/ The date format used for storing dates (e.g. lastupdated, added) in the\n \/\/ database.\n public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.ENGLISH);\n\n private static final String[] FRIENDLY_SIZE_FORMAT = {\n \"%.0f B\", \"%.0f KiB\", \"%.1f MiB\", \"%.2f GiB\" };\n\n public static final SimpleDateFormat LOG_DATE_FORMAT =\n new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.ENGLISH);\n\n public static String getIconsDir(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n String iconsDir;\n if (metrics.densityDpi >= 640) {\n iconsDir = \"\/icons-640\/\";\n } else if (metrics.densityDpi >= 480) {\n iconsDir = \"\/icons-480\/\";\n } else if (metrics.densityDpi >= 320) {\n iconsDir = \"\/icons-320\/\";\n } else if (metrics.densityDpi >= 240) {\n iconsDir = \"\/icons-240\/\";\n } else if (metrics.densityDpi >= 160) {\n iconsDir = \"\/icons-160\/\";\n } else {\n iconsDir = \"\/icons-120\/\";\n }\n return iconsDir;\n }\n\n public static void copy(InputStream input, OutputStream output)\n throws IOException {\n copy(input, output, null, null);\n }\n\n public static void copy(InputStream input, OutputStream output,\n ProgressListener progressListener,\n ProgressListener.Event templateProgressEvent)\n throws IOException {\n byte[] buffer = new byte[BUFFER_SIZE];\n int bytesRead = 0;\n while (true) {\n int count = input.read(buffer);\n if (count == -1) {\n break;\n }\n if (progressListener != null) {\n bytesRead += count;\n templateProgressEvent.progress = bytesRead;\n progressListener.onProgress(templateProgressEvent);\n }\n output.write(buffer, 0, count);\n }\n output.flush();\n }\n\n public static void closeQuietly(Closeable closeable) {\n if (closeable == null) {\n return;\n }\n try {\n closeable.close();\n } catch (IOException ioe) {\n \/\/ ignore\n }\n }\n\n public static String getFriendlySize(int size) {\n double s = size;\n int i = 0;\n while (i < FRIENDLY_SIZE_FORMAT.length - 1 && s >= 1024) {\n s = (100 * s \/ 1024) \/ 100.0;\n i++;\n }\n return String.format(FRIENDLY_SIZE_FORMAT[i], s);\n }\n\n public static String getAndroidVersionName(int sdkLevel) {\n if (sdkLevel < 1) return null;\n switch (sdkLevel) {\n case 19: return \"4.4\";\n case 18: return \"4.3\";\n case 17: return \"4.2\";\n case 16: return \"4.1\";\n case 15: return \"4.0.3\";\n case 14: return \"4.0\";\n case 13: return \"3.2\";\n case 12: return \"3.1\";\n case 11: return \"3.0\";\n case 10: return \"2.3.3\";\n case 9: return \"2.3\";\n case 8: return \"2.2\";\n case 7: return \"2.1\";\n case 6: return \"2.0.1\";\n case 5: return \"2.0\";\n case 4: return \"1.6\";\n case 3: return \"1.5\";\n case 2: return \"1.1\";\n case 1: return \"1.0\";\n default: return \"?\";\n }\n }\n\n public static int countSubstringOccurrence(File file, String substring) throws IOException {\n int count = 0;\n FileReader input = null;\n try {\n int currentSubstringIndex = 0;\n char[] buffer = new char[4096];\n\n input = new FileReader(file);\n int numRead = input.read(buffer);\n while(numRead != -1) {\n\n for (char c : buffer) {\n if (c == substring.charAt(currentSubstringIndex)) {\n currentSubstringIndex ++;\n if (currentSubstringIndex == substring.length()) {\n count ++;\n currentSubstringIndex = 0;\n }\n } else {\n currentSubstringIndex = 0;\n }\n }\n numRead = input.read(buffer);\n }\n } finally {\n closeQuietly(input);\n }\n return count;\n }\n\n \/\/ return a fingerprint formatted for display\n public static String formatFingerprint(String fingerprint) {\n if (fingerprint.length() != 62) \/\/ SHA-256 is 62 hex chars\n return \"BAD FINGERPRINT\";\n String displayFP = fingerprint.substring(0, 2);\n for (int i = 2; i < fingerprint.length(); i = i + 2)\n displayFP += \" \" + fingerprint.substring(i, i + 2);\n return displayFP;\n }\n\n public static File getApkCacheDir(Context context) {\n File apkCacheDir = new File(\n StorageUtils.getCacheDirectory(context, true), \"apks\");\n if (!apkCacheDir.exists()) {\n apkCacheDir.mkdir();\n }\n return apkCacheDir;\n }\n\n public static Map getInstalledApps(Context context) {\n return installedApkCache.getApks(context);\n }\n\n public static void clearInstalledApksCache() {\n installedApkCache.emptyCache();\n }\n\n public static String calcFingerprint(String keyHexString) {\n if (TextUtils.isEmpty(keyHexString))\n return null;\n else\n return calcFingerprint(Hasher.unhex(keyHexString));\n }\n\n public static String calcFingerprint(Certificate cert) {\n try {\n return calcFingerprint(cert.getEncoded());\n } catch (CertificateEncodingException e) {\n return null;\n }\n }\n\n public static String calcFingerprint(byte[] key) {\n String ret = null;\n try {\n \/\/ keytool -list -v gives you the SHA-256 fingerprint\n MessageDigest digest = MessageDigest.getInstance(\"SHA-256\");\n digest.update(key);\n byte[] fingerprint = digest.digest();\n Formatter formatter = new Formatter(new StringBuilder());\n for (int i = 1; i < fingerprint.length; i++) {\n formatter.format(\"%02X\", fingerprint[i]);\n }\n ret = formatter.toString();\n formatter.close();\n } catch (Exception e) {\n Log.w(\"FDroid\", \"Unable to get certificate fingerprint.\\n\"\n + Log.getStackTraceString(e));\n }\n return ret;\n }\n\n public static class CommaSeparatedList implements Iterable {\n private String value;\n\n private CommaSeparatedList(String list) {\n value = list;\n }\n\n public static CommaSeparatedList make(List list) {\n if (list == null || list.size() == 0)\n return null;\n else {\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < list.size(); i ++) {\n if (i > 0) {\n sb.append(',');\n }\n sb.append(list.get(i));\n }\n return new CommaSeparatedList(sb.toString());\n }\n }\n\n public static CommaSeparatedList make(String list) {\n if (list == null || list.length() == 0)\n return null;\n else\n return new CommaSeparatedList(list);\n }\n\n public static String str(CommaSeparatedList instance) {\n return (instance == null ? null : instance.toString());\n }\n\n @Override\n public String toString() {\n return value;\n }\n\n public String toPrettyString() {\n return value.replaceAll(\",\", \", \");\n }\n\n @Override\n public Iterator iterator() {\n TextUtils.SimpleStringSplitter splitter = new TextUtils.SimpleStringSplitter(',');\n splitter.setString(value);\n return splitter.iterator();\n }\n\n public boolean contains(String v) {\n for (String s : this) {\n if (s.equals(v))\n return true;\n }\n return false;\n }\n }\n\n private static InstalledApkCache installedApkCache = null;\n\n \/**\n * We do a lot of querying of the installed app's. As a result, we like\n * to cache this information quite heavily (and flush the cache when new\n * apps are installed). The caching implementation needs to be setup like\n * this so that it is possible to mock for testing purposes.\n *\/\n public static void setupInstalledApkCache(InstalledApkCache cache) {\n installedApkCache = cache;\n }\n\n public static class InstalledApkCache {\n\n protected Map installedApks = null;\n\n protected Map buildAppList(Context context) {\n Map info = new HashMap();\n Log.d(\"FDroid\", \"Reading installed packages\");\n List installedPackages = context.getPackageManager().getInstalledPackages(0);\n for (PackageInfo appInfo : installedPackages) {\n info.put(appInfo.packageName, appInfo);\n }\n return info;\n }\n\n public Map getApks(Context context) {\n if (installedApks == null) {\n installedApks = buildAppList(context);\n }\n return installedApks;\n }\n\n public void emptyCache() {\n installedApks = null;\n }\n\n }\n\n\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\n\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport android.content.Context;\n\nimport android.content.pm.PackageInfo;\nimport android.text.TextUtils;\nimport android.util.DisplayMetrics;\nimport android.util.Log;\nimport com.nostra13.universalimageloader.utils.StorageUtils;\n\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.security.cert.Certificate;\nimport java.security.cert.CertificateEncodingException;\nimport java.text.SimpleDateFormat;\nimport java.security.MessageDigest;\nimport java.util.*;\n\npublic final class Utils {\n\n public static final int BUFFER_SIZE = 4096;\n\n \/\/ The date format used for storing dates (e.g. lastupdated, added) in the\n \/\/ database.\n public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.ENGLISH);\n\n private static final String[] FRIENDLY_SIZE_FORMAT = {\n \"%.0f B\", \"%.0f KiB\", \"%.1f MiB\", \"%.2f GiB\" };\n\n public static final SimpleDateFormat LOG_DATE_FORMAT =\n new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.ENGLISH);\n\n public static String getIconsDir(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n String iconsDir;\n if (metrics.densityDpi >= 640) {\n iconsDir = \"\/icons-640\/\";\n } else if (metrics.densityDpi >= 480) {\n iconsDir = \"\/icons-480\/\";\n } else if (metrics.densityDpi >= 320) {\n iconsDir = \"\/icons-320\/\";\n } else if (metrics.densityDpi >= 240) {\n iconsDir = \"\/icons-240\/\";\n } else if (metrics.densityDpi >= 160) {\n iconsDir = \"\/icons-160\/\";\n } else {\n iconsDir = \"\/icons-120\/\";\n }\n return iconsDir;\n }\n\n public static void copy(InputStream input, OutputStream output)\n throws IOException {\n copy(input, output, null, null);\n }\n\n public static void copy(InputStream input, OutputStream output,\n ProgressListener progressListener,\n ProgressListener.Event templateProgressEvent)\n throws IOException {\n byte[] buffer = new byte[BUFFER_SIZE];\n int bytesRead = 0;\n while (true) {\n int count = input.read(buffer);\n if (count == -1) {\n break;\n }\n if (progressListener != null) {\n bytesRead += count;\n templateProgressEvent.progress = bytesRead;\n progressListener.onProgress(templateProgressEvent);\n }\n output.write(buffer, 0, count);\n }\n output.flush();\n }\n\n public static void closeQuietly(Closeable closeable) {\n if (closeable == null) {\n return;\n }\n try {\n closeable.close();\n } catch (IOException ioe) {\n \/\/ ignore\n }\n }\n\n public static String getFriendlySize(int size) {\n double s = size;\n int i = 0;\n while (i < FRIENDLY_SIZE_FORMAT.length - 1 && s >= 1024) {\n s = (100 * s \/ 1024) \/ 100.0;\n i++;\n }\n return String.format(FRIENDLY_SIZE_FORMAT[i], s);\n }\n\n public static String getAndroidVersionName(int sdkLevel) {\n if (sdkLevel < 1) return null;\n switch (sdkLevel) {\n case 19: return \"4.4\";\n case 18: return \"4.3\";\n case 17: return \"4.2\";\n case 16: return \"4.1\";\n case 15: return \"4.0.3\";\n case 14: return \"4.0\";\n case 13: return \"3.2\";\n case 12: return \"3.1\";\n case 11: return \"3.0\";\n case 10: return \"2.3.3\";\n case 9: return \"2.3\";\n case 8: return \"2.2\";\n case 7: return \"2.1\";\n case 6: return \"2.0.1\";\n case 5: return \"2.0\";\n case 4: return \"1.6\";\n case 3: return \"1.5\";\n case 2: return \"1.1\";\n case 1: return \"1.0\";\n default: return \"?\";\n }\n }\n\n public static int countSubstringOccurrence(File file, String substring) throws IOException {\n int count = 0;\n FileReader input = null;\n try {\n int currentSubstringIndex = 0;\n char[] buffer = new char[4096];\n\n input = new FileReader(file);\n int numRead = input.read(buffer);\n while(numRead != -1) {\n\n for (char c : buffer) {\n if (c == substring.charAt(currentSubstringIndex)) {\n currentSubstringIndex ++;\n if (currentSubstringIndex == substring.length()) {\n count ++;\n currentSubstringIndex = 0;\n }\n } else {\n currentSubstringIndex = 0;\n }\n }\n numRead = input.read(buffer);\n }\n } finally {\n closeQuietly(input);\n }\n return count;\n }\n\n \/\/ return a fingerprint formatted for display\n public static String formatFingerprint(String fingerprint) {\n if (fingerprint.length() != 62) \/\/ SHA-256 is 62 hex chars\n return \"BAD FINGERPRINT\";\n String displayFP = fingerprint.substring(0, 2);\n for (int i = 2; i < fingerprint.length(); i = i + 2)\n displayFP += \" \" + fingerprint.substring(i, i + 2);\n return displayFP;\n }\n\n public static File getApkCacheDir(Context context) {\n File apkCacheDir = new File(\n StorageUtils.getCacheDirectory(context, true), \"apks\");\n if (!apkCacheDir.exists()) {\n apkCacheDir.mkdir();\n }\n return apkCacheDir;\n }\n\n public static Map getInstalledApps(Context context) {\n return installedApkCache.getApks(context);\n }\n\n public static void clearInstalledApksCache() {\n installedApkCache.emptyCache();\n }\n\n public static String calcFingerprint(String keyHexString) {\n if (TextUtils.isEmpty(keyHexString))\n return null;\n else\n return calcFingerprint(Hasher.unhex(keyHexString));\n }\n\n public static String calcFingerprint(Certificate cert) {\n try {\n return calcFingerprint(cert.getEncoded());\n } catch (CertificateEncodingException e) {\n return null;\n }\n }\n\n public static String calcFingerprint(byte[] key) {\n String ret = null;\n try {\n \/\/ keytool -list -v gives you the SHA-256 fingerprint\n MessageDigest digest = MessageDigest.getInstance(\"SHA-256\");\n digest.update(key);\n byte[] fingerprint = digest.digest();\n Formatter formatter = new Formatter(new StringBuilder());\n for (int i = 1; i < fingerprint.length; i++) {\n formatter.format(\"%02X\", fingerprint[i]);\n }\n ret = formatter.toString();\n formatter.close();\n } catch (Exception e) {\n Log.w(\"FDroid\", \"Unable to get certificate fingerprint.\\n\"\n + Log.getStackTraceString(e));\n }\n return ret;\n }\n\n public static class CommaSeparatedList implements Iterable {\n private String value;\n\n private CommaSeparatedList(String list) {\n value = list;\n }\n\n public static CommaSeparatedList make(List list) {\n if (list == null || list.size() == 0)\n return null;\n else {\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < list.size(); i ++) {\n if (i > 0) {\n sb.append(',');\n }\n sb.append(list.get(i));\n }\n return new CommaSeparatedList(sb.toString());\n }\n }\n\n public static CommaSeparatedList make(String list) {\n if (list == null || list.length() == 0)\n return null;\n else\n return new CommaSeparatedList(list);\n }\n\n public static String str(CommaSeparatedList instance) {\n return (instance == null ? null : instance.toString());\n }\n\n @Override\n public String toString() {\n return value;\n }\n\n public String toPrettyString() {\n return value.replaceAll(\",\", \", \");\n }\n\n @Override\n public Iterator iterator() {\n TextUtils.SimpleStringSplitter splitter = new TextUtils.SimpleStringSplitter(',');\n splitter.setString(value);\n return splitter.iterator();\n }\n\n public boolean contains(String v) {\n for (String s : this) {\n if (s.equals(v))\n return true;\n }\n return false;\n }\n }\n\n private static InstalledApkCache installedApkCache = null;\n\n \/**\n * We do a lot of querying of the installed app's. As a result, we like\n * to cache this information quite heavily (and flush the cache when new\n * apps are installed). The caching implementation needs to be setup like\n * this so that it is possible to mock for testing purposes.\n *\/\n public static void setupInstalledApkCache(InstalledApkCache cache) {\n installedApkCache = cache;\n }\n\n public static class InstalledApkCache {\n\n protected Map installedApks = null;\n\n protected Map buildAppList(Context context) {\n Map info = new HashMap();\n Log.d(\"FDroid\", \"Reading installed packages\");\n List installedPackages = context.getPackageManager().getInstalledPackages(0);\n for (PackageInfo appInfo : installedPackages) {\n info.put(appInfo.packageName, appInfo);\n }\n return info;\n }\n\n public Map getApks(Context context) {\n if (installedApks == null) {\n installedApks = buildAppList(context);\n }\n return installedApks;\n }\n\n public void emptyCache() {\n installedApks = null;\n }\n\n }\n\n\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nSpeed up getAndroidVersionName by using a static array. Write the entire code and no other text in the response.\n\n### Concepts:\n[in] getAndroidVersionName\n\n### Given program:\n```java\n\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport android.content.Context;\n\nimport android.content.pm.PackageInfo;\nimport android.text.TextUtils;\nimport android.util.DisplayMetrics;\nimport android.util.Log;\nimport com.nostra13.universalimageloader.utils.StorageUtils;\n\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.security.cert.Certificate;\nimport java.security.cert.CertificateEncodingException;\nimport java.text.SimpleDateFormat;\nimport java.security.MessageDigest;\nimport java.util.*;\n\npublic final class Utils {\n\n public static final int BUFFER_SIZE = 4096;\n\n \/\/ The date format used for storing dates (e.g. lastupdated, added) in the\n \/\/ database.\n public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.ENGLISH);\n\n private static final String[] FRIENDLY_SIZE_FORMAT = {\n \"%.0f B\", \"%.0f KiB\", \"%.1f MiB\", \"%.2f GiB\" };\n\n public static final SimpleDateFormat LOG_DATE_FORMAT =\n new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.ENGLISH);\n\n public static String getIconsDir(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n String iconsDir;\n if (metrics.densityDpi >= 640) {\n iconsDir = \"\/icons-640\/\";\n } else if (metrics.densityDpi >= 480) {\n iconsDir = \"\/icons-480\/\";\n } else if (metrics.densityDpi >= 320) {\n iconsDir = \"\/icons-320\/\";\n } else if (metrics.densityDpi >= 240) {\n iconsDir = \"\/icons-240\/\";\n } else if (metrics.densityDpi >= 160) {\n iconsDir = \"\/icons-160\/\";\n } else {\n iconsDir = \"\/icons-120\/\";\n }\n return iconsDir;\n }\n\n public static void copy(InputStream input, OutputStream output)\n throws IOException {\n copy(input, output, null, null);\n }\n\n public static void copy(InputStream input, OutputStream output,\n ProgressListener progressListener,\n ProgressListener.Event templateProgressEvent)\n throws IOException {\n byte[] buffer = new byte[BUFFER_SIZE];\n int bytesRead = 0;\n while (true) {\n int count = input.read(buffer);\n if (count == -1) {\n break;\n }\n if (progressListener != null) {\n bytesRead += count;\n templateProgressEvent.progress = bytesRead;\n progressListener.onProgress(templateProgressEvent);\n }\n output.write(buffer, 0, count);\n }\n output.flush();\n }\n\n public static void closeQuietly(Closeable closeable) {\n if (closeable == null) {\n return;\n }\n try {\n closeable.close();\n } catch (IOException ioe) {\n \/\/ ignore\n }\n }\n\n public static String getFriendlySize(int size) {\n double s = size;\n int i = 0;\n while (i < FRIENDLY_SIZE_FORMAT.length - 1 && s >= 1024) {\n s = (100 * s \/ 1024) \/ 100.0;\n i++;\n }\n return String.format(FRIENDLY_SIZE_FORMAT[i], s);\n }\n\n public static String getAndroidVersionName(int sdkLevel) {\n if (sdkLevel < 1) return null;\n switch (sdkLevel) {\n case 19: return \"4.4\";\n case 18: return \"4.3\";\n case 17: return \"4.2\";\n case 16: return \"4.1\";\n case 15: return \"4.0.3\";\n case 14: return \"4.0\";\n case 13: return \"3.2\";\n case 12: return \"3.1\";\n case 11: return \"3.0\";\n case 10: return \"2.3.3\";\n case 9: return \"2.3\";\n case 8: return \"2.2\";\n case 7: return \"2.1\";\n case 6: return \"2.0.1\";\n case 5: return \"2.0\";\n case 4: return \"1.6\";\n case 3: return \"1.5\";\n case 2: return \"1.1\";\n case 1: return \"1.0\";\n default: return \"?\";\n }\n }\n\n public static int countSubstringOccurrence(File file, String substring) throws IOException {\n int count = 0;\n FileReader input = null;\n try {\n int currentSubstringIndex = 0;\n char[] buffer = new char[4096];\n\n input = new FileReader(file);\n int numRead = input.read(buffer);\n while(numRead != -1) {\n\n for (char c : buffer) {\n if (c == substring.charAt(currentSubstringIndex)) {\n currentSubstringIndex ++;\n if (currentSubstringIndex == substring.length()) {\n count ++;\n currentSubstringIndex = 0;\n }\n } else {\n currentSubstringIndex = 0;\n }\n }\n numRead = input.read(buffer);\n }\n } finally {\n closeQuietly(input);\n }\n return count;\n }\n\n \/\/ return a fingerprint formatted for display\n public static String formatFingerprint(String fingerprint) {\n if (fingerprint.length() != 62) \/\/ SHA-256 is 62 hex chars\n return \"BAD FINGERPRINT\";\n String displayFP = fingerprint.substring(0, 2);\n for (int i = 2; i < fingerprint.length(); i = i + 2)\n displayFP += \" \" + fingerprint.substring(i, i + 2);\n return displayFP;\n }\n\n public static File getApkCacheDir(Context context) {\n File apkCacheDir = new File(\n StorageUtils.getCacheDirectory(context, true), \"apks\");\n if (!apkCacheDir.exists()) {\n apkCacheDir.mkdir();\n }\n return apkCacheDir;\n }\n\n public static Map getInstalledApps(Context context) {\n return installedApkCache.getApks(context);\n }\n\n public static void clearInstalledApksCache() {\n installedApkCache.emptyCache();\n }\n\n public static String calcFingerprint(String keyHexString) {\n if (TextUtils.isEmpty(keyHexString))\n return null;\n else\n return calcFingerprint(Hasher.unhex(keyHexString));\n }\n\n public static String calcFingerprint(Certificate cert) {\n try {\n return calcFingerprint(cert.getEncoded());\n } catch (CertificateEncodingException e) {\n return null;\n }\n }\n\n public static String calcFingerprint(byte[] key) {\n String ret = null;\n try {\n \/\/ keytool -list -v gives you the SHA-256 fingerprint\n MessageDigest digest = MessageDigest.getInstance(\"SHA-256\");\n digest.update(key);\n byte[] fingerprint = digest.digest();\n Formatter formatter = new Formatter(new StringBuilder());\n for (int i = 1; i < fingerprint.length; i++) {\n formatter.format(\"%02X\", fingerprint[i]);\n }\n ret = formatter.toString();\n formatter.close();\n } catch (Exception e) {\n Log.w(\"FDroid\", \"Unable to get certificate fingerprint.\\n\"\n + Log.getStackTraceString(e));\n }\n return ret;\n }\n\n public static class CommaSeparatedList implements Iterable {\n private String value;\n\n private CommaSeparatedList(String list) {\n value = list;\n }\n\n public static CommaSeparatedList make(List list) {\n if (list == null || list.size() == 0)\n return null;\n else {\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < list.size(); i ++) {\n if (i > 0) {\n sb.append(',');\n }\n sb.append(list.get(i));\n }\n return new CommaSeparatedList(sb.toString());\n }\n }\n\n public static CommaSeparatedList make(String list) {\n if (list == null || list.length() == 0)\n return null;\n else\n return new CommaSeparatedList(list);\n }\n\n public static String str(CommaSeparatedList instance) {\n return (instance == null ? null : instance.toString());\n }\n\n @Override\n public String toString() {\n return value;\n }\n\n public String toPrettyString() {\n return value.replaceAll(\",\", \", \");\n }\n\n @Override\n public Iterator iterator() {\n TextUtils.SimpleStringSplitter splitter = new TextUtils.SimpleStringSplitter(',');\n splitter.setString(value);\n return splitter.iterator();\n }\n\n public boolean contains(String v) {\n for (String s : this) {\n if (s.equals(v))\n return true;\n }\n return false;\n }\n }\n\n private static InstalledApkCache installedApkCache = null;\n\n \/**\n * We do a lot of querying of the installed app's. As a result, we like\n * to cache this information quite heavily (and flush the cache when new\n * apps are installed). The caching implementation needs to be setup like\n * this so that it is possible to mock for testing purposes.\n *\/\n public static void setupInstalledApkCache(InstalledApkCache cache) {\n installedApkCache = cache;\n }\n\n public static class InstalledApkCache {\n\n protected Map installedApks = null;\n\n protected Map buildAppList(Context context) {\n Map info = new HashMap();\n Log.d(\"FDroid\", \"Reading installed packages\");\n List installedPackages = context.getPackageManager().getInstalledPackages(0);\n for (PackageInfo appInfo : installedPackages) {\n info.put(appInfo.packageName, appInfo);\n }\n return info;\n }\n\n public Map getApks(Context context) {\n if (installedApks == null) {\n installedApks = buildAppList(context);\n }\n return installedApks;\n }\n\n public void emptyCache() {\n installedApks = null;\n }\n\n }\n\n\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.ProgressDialog;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.net.NetworkInfo;\nimport android.net.wifi.WifiManager;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.Button;\nimport android.widget.ListAdapter;\nimport android.widget.ListView;\nimport android.widget.SimpleAdapter;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Discovery;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class MainActivity extends Activity implements MainAsyncResponse {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n private Discovery discovery = new Discovery();\n private ListView hostList;\n private TextView internalIp;\n private TextView externalIp;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n private ProgressDialog scanProgressDialog;\n private Handler mHandler = new Handler();\n private BroadcastReceiver receiver;\n private IntentFilter intentFilter = new IntentFilter();\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n TextView macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.internalIp = (TextView) findViewById(R.id.internalIpAddress);\n this.externalIp = (TextView) findViewById(R.id.externalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n Button discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n this.wifi = new Wireless(this);\n\n macAddress.setText(this.wifi.getMacAddress());\n\n this.receiver = new BroadcastReceiver() {\n\n \/**\n * Detect if a network connection has been lost or established\n * @param context\n * @param intent\n *\/\n @Override\n public void onReceive(Context context, Intent intent) {\n NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);\n if(info != null) {\n if(info.isConnected()) {\n getNetworkInfo();\n }\n else {\n mHandler.removeCallbacksAndMessages(null);\n MainActivity.this.internalIp.setText(\"No WiFi connection\");\n externalIp.setText(\"No WiFi connection\");\n signalStrength.setText(\"No WiFi connection\");\n ssid.setText(\"No WiFi connection\");\n bssid.setText(\"No WiFi connection\");\n }\n }\n }\n };\n\n this.intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);\n registerReceiver(receiver, this.intentFilter);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler to perform host discovery\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n scanProgressDialog = new ProgressDialog(MainActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning For Hosts\");\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(255);\n scanProgressDialog.show();\n\n discovery.scanHosts(wifi.getInternalIpAddress(), MainActivity.this);\n }\n });\n\n this.hostList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open the host activity for a specific host found on the network\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n HashMap map = (HashMap) hostList.getItemAtPosition(position);\n Intent intent = new Intent(MainActivity.this, HostActivity.class);\n String firstLine = map.get(\"First Line\");\n String secondLine = map.get(\"Second Line\");\n String macAddress = map.get(\"Second Line\").substring(secondLine.indexOf(\"[\") + 1, secondLine.indexOf(\"]\"));\n\n intent.putExtra(\"HOST\", firstLine);\n intent.putExtra(\"MAC\", macAddress);\n startActivity(intent);\n }\n });\n\n }\n\n \/**\n * Gets network information about the device and updates various UI elements\n *\/\n private void getNetworkInfo() {\n this.mHandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n this.internalIp.setText(this.wifi.getInternalIpAddress());\n this.wifi.getExternalIpAddress(this);\n this.ssid.setText(this.wifi.getSSID());\n this.bssid.setText(this.wifi.getBSSID());\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n unregisterReceiver(this.receiver);\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n this.scanProgressDialog = null;\n }\n\n \/**\n * Activity restarted\n *\/\n @Override\n public void onRestart() {\n super.onRestart();\n\n registerReceiver(this.receiver, this.intentFilter);\n }\n\n \/**\n * Save the state of an activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n ListAdapter adapter = this.hostList.getAdapter();\n if(adapter != null) {\n ArrayList> adapterData = new ArrayList<>();\n for(int i = 0; i < adapter.getCount(); i++) {\n HashMap item = (HashMap) adapter.getItem(i);\n adapterData.add(item);\n }\n savedState.putSerializable(\"hosts\", adapterData);\n }\n }\n\n \/**\n * Activity state restored\n *\n * @param savedState Saved data from the saved state\n *\/\n @Override\n public void onRestoreInstanceState(Bundle savedState) {\n super.onRestoreInstanceState(savedState);\n\n ArrayList> hosts = (ArrayList) savedState.getSerializable(\"hosts\");\n if(hosts != null) {\n SimpleAdapter newAdapter = new SimpleAdapter(this, hosts, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n this.hostList.setAdapter(newAdapter);\n }\n }\n\n \/**\n * Delegate to update the host list and dismiss the progress dialog\n * Gets called when host discovery has finished\n *\n * @param output The list of hosts to bind to the list view\n *\/\n @Override\n public void processFinish(ArrayList> output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n SimpleAdapter adapter = new SimpleAdapter(this, output, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n ListView hostList = (ListView) this.findViewById(R.id.hostList);\n hostList.setAdapter(adapter);\n this.scanProgressDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to update the progress of the host discovery scan\n *\n * @param output The amount of progress to increment by\n *\/\n @Override\n public void processFinish(int output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.incrementProgressBy(output);\n }\n }\n\n \/**\n * Delegate to handle setting the external IP in the UI\n *\n * @param output External IP\n *\/\n @Override\n public void processFinish(String output) {\n this.externalIp.setText(output);\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.ProgressDialog;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.net.NetworkInfo;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.Button;\nimport android.widget.ListAdapter;\nimport android.widget.ListView;\nimport android.widget.SimpleAdapter;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Discovery;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class MainActivity extends Activity implements MainAsyncResponse {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n private Discovery discovery = new Discovery();\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView internalIp;\n private TextView externalIp;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n private ProgressDialog scanProgressDialog;\n private Handler mHandler = new Handler();\n private BroadcastReceiver receiver;\n private IntentFilter intentFilter = new IntentFilter();\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.internalIp = (TextView) findViewById(R.id.internalIpAddress);\n this.externalIp = (TextView) findViewById(R.id.externalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n this.wifi = new Wireless(this);\n\n this.macAddress.setText(this.wifi.getMacAddress());\n\n this.receiver = new BroadcastReceiver() {\n\n \/**\n * Detect if a network connection has been lost or established\n * @param context\n * @param intent\n *\/\n @Override\n public void onReceive(Context context, Intent intent) {\n NetworkInfo info = intent.getParcelableExtra(wifi.getWifiManager().EXTRA_NETWORK_INFO);\n if(info != null) {\n if(info.isConnected()) {\n getNetworkInfo();\n }\n else {\n mHandler.removeCallbacksAndMessages(null);\n MainActivity.this.internalIp.setText(\"No WiFi connection\");\n externalIp.setText(\"No WiFi connection\");\n signalStrength.setText(\"No WiFi connection\");\n ssid.setText(\"No WiFi connection\");\n bssid.setText(\"No WiFi connection\");\n }\n }\n }\n };\n\n this.intentFilter.addAction(this.wifi.getWifiManager().NETWORK_STATE_CHANGED_ACTION);\n registerReceiver(receiver, this.intentFilter);\n\n this.discoverHosts.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler to perform host discovery\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n scanProgressDialog = new ProgressDialog(MainActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning For Hosts\");\n scanProgressDialog.setProgressStyle(scanProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(255);\n scanProgressDialog.show();\n\n discovery.scanHosts(wifi.getInternalIpAddress(), MainActivity.this);\n }\n });\n\n this.hostList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open the host activity for a specific host found on the network\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n HashMap map = (HashMap) hostList.getItemAtPosition(position);\n Intent intent = new Intent(MainActivity.this, HostActivity.class);\n String firstLine = map.get(\"First Line\");\n String secondLine = map.get(\"Second Line\");\n String macAddress = map.get(\"Second Line\").substring(secondLine.indexOf(\"[\") + 1, secondLine.indexOf(\"]\"));\n\n intent.putExtra(\"HOST\", firstLine);\n intent.putExtra(\"MAC\", macAddress);\n startActivity(intent);\n }\n });\n\n }\n\n \/**\n * Gets network information about the device and updates various UI elements\n *\/\n private void getNetworkInfo() {\n this.mHandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n this.internalIp.setText(this.wifi.getInternalIpAddress());\n this.wifi.getExternalIpAddress(this);\n this.ssid.setText(this.wifi.getSSID());\n this.bssid.setText(this.wifi.getBSSID());\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n unregisterReceiver(this.receiver);\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n this.scanProgressDialog = null;\n }\n\n \/**\n * Activity restarted\n *\/\n @Override\n public void onRestart() {\n super.onRestart();\n\n registerReceiver(this.receiver, this.intentFilter);\n }\n\n \/**\n * Save the state of an activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n ListAdapter adapter = this.hostList.getAdapter();\n if(adapter != null) {\n ArrayList> adapterData = new ArrayList<>();\n for(int i = 0; i < adapter.getCount(); i++) {\n HashMap item = (HashMap) adapter.getItem(i);\n adapterData.add(item);\n }\n savedState.putSerializable(\"hosts\", adapterData);\n }\n }\n\n \/**\n * Activity state restored\n *\n * @param savedState Saved data from the saved state\n *\/\n @Override\n public void onRestoreInstanceState(Bundle savedState) {\n super.onRestoreInstanceState(savedState);\n\n ArrayList> hosts = (ArrayList) savedState.getSerializable(\"hosts\");\n if(hosts != null) {\n SimpleAdapter newAdapter = new SimpleAdapter(this, hosts, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n this.hostList.setAdapter(newAdapter);\n }\n }\n\n \/**\n * Delegate to update the host list and dismiss the progress dialog\n * Gets called when host discovery has finished\n *\n * @param output The list of hosts to bind to the list view\n *\/\n @Override\n public void processFinish(ArrayList> output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n SimpleAdapter adapter = new SimpleAdapter(this, output, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n ListView hostList = (ListView) this.findViewById(R.id.hostList);\n hostList.setAdapter(adapter);\n this.scanProgressDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to update the progress of the host discovery scan\n *\n * @param output The amount of progress to increment by\n *\/\n @Override\n public void processFinish(int output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.incrementProgressBy(output);\n }\n }\n\n \/**\n * Delegate to handle setting the external IP in the UI\n *\n * @param output External IP\n *\/\n @Override\n public void processFinish(String output) {\n this.externalIp.setText(output);\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.ProgressDialog;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.net.NetworkInfo;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.Button;\nimport android.widget.ListAdapter;\nimport android.widget.ListView;\nimport android.widget.SimpleAdapter;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Discovery;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class MainActivity extends Activity implements MainAsyncResponse {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n private Discovery discovery = new Discovery();\n private Button discoverHosts;\n private ListView hostList;\n private TextView macAddress;\n private TextView internalIp;\n private TextView externalIp;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n private ProgressDialog scanProgressDialog;\n private Handler mHandler = new Handler();\n private BroadcastReceiver receiver;\n private IntentFilter intentFilter = new IntentFilter();\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n this.macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.internalIp = (TextView) findViewById(R.id.internalIpAddress);\n this.externalIp = (TextView) findViewById(R.id.externalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n this.discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n this.wifi = new Wireless(this);\n\n this.macAddress.setText(this.wifi.getMacAddress());\n\n this.receiver = new BroadcastReceiver() {\n\n \/**\n * Detect if a network connection has been lost or established\n * @param context\n * @param intent\n *\/\n @Override\n public void onReceive(Context context, Intent intent) {\n NetworkInfo info = intent.getParcelableExtra(wifi.getWifiManager().EXTRA_NETWORK_INFO);\n if(info != null) {\n if(info.isConnected()) {\n getNetworkInfo();\n }\n else {\n mHandler.removeCallbacksAndMessages(null);\n MainActivity.this.internalIp.setText(\"No WiFi connection\");\n externalIp.setText(\"No WiFi connection\");\n signalStrength.setText(\"No WiFi connection\");\n ssid.setText(\"No WiFi connection\");\n bssid.setText(\"No WiFi connection\");\n }\n }\n }\n };\n\n this.intentFilter.addAction(this.wifi.getWifiManager().NETWORK_STATE_CHANGED_ACTION);\n registerReceiver(receiver, this.intentFilter);\n\n this.discoverHosts.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler to perform host discovery\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n scanProgressDialog = new ProgressDialog(MainActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning For Hosts\");\n scanProgressDialog.setProgressStyle(scanProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(255);\n scanProgressDialog.show();\n\n discovery.scanHosts(wifi.getInternalIpAddress(), MainActivity.this);\n }\n });\n\n this.hostList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open the host activity for a specific host found on the network\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n HashMap map = (HashMap) hostList.getItemAtPosition(position);\n Intent intent = new Intent(MainActivity.this, HostActivity.class);\n String firstLine = map.get(\"First Line\");\n String secondLine = map.get(\"Second Line\");\n String macAddress = map.get(\"Second Line\").substring(secondLine.indexOf(\"[\") + 1, secondLine.indexOf(\"]\"));\n\n intent.putExtra(\"HOST\", firstLine);\n intent.putExtra(\"MAC\", macAddress);\n startActivity(intent);\n }\n });\n\n }\n\n \/**\n * Gets network information about the device and updates various UI elements\n *\/\n private void getNetworkInfo() {\n this.mHandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n this.internalIp.setText(this.wifi.getInternalIpAddress());\n this.wifi.getExternalIpAddress(this);\n this.ssid.setText(this.wifi.getSSID());\n this.bssid.setText(this.wifi.getBSSID());\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n unregisterReceiver(this.receiver);\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n this.scanProgressDialog = null;\n }\n\n \/**\n * Activity restarted\n *\/\n @Override\n public void onRestart() {\n super.onRestart();\n\n registerReceiver(this.receiver, this.intentFilter);\n }\n\n \/**\n * Save the state of an activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n ListAdapter adapter = this.hostList.getAdapter();\n if(adapter != null) {\n ArrayList> adapterData = new ArrayList<>();\n for(int i = 0; i < adapter.getCount(); i++) {\n HashMap item = (HashMap) adapter.getItem(i);\n adapterData.add(item);\n }\n savedState.putSerializable(\"hosts\", adapterData);\n }\n }\n\n \/**\n * Activity state restored\n *\n * @param savedState Saved data from the saved state\n *\/\n @Override\n public void onRestoreInstanceState(Bundle savedState) {\n super.onRestoreInstanceState(savedState);\n\n ArrayList> hosts = (ArrayList) savedState.getSerializable(\"hosts\");\n if(hosts != null) {\n SimpleAdapter newAdapter = new SimpleAdapter(this, hosts, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n this.hostList.setAdapter(newAdapter);\n }\n }\n\n \/**\n * Delegate to update the host list and dismiss the progress dialog\n * Gets called when host discovery has finished\n *\n * @param output The list of hosts to bind to the list view\n *\/\n @Override\n public void processFinish(ArrayList> output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n SimpleAdapter adapter = new SimpleAdapter(this, output, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n ListView hostList = (ListView) this.findViewById(R.id.hostList);\n hostList.setAdapter(adapter);\n this.scanProgressDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to update the progress of the host discovery scan\n *\n * @param output The amount of progress to increment by\n *\/\n @Override\n public void processFinish(int output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.incrementProgressBy(output);\n }\n }\n\n \/**\n * Delegate to handle setting the external IP in the UI\n *\n * @param output External IP\n *\/\n @Override\n public void processFinish(String output) {\n this.externalIp.setText(output);\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.ProgressDialog;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.net.NetworkInfo;\nimport android.net.wifi.WifiManager;\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.Button;\nimport android.widget.ListAdapter;\nimport android.widget.ListView;\nimport android.widget.SimpleAdapter;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Discovery;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.MainAsyncResponse;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class MainActivity extends Activity implements MainAsyncResponse {\n\n private final static int TIMER_INTERVAL = 1500;\n\n private Wireless wifi;\n private Discovery discovery = new Discovery();\n private ListView hostList;\n private TextView internalIp;\n private TextView externalIp;\n private TextView signalStrength;\n private TextView ssid;\n private TextView bssid;\n private ProgressDialog scanProgressDialog;\n private Handler mHandler = new Handler();\n private BroadcastReceiver receiver;\n private IntentFilter intentFilter = new IntentFilter();\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n this.hostList = (ListView) findViewById(R.id.hostList);\n TextView macAddress = (TextView) findViewById(R.id.deviceMacAddress);\n this.internalIp = (TextView) findViewById(R.id.internalIpAddress);\n this.externalIp = (TextView) findViewById(R.id.externalIpAddress);\n this.signalStrength = (TextView) findViewById(R.id.signalStrength);\n Button discoverHosts = (Button) findViewById(R.id.discoverHosts);\n this.ssid = (TextView) findViewById(R.id.ssid);\n this.bssid = (TextView) findViewById(R.id.bssid);\n\n this.wifi = new Wireless(this);\n\n macAddress.setText(this.wifi.getMacAddress());\n\n this.receiver = new BroadcastReceiver() {\n\n \/**\n * Detect if a network connection has been lost or established\n * @param context\n * @param intent\n *\/\n @Override\n public void onReceive(Context context, Intent intent) {\n NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);\n if(info != null) {\n if(info.isConnected()) {\n getNetworkInfo();\n }\n else {\n mHandler.removeCallbacksAndMessages(null);\n MainActivity.this.internalIp.setText(\"No WiFi connection\");\n externalIp.setText(\"No WiFi connection\");\n signalStrength.setText(\"No WiFi connection\");\n ssid.setText(\"No WiFi connection\");\n bssid.setText(\"No WiFi connection\");\n }\n }\n }\n };\n\n this.intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);\n registerReceiver(receiver, this.intentFilter);\n\n discoverHosts.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler to perform host discovery\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n scanProgressDialog = new ProgressDialog(MainActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning For Hosts\");\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(255);\n scanProgressDialog.show();\n\n discovery.scanHosts(wifi.getInternalIpAddress(), MainActivity.this);\n }\n });\n\n this.hostList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open the host activity for a specific host found on the network\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n HashMap map = (HashMap) hostList.getItemAtPosition(position);\n Intent intent = new Intent(MainActivity.this, HostActivity.class);\n String firstLine = map.get(\"First Line\");\n String secondLine = map.get(\"Second Line\");\n String macAddress = map.get(\"Second Line\").substring(secondLine.indexOf(\"[\") + 1, secondLine.indexOf(\"]\"));\n\n intent.putExtra(\"HOST\", firstLine);\n intent.putExtra(\"MAC\", macAddress);\n startActivity(intent);\n }\n });\n\n }\n\n \/**\n * Gets network information about the device and updates various UI elements\n *\/\n private void getNetworkInfo() {\n this.mHandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n signalStrength.setText(String.valueOf(wifi.getSignalStrength()) + \" dBm\");\n mHandler.postDelayed(this, TIMER_INTERVAL);\n }\n }, 0);\n this.internalIp.setText(this.wifi.getInternalIpAddress());\n this.wifi.getExternalIpAddress(this);\n this.ssid.setText(this.wifi.getSSID());\n this.bssid.setText(this.wifi.getBSSID());\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n unregisterReceiver(this.receiver);\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n this.scanProgressDialog = null;\n }\n\n \/**\n * Activity restarted\n *\/\n @Override\n public void onRestart() {\n super.onRestart();\n\n registerReceiver(this.receiver, this.intentFilter);\n }\n\n \/**\n * Save the state of an activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n ListAdapter adapter = this.hostList.getAdapter();\n if(adapter != null) {\n ArrayList> adapterData = new ArrayList<>();\n for(int i = 0; i < adapter.getCount(); i++) {\n HashMap item = (HashMap) adapter.getItem(i);\n adapterData.add(item);\n }\n savedState.putSerializable(\"hosts\", adapterData);\n }\n }\n\n \/**\n * Activity state restored\n *\n * @param savedState Saved data from the saved state\n *\/\n @Override\n public void onRestoreInstanceState(Bundle savedState) {\n super.onRestoreInstanceState(savedState);\n\n ArrayList> hosts = (ArrayList) savedState.getSerializable(\"hosts\");\n if(hosts != null) {\n SimpleAdapter newAdapter = new SimpleAdapter(this, hosts, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n this.hostList.setAdapter(newAdapter);\n }\n }\n\n \/**\n * Delegate to update the host list and dismiss the progress dialog\n * Gets called when host discovery has finished\n *\n * @param output The list of hosts to bind to the list view\n *\/\n @Override\n public void processFinish(ArrayList> output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n SimpleAdapter adapter = new SimpleAdapter(this, output, android.R.layout.simple_list_item_2, new String[]{\"First Line\", \"Second Line\"}, new int[]{android.R.id.text1, android.R.id.text2});\n ListView hostList = (ListView) this.findViewById(R.id.hostList);\n hostList.setAdapter(adapter);\n this.scanProgressDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to update the progress of the host discovery scan\n *\n * @param output The amount of progress to increment by\n *\/\n @Override\n public void processFinish(int output) {\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.incrementProgressBy(output);\n }\n }\n\n \/**\n * Delegate to handle setting the external IP in the UI\n *\n * @param output External IP\n *\/\n @Override\n public void processFinish(String output) {\n this.externalIp.setText(output);\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/aaronjwood\/PortAuthority\/commit\/6c67fe9803700616899393f0cd15eefbe93bb58d","commit_message":"'\\\\\"Use the faster version of indexOf with a char\\\\n\\\\\"'","source_code":"package com.aaronjwood.portauthority.activity;\n\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.database.Cursor;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.SparseArray;\nimport android.view.View;\nimport android.view.animation.AnimationUtils;\nimport android.view.animation.LayoutAnimationController;\nimport android.widget.AdapterView;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.db.Database;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.utils.Constants;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\n\npublic abstract class HostActivity extends AppCompatActivity implements HostAsyncResponse {\n\n protected int layout;\n protected ArrayAdapter adapter;\n protected ListView portList;\n protected ArrayList ports = new ArrayList<>();\n protected ProgressDialog scanProgressDialog;\n protected Dialog portRangeDialog;\n private Database db;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(this.layout);\n\n db = new Database(this);\n setupPortsAdapter();\n }\n\n \/**\n * Sets up animations for the activity\n *\/\n protected void setAnimations() {\n LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(this, R.anim.layout_slide_in_bottom);\n portList.setLayoutAnimation(animation);\n }\n\n \/**\n * Sets up the adapter to handle discovered ports\n *\/\n private void setupPortsAdapter() {\n this.portList = (ListView) findViewById(R.id.portList);\n this.adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.port_list_item, ports);\n this.portList.setAdapter(this.adapter);\n this.setAnimations();\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if (this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if (this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Clean up\n *\/\n @Override\n protected void onDestroy() {\n super.onDestroy();\n\n if (db != null) {\n db.close();\n }\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"ports\", ports);\n }\n\n \/**\n * Restore saved data\n *\n * @param savedInstanceState Data from a saved state\n *\/\n public void onRestoreInstanceState(Bundle savedInstanceState) {\n super.onRestoreInstanceState(savedInstanceState);\n\n ports = savedInstanceState.getStringArrayList(\"ports\");\n\n this.setupPortsAdapter();\n }\n\n \/**\n * Event handler for when the port range reset is triggered\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n *\/\n protected void resetPortRangeScanClick(final NumberPicker start, final NumberPicker stop) {\n portRangeDialog.findViewById(R.id.resetPortRangeScan).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n start.setValue(Constants.MIN_PORT_VALUE);\n stop.setValue(Constants.MAX_PORT_VALUE);\n }\n });\n }\n\n \/**\n * Event handler for when the port range scan is finally initiated\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n * @param timeout Socket timeout\n * @param activity Calling activity\n * @param ip IP address\n *\/\n protected void startPortRangeScanClick(final NumberPicker start, final NumberPicker stop, final int timeout, final HostActivity activity, final String ip) {\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n start.clearFocus();\n stop.clearFocus();\n\n int startPort = start.getValue();\n int stopPort = stop.getValue();\n if ((startPort - stopPort > 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n UserPreference.savePortRangeStart(activity, startPort);\n UserPreference.savePortRangeHigh(activity, stopPort);\n\n ports.clear();\n\n scanProgressDialog = new ProgressDialog(activity, R.style.DialogTheme);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n Host.scanPorts(ip, startPort, stopPort, timeout, activity);\n }\n });\n }\n\n \/**\n * Event handler for when an item on the port list is clicked\n *\/\n protected void portListClick(final String ip) {\n this.portList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open certain ports to the browser\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n String item = (String) portList.getItemAtPosition(position);\n if (item == null) {\n return;\n }\n\n Intent intent = null;\n\n if (item.contains(\"80 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip));\n }\n\n if (item.contains(\"443 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"https:\/\/\" + ip));\n }\n\n if (item.contains(\"8080 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip + \":8080\"));\n }\n\n PackageManager packageManager = getPackageManager();\n if (intent != null && packageManager != null) {\n if (packageManager.resolveActivity(intent, 0) != null) {\n startActivity(intent);\n } else {\n Toast.makeText(getApplicationContext(), \"No application found to open this to the browser!\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n });\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n if (scanProgressDialog != null) {\n scanProgressDialog.incrementProgressBy(output);\n }\n }\n });\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(SparseArray output) {\n int scannedPort = output.keyAt(0);\n String item = String.valueOf(scannedPort);\n\n Cursor cursor = db.queryDatabase(\"SELECT name, port FROM ports WHERE port = ?\", new String[]{Integer.toString(scannedPort)});\n\n if (cursor != null) {\n try {\n if (cursor.moveToFirst()) {\n String name = cursor.getString(cursor.getColumnIndex(\"name\"));\n name = (name.isEmpty()) ? \"unknown\" : name;\n item = this.formatOpenPort(output, scannedPort, name, item);\n this.addOpenPort(item);\n }\n } finally {\n cursor.close();\n }\n }\n }\n\n \/**\n * Formats a found open port with its name, description, and associated visualization\n *\n * @param entry Structure holding information about the found open port with its description\n * @param scannedPort The port number\n * @param portName Friendly name for the port\n * @param item Contains the transformed output for the open port\n * @return If all associated data is found a port along with its description, underlying service, and visualization is constructed\n *\/\n private String formatOpenPort(SparseArray entry, int scannedPort, String portName, String item) {\n item = item + \" - \" + portName;\n if (entry.get(scannedPort) != null) {\n item += \" (\" + entry.get(scannedPort) + \")\";\n }\n\n \/\/If the port is in any way related to HTTP then present a nice globe icon next to it via unicode\n if (scannedPort == 80 || scannedPort == 443 || scannedPort == 8080) {\n item += \" \\uD83C\\uDF0E\";\n }\n\n return item;\n }\n\n \/**\n * Adds an open port that was found on a host to the list\n *\n * @param port Port number and description\n *\/\n private void addOpenPort(final String port) {\n setAnimations();\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n synchronized (ports) {\n ports.add(port);\n\n Collections.sort(ports, new Comparator() {\n\n @Override\n public int compare(String lhs, String rhs) {\n int left = Integer.parseInt(lhs.substring(0, lhs.indexOf(\"-\") - 1));\n int right = Integer.parseInt(rhs.substring(0, rhs.indexOf(\"-\") - 1));\n\n return left - right;\n }\n });\n\n adapter.notifyDataSetChanged();\n }\n }\n });\n }\n}\n","target_code":"package com.aaronjwood.portauthority.activity;\n\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.database.Cursor;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.SparseArray;\nimport android.view.View;\nimport android.view.animation.AnimationUtils;\nimport android.view.animation.LayoutAnimationController;\nimport android.widget.AdapterView;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.db.Database;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.utils.Constants;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\n\npublic abstract class HostActivity extends AppCompatActivity implements HostAsyncResponse {\n\n protected int layout;\n protected ArrayAdapter adapter;\n protected ListView portList;\n protected ArrayList ports = new ArrayList<>();\n protected ProgressDialog scanProgressDialog;\n protected Dialog portRangeDialog;\n private Database db;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(this.layout);\n\n db = new Database(this);\n setupPortsAdapter();\n }\n\n \/**\n * Sets up animations for the activity\n *\/\n protected void setAnimations() {\n LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(this, R.anim.layout_slide_in_bottom);\n portList.setLayoutAnimation(animation);\n }\n\n \/**\n * Sets up the adapter to handle discovered ports\n *\/\n private void setupPortsAdapter() {\n this.portList = (ListView) findViewById(R.id.portList);\n this.adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.port_list_item, ports);\n this.portList.setAdapter(this.adapter);\n this.setAnimations();\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if (this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if (this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Clean up\n *\/\n @Override\n protected void onDestroy() {\n super.onDestroy();\n\n if (db != null) {\n db.close();\n }\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"ports\", ports);\n }\n\n \/**\n * Restore saved data\n *\n * @param savedInstanceState Data from a saved state\n *\/\n public void onRestoreInstanceState(Bundle savedInstanceState) {\n super.onRestoreInstanceState(savedInstanceState);\n\n ports = savedInstanceState.getStringArrayList(\"ports\");\n\n this.setupPortsAdapter();\n }\n\n \/**\n * Event handler for when the port range reset is triggered\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n *\/\n protected void resetPortRangeScanClick(final NumberPicker start, final NumberPicker stop) {\n portRangeDialog.findViewById(R.id.resetPortRangeScan).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n start.setValue(Constants.MIN_PORT_VALUE);\n stop.setValue(Constants.MAX_PORT_VALUE);\n }\n });\n }\n\n \/**\n * Event handler for when the port range scan is finally initiated\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n * @param timeout Socket timeout\n * @param activity Calling activity\n * @param ip IP address\n *\/\n protected void startPortRangeScanClick(final NumberPicker start, final NumberPicker stop, final int timeout, final HostActivity activity, final String ip) {\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n start.clearFocus();\n stop.clearFocus();\n\n int startPort = start.getValue();\n int stopPort = stop.getValue();\n if ((startPort - stopPort > 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n UserPreference.savePortRangeStart(activity, startPort);\n UserPreference.savePortRangeHigh(activity, stopPort);\n\n ports.clear();\n\n scanProgressDialog = new ProgressDialog(activity, R.style.DialogTheme);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n Host.scanPorts(ip, startPort, stopPort, timeout, activity);\n }\n });\n }\n\n \/**\n * Event handler for when an item on the port list is clicked\n *\/\n protected void portListClick(final String ip) {\n this.portList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open certain ports to the browser\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n String item = (String) portList.getItemAtPosition(position);\n if (item == null) {\n return;\n }\n\n Intent intent = null;\n\n if (item.contains(\"80 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip));\n }\n\n if (item.contains(\"443 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"https:\/\/\" + ip));\n }\n\n if (item.contains(\"8080 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip + \":8080\"));\n }\n\n PackageManager packageManager = getPackageManager();\n if (intent != null && packageManager != null) {\n if (packageManager.resolveActivity(intent, 0) != null) {\n startActivity(intent);\n } else {\n Toast.makeText(getApplicationContext(), \"No application found to open this to the browser!\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n });\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n if (scanProgressDialog != null) {\n scanProgressDialog.incrementProgressBy(output);\n }\n }\n });\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(SparseArray output) {\n int scannedPort = output.keyAt(0);\n String item = String.valueOf(scannedPort);\n\n Cursor cursor = db.queryDatabase(\"SELECT name, port FROM ports WHERE port = ?\", new String[]{Integer.toString(scannedPort)});\n\n if (cursor != null) {\n try {\n if (cursor.moveToFirst()) {\n String name = cursor.getString(cursor.getColumnIndex(\"name\"));\n name = (name.isEmpty()) ? \"unknown\" : name;\n item = this.formatOpenPort(output, scannedPort, name, item);\n this.addOpenPort(item);\n }\n } finally {\n cursor.close();\n }\n }\n }\n\n \/**\n * Formats a found open port with its name, description, and associated visualization\n *\n * @param entry Structure holding information about the found open port with its description\n * @param scannedPort The port number\n * @param portName Friendly name for the port\n * @param item Contains the transformed output for the open port\n * @return If all associated data is found a port along with its description, underlying service, and visualization is constructed\n *\/\n private String formatOpenPort(SparseArray entry, int scannedPort, String portName, String item) {\n item = item + \" - \" + portName;\n if (entry.get(scannedPort) != null) {\n item += \" (\" + entry.get(scannedPort) + \")\";\n }\n\n \/\/If the port is in any way related to HTTP then present a nice globe icon next to it via unicode\n if (scannedPort == 80 || scannedPort == 443 || scannedPort == 8080) {\n item += \" \\uD83C\\uDF0E\";\n }\n\n return item;\n }\n\n \/**\n * Adds an open port that was found on a host to the list\n *\n * @param port Port number and description\n *\/\n private void addOpenPort(final String port) {\n setAnimations();\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n synchronized (ports) {\n ports.add(port);\n\n Collections.sort(ports, new Comparator() {\n\n @Override\n public int compare(String lhs, String rhs) {\n int left = Integer.parseInt(lhs.substring(0, lhs.indexOf('-') - 1));\n int right = Integer.parseInt(rhs.substring(0, rhs.indexOf('-') - 1));\n\n return left - right;\n }\n });\n\n adapter.notifyDataSetChanged();\n }\n }\n });\n }\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.database.Cursor;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.SparseArray;\nimport android.view.View;\nimport android.view.animation.AnimationUtils;\nimport android.view.animation.LayoutAnimationController;\nimport android.widget.AdapterView;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.db.Database;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.utils.Constants;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\n\npublic abstract class HostActivity extends AppCompatActivity implements HostAsyncResponse {\n\n protected int layout;\n protected ArrayAdapter adapter;\n protected ListView portList;\n protected ArrayList ports = new ArrayList<>();\n protected ProgressDialog scanProgressDialog;\n protected Dialog portRangeDialog;\n private Database db;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(this.layout);\n\n db = new Database(this);\n setupPortsAdapter();\n }\n\n \/**\n * Sets up animations for the activity\n *\/\n protected void setAnimations() {\n LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(this, R.anim.layout_slide_in_bottom);\n portList.setLayoutAnimation(animation);\n }\n\n \/**\n * Sets up the adapter to handle discovered ports\n *\/\n private void setupPortsAdapter() {\n this.portList = (ListView) findViewById(R.id.portList);\n this.adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.port_list_item, ports);\n this.portList.setAdapter(this.adapter);\n this.setAnimations();\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if (this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if (this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Clean up\n *\/\n @Override\n protected void onDestroy() {\n super.onDestroy();\n\n if (db != null) {\n db.close();\n }\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"ports\", ports);\n }\n\n \/**\n * Restore saved data\n *\n * @param savedInstanceState Data from a saved state\n *\/\n public void onRestoreInstanceState(Bundle savedInstanceState) {\n super.onRestoreInstanceState(savedInstanceState);\n\n ports = savedInstanceState.getStringArrayList(\"ports\");\n\n this.setupPortsAdapter();\n }\n\n \/**\n * Event handler for when the port range reset is triggered\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n *\/\n protected void resetPortRangeScanClick(final NumberPicker start, final NumberPicker stop) {\n portRangeDialog.findViewById(R.id.resetPortRangeScan).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n start.setValue(Constants.MIN_PORT_VALUE);\n stop.setValue(Constants.MAX_PORT_VALUE);\n }\n });\n }\n\n \/**\n * Event handler for when the port range scan is finally initiated\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n * @param timeout Socket timeout\n * @param activity Calling activity\n * @param ip IP address\n *\/\n protected void startPortRangeScanClick(final NumberPicker start, final NumberPicker stop, final int timeout, final HostActivity activity, final String ip) {\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n start.clearFocus();\n stop.clearFocus();\n\n int startPort = start.getValue();\n int stopPort = stop.getValue();\n if ((startPort - stopPort > 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n UserPreference.savePortRangeStart(activity, startPort);\n UserPreference.savePortRangeHigh(activity, stopPort);\n\n ports.clear();\n\n scanProgressDialog = new ProgressDialog(activity, R.style.DialogTheme);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n Host.scanPorts(ip, startPort, stopPort, timeout, activity);\n }\n });\n }\n\n \/**\n * Event handler for when an item on the port list is clicked\n *\/\n protected void portListClick(final String ip) {\n this.portList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open certain ports to the browser\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n String item = (String) portList.getItemAtPosition(position);\n if (item == null) {\n return;\n }\n\n Intent intent = null;\n\n if (item.contains(\"80 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip));\n }\n\n if (item.contains(\"443 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"https:\/\/\" + ip));\n }\n\n if (item.contains(\"8080 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip + \":8080\"));\n }\n\n PackageManager packageManager = getPackageManager();\n if (intent != null && packageManager != null) {\n if (packageManager.resolveActivity(intent, 0) != null) {\n startActivity(intent);\n } else {\n Toast.makeText(getApplicationContext(), \"No application found to open this to the browser!\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n });\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n if (scanProgressDialog != null) {\n scanProgressDialog.incrementProgressBy(output);\n }\n }\n });\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(SparseArray output) {\n int scannedPort = output.keyAt(0);\n String item = String.valueOf(scannedPort);\n\n Cursor cursor = db.queryDatabase(\"SELECT name, port FROM ports WHERE port = ?\", new String[]{Integer.toString(scannedPort)});\n\n if (cursor != null) {\n try {\n if (cursor.moveToFirst()) {\n String name = cursor.getString(cursor.getColumnIndex(\"name\"));\n name = (name.isEmpty()) ? \"unknown\" : name;\n item = this.formatOpenPort(output, scannedPort, name, item);\n this.addOpenPort(item);\n }\n } finally {\n cursor.close();\n }\n }\n }\n\n \/**\n * Formats a found open port with its name, description, and associated visualization\n *\n * @param entry Structure holding information about the found open port with its description\n * @param scannedPort The port number\n * @param portName Friendly name for the port\n * @param item Contains the transformed output for the open port\n * @return If all associated data is found a port along with its description, underlying service, and visualization is constructed\n *\/\n private String formatOpenPort(SparseArray entry, int scannedPort, String portName, String item) {\n item = item + \" - \" + portName;\n if (entry.get(scannedPort) != null) {\n item += \" (\" + entry.get(scannedPort) + \")\";\n }\n\n \/\/If the port is in any way related to HTTP then present a nice globe icon next to it via unicode\n if (scannedPort == 80 || scannedPort == 443 || scannedPort == 8080) {\n item += \" \\uD83C\\uDF0E\";\n }\n\n return item;\n }\n\n \/**\n * Adds an open port that was found on a host to the list\n *\n * @param port Port number and description\n *\/\n private void addOpenPort(final String port) {\n setAnimations();\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n synchronized (ports) {\n ports.add(port);\n\n Collections.sort(ports, new Comparator() {\n\n @Override\n public int compare(String lhs, String rhs) {\n int left = Integer.parseInt(lhs.substring(0, lhs.indexOf(\"-\") - 1));\n int right = Integer.parseInt(rhs.substring(0, rhs.indexOf(\"-\") - 1));\n\n return left - right;\n }\n });\n\n adapter.notifyDataSetChanged();\n }\n }\n });\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.database.Cursor;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.SparseArray;\nimport android.view.View;\nimport android.view.animation.AnimationUtils;\nimport android.view.animation.LayoutAnimationController;\nimport android.widget.AdapterView;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.db.Database;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.utils.Constants;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\n\npublic abstract class HostActivity extends AppCompatActivity implements HostAsyncResponse {\n\n protected int layout;\n protected ArrayAdapter adapter;\n protected ListView portList;\n protected ArrayList ports = new ArrayList<>();\n protected ProgressDialog scanProgressDialog;\n protected Dialog portRangeDialog;\n private Database db;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(this.layout);\n\n db = new Database(this);\n setupPortsAdapter();\n }\n\n \/**\n * Sets up animations for the activity\n *\/\n protected void setAnimations() {\n LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(this, R.anim.layout_slide_in_bottom);\n portList.setLayoutAnimation(animation);\n }\n\n \/**\n * Sets up the adapter to handle discovered ports\n *\/\n private void setupPortsAdapter() {\n this.portList = (ListView) findViewById(R.id.portList);\n this.adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.port_list_item, ports);\n this.portList.setAdapter(this.adapter);\n this.setAnimations();\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if (this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if (this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Clean up\n *\/\n @Override\n protected void onDestroy() {\n super.onDestroy();\n\n if (db != null) {\n db.close();\n }\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"ports\", ports);\n }\n\n \/**\n * Restore saved data\n *\n * @param savedInstanceState Data from a saved state\n *\/\n public void onRestoreInstanceState(Bundle savedInstanceState) {\n super.onRestoreInstanceState(savedInstanceState);\n\n ports = savedInstanceState.getStringArrayList(\"ports\");\n\n this.setupPortsAdapter();\n }\n\n \/**\n * Event handler for when the port range reset is triggered\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n *\/\n protected void resetPortRangeScanClick(final NumberPicker start, final NumberPicker stop) {\n portRangeDialog.findViewById(R.id.resetPortRangeScan).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n start.setValue(Constants.MIN_PORT_VALUE);\n stop.setValue(Constants.MAX_PORT_VALUE);\n }\n });\n }\n\n \/**\n * Event handler for when the port range scan is finally initiated\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n * @param timeout Socket timeout\n * @param activity Calling activity\n * @param ip IP address\n *\/\n protected void startPortRangeScanClick(final NumberPicker start, final NumberPicker stop, final int timeout, final HostActivity activity, final String ip) {\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n start.clearFocus();\n stop.clearFocus();\n\n int startPort = start.getValue();\n int stopPort = stop.getValue();\n if ((startPort - stopPort > 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n UserPreference.savePortRangeStart(activity, startPort);\n UserPreference.savePortRangeHigh(activity, stopPort);\n\n ports.clear();\n\n scanProgressDialog = new ProgressDialog(activity, R.style.DialogTheme);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n Host.scanPorts(ip, startPort, stopPort, timeout, activity);\n }\n });\n }\n\n \/**\n * Event handler for when an item on the port list is clicked\n *\/\n protected void portListClick(final String ip) {\n this.portList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open certain ports to the browser\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n String item = (String) portList.getItemAtPosition(position);\n if (item == null) {\n return;\n }\n\n Intent intent = null;\n\n if (item.contains(\"80 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip));\n }\n\n if (item.contains(\"443 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"https:\/\/\" + ip));\n }\n\n if (item.contains(\"8080 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip + \":8080\"));\n }\n\n PackageManager packageManager = getPackageManager();\n if (intent != null && packageManager != null) {\n if (packageManager.resolveActivity(intent, 0) != null) {\n startActivity(intent);\n } else {\n Toast.makeText(getApplicationContext(), \"No application found to open this to the browser!\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n });\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n if (scanProgressDialog != null) {\n scanProgressDialog.incrementProgressBy(output);\n }\n }\n });\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(SparseArray output) {\n int scannedPort = output.keyAt(0);\n String item = String.valueOf(scannedPort);\n\n Cursor cursor = db.queryDatabase(\"SELECT name, port FROM ports WHERE port = ?\", new String[]{Integer.toString(scannedPort)});\n\n if (cursor != null) {\n try {\n if (cursor.moveToFirst()) {\n String name = cursor.getString(cursor.getColumnIndex(\"name\"));\n name = (name.isEmpty()) ? \"unknown\" : name;\n item = this.formatOpenPort(output, scannedPort, name, item);\n this.addOpenPort(item);\n }\n } finally {\n cursor.close();\n }\n }\n }\n\n \/**\n * Formats a found open port with its name, description, and associated visualization\n *\n * @param entry Structure holding information about the found open port with its description\n * @param scannedPort The port number\n * @param portName Friendly name for the port\n * @param item Contains the transformed output for the open port\n * @return If all associated data is found a port along with its description, underlying service, and visualization is constructed\n *\/\n private String formatOpenPort(SparseArray entry, int scannedPort, String portName, String item) {\n item = item + \" - \" + portName;\n if (entry.get(scannedPort) != null) {\n item += \" (\" + entry.get(scannedPort) + \")\";\n }\n\n \/\/If the port is in any way related to HTTP then present a nice globe icon next to it via unicode\n if (scannedPort == 80 || scannedPort == 443 || scannedPort == 8080) {\n item += \" \\uD83C\\uDF0E\";\n }\n\n return item;\n }\n\n \/**\n * Adds an open port that was found on a host to the list\n *\n * @param port Port number and description\n *\/\n private void addOpenPort(final String port) {\n setAnimations();\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n synchronized (ports) {\n ports.add(port);\n\n Collections.sort(ports, new Comparator() {\n\n @Override\n public int compare(String lhs, String rhs) {\n int left = Integer.parseInt(lhs.substring(0, lhs.indexOf(\"-\") - 1));\n int right = Integer.parseInt(rhs.substring(0, rhs.indexOf(\"-\") - 1));\n\n return left - right;\n }\n });\n\n adapter.notifyDataSetChanged();\n }\n }\n });\n }\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.database.Cursor;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.SparseArray;\nimport android.view.View;\nimport android.view.animation.AnimationUtils;\nimport android.view.animation.LayoutAnimationController;\nimport android.widget.AdapterView;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.db.Database;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.utils.Constants;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\n\npublic abstract class HostActivity extends AppCompatActivity implements HostAsyncResponse {\n\n protected int layout;\n protected ArrayAdapter adapter;\n protected ListView portList;\n protected ArrayList ports = new ArrayList<>();\n protected ProgressDialog scanProgressDialog;\n protected Dialog portRangeDialog;\n private Database db;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(this.layout);\n\n db = new Database(this);\n setupPortsAdapter();\n }\n\n \/**\n * Sets up animations for the activity\n *\/\n protected void setAnimations() {\n LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(this, R.anim.layout_slide_in_bottom);\n portList.setLayoutAnimation(animation);\n }\n\n \/**\n * Sets up the adapter to handle discovered ports\n *\/\n private void setupPortsAdapter() {\n this.portList = (ListView) findViewById(R.id.portList);\n this.adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.port_list_item, ports);\n this.portList.setAdapter(this.adapter);\n this.setAnimations();\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if (this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if (this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Clean up\n *\/\n @Override\n protected void onDestroy() {\n super.onDestroy();\n\n if (db != null) {\n db.close();\n }\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"ports\", ports);\n }\n\n \/**\n * Restore saved data\n *\n * @param savedInstanceState Data from a saved state\n *\/\n public void onRestoreInstanceState(Bundle savedInstanceState) {\n super.onRestoreInstanceState(savedInstanceState);\n\n ports = savedInstanceState.getStringArrayList(\"ports\");\n\n this.setupPortsAdapter();\n }\n\n \/**\n * Event handler for when the port range reset is triggered\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n *\/\n protected void resetPortRangeScanClick(final NumberPicker start, final NumberPicker stop) {\n portRangeDialog.findViewById(R.id.resetPortRangeScan).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n start.setValue(Constants.MIN_PORT_VALUE);\n stop.setValue(Constants.MAX_PORT_VALUE);\n }\n });\n }\n\n \/**\n * Event handler for when the port range scan is finally initiated\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n * @param timeout Socket timeout\n * @param activity Calling activity\n * @param ip IP address\n *\/\n protected void startPortRangeScanClick(final NumberPicker start, final NumberPicker stop, final int timeout, final HostActivity activity, final String ip) {\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n start.clearFocus();\n stop.clearFocus();\n\n int startPort = start.getValue();\n int stopPort = stop.getValue();\n if ((startPort - stopPort > 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n UserPreference.savePortRangeStart(activity, startPort);\n UserPreference.savePortRangeHigh(activity, stopPort);\n\n ports.clear();\n\n scanProgressDialog = new ProgressDialog(activity, R.style.DialogTheme);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n Host.scanPorts(ip, startPort, stopPort, timeout, activity);\n }\n });\n }\n\n \/**\n * Event handler for when an item on the port list is clicked\n *\/\n protected void portListClick(final String ip) {\n this.portList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open certain ports to the browser\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n String item = (String) portList.getItemAtPosition(position);\n if (item == null) {\n return;\n }\n\n Intent intent = null;\n\n if (item.contains(\"80 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip));\n }\n\n if (item.contains(\"443 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"https:\/\/\" + ip));\n }\n\n if (item.contains(\"8080 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip + \":8080\"));\n }\n\n PackageManager packageManager = getPackageManager();\n if (intent != null && packageManager != null) {\n if (packageManager.resolveActivity(intent, 0) != null) {\n startActivity(intent);\n } else {\n Toast.makeText(getApplicationContext(), \"No application found to open this to the browser!\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n });\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n if (scanProgressDialog != null) {\n scanProgressDialog.incrementProgressBy(output);\n }\n }\n });\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(SparseArray output) {\n int scannedPort = output.keyAt(0);\n String item = String.valueOf(scannedPort);\n\n Cursor cursor = db.queryDatabase(\"SELECT name, port FROM ports WHERE port = ?\", new String[]{Integer.toString(scannedPort)});\n\n if (cursor != null) {\n try {\n if (cursor.moveToFirst()) {\n String name = cursor.getString(cursor.getColumnIndex(\"name\"));\n name = (name.isEmpty()) ? \"unknown\" : name;\n item = this.formatOpenPort(output, scannedPort, name, item);\n this.addOpenPort(item);\n }\n } finally {\n cursor.close();\n }\n }\n }\n\n \/**\n * Formats a found open port with its name, description, and associated visualization\n *\n * @param entry Structure holding information about the found open port with its description\n * @param scannedPort The port number\n * @param portName Friendly name for the port\n * @param item Contains the transformed output for the open port\n * @return If all associated data is found a port along with its description, underlying service, and visualization is constructed\n *\/\n private String formatOpenPort(SparseArray entry, int scannedPort, String portName, String item) {\n item = item + \" - \" + portName;\n if (entry.get(scannedPort) != null) {\n item += \" (\" + entry.get(scannedPort) + \")\";\n }\n\n \/\/If the port is in any way related to HTTP then present a nice globe icon next to it via unicode\n if (scannedPort == 80 || scannedPort == 443 || scannedPort == 8080) {\n item += \" \\uD83C\\uDF0E\";\n }\n\n return item;\n }\n\n \/**\n * Adds an open port that was found on a host to the list\n *\n * @param port Port number and description\n *\/\n private void addOpenPort(final String port) {\n setAnimations();\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n synchronized (ports) {\n ports.add(port);\n\n Collections.sort(ports, new Comparator() {\n\n @Override\n public int compare(String lhs, String rhs) {\n int left = Integer.parseInt(lhs.substring(0, lhs.indexOf(\"-\") - 1));\n int right = Integer.parseInt(rhs.substring(0, rhs.indexOf(\"-\") - 1));\n\n return left - right;\n }\n });\n\n adapter.notifyDataSetChanged();\n }\n }\n });\n }\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRewrite compare function to improve execution performance. Write the entire code and no other text in the response.\n\n### Concepts:\n[in] compare function\n\n### Given program:\n```java\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.database.Cursor;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.SparseArray;\nimport android.view.View;\nimport android.view.animation.AnimationUtils;\nimport android.view.animation.LayoutAnimationController;\nimport android.widget.AdapterView;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.db.Database;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.utils.Constants;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\n\npublic abstract class HostActivity extends AppCompatActivity implements HostAsyncResponse {\n\n protected int layout;\n protected ArrayAdapter adapter;\n protected ListView portList;\n protected ArrayList ports = new ArrayList<>();\n protected ProgressDialog scanProgressDialog;\n protected Dialog portRangeDialog;\n private Database db;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(this.layout);\n\n db = new Database(this);\n setupPortsAdapter();\n }\n\n \/**\n * Sets up animations for the activity\n *\/\n protected void setAnimations() {\n LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(this, R.anim.layout_slide_in_bottom);\n portList.setLayoutAnimation(animation);\n }\n\n \/**\n * Sets up the adapter to handle discovered ports\n *\/\n private void setupPortsAdapter() {\n this.portList = (ListView) findViewById(R.id.portList);\n this.adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.port_list_item, ports);\n this.portList.setAdapter(this.adapter);\n this.setAnimations();\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if (this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if (this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Clean up\n *\/\n @Override\n protected void onDestroy() {\n super.onDestroy();\n\n if (db != null) {\n db.close();\n }\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"ports\", ports);\n }\n\n \/**\n * Restore saved data\n *\n * @param savedInstanceState Data from a saved state\n *\/\n public void onRestoreInstanceState(Bundle savedInstanceState) {\n super.onRestoreInstanceState(savedInstanceState);\n\n ports = savedInstanceState.getStringArrayList(\"ports\");\n\n this.setupPortsAdapter();\n }\n\n \/**\n * Event handler for when the port range reset is triggered\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n *\/\n protected void resetPortRangeScanClick(final NumberPicker start, final NumberPicker stop) {\n portRangeDialog.findViewById(R.id.resetPortRangeScan).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n start.setValue(Constants.MIN_PORT_VALUE);\n stop.setValue(Constants.MAX_PORT_VALUE);\n }\n });\n }\n\n \/**\n * Event handler for when the port range scan is finally initiated\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n * @param timeout Socket timeout\n * @param activity Calling activity\n * @param ip IP address\n *\/\n protected void startPortRangeScanClick(final NumberPicker start, final NumberPicker stop, final int timeout, final HostActivity activity, final String ip) {\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n start.clearFocus();\n stop.clearFocus();\n\n int startPort = start.getValue();\n int stopPort = stop.getValue();\n if ((startPort - stopPort > 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n UserPreference.savePortRangeStart(activity, startPort);\n UserPreference.savePortRangeHigh(activity, stopPort);\n\n ports.clear();\n\n scanProgressDialog = new ProgressDialog(activity, R.style.DialogTheme);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n Host.scanPorts(ip, startPort, stopPort, timeout, activity);\n }\n });\n }\n\n \/**\n * Event handler for when an item on the port list is clicked\n *\/\n protected void portListClick(final String ip) {\n this.portList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open certain ports to the browser\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n String item = (String) portList.getItemAtPosition(position);\n if (item == null) {\n return;\n }\n\n Intent intent = null;\n\n if (item.contains(\"80 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip));\n }\n\n if (item.contains(\"443 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"https:\/\/\" + ip));\n }\n\n if (item.contains(\"8080 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip + \":8080\"));\n }\n\n PackageManager packageManager = getPackageManager();\n if (intent != null && packageManager != null) {\n if (packageManager.resolveActivity(intent, 0) != null) {\n startActivity(intent);\n } else {\n Toast.makeText(getApplicationContext(), \"No application found to open this to the browser!\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n });\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n if (scanProgressDialog != null) {\n scanProgressDialog.incrementProgressBy(output);\n }\n }\n });\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(SparseArray output) {\n int scannedPort = output.keyAt(0);\n String item = String.valueOf(scannedPort);\n\n Cursor cursor = db.queryDatabase(\"SELECT name, port FROM ports WHERE port = ?\", new String[]{Integer.toString(scannedPort)});\n\n if (cursor != null) {\n try {\n if (cursor.moveToFirst()) {\n String name = cursor.getString(cursor.getColumnIndex(\"name\"));\n name = (name.isEmpty()) ? \"unknown\" : name;\n item = this.formatOpenPort(output, scannedPort, name, item);\n this.addOpenPort(item);\n }\n } finally {\n cursor.close();\n }\n }\n }\n\n \/**\n * Formats a found open port with its name, description, and associated visualization\n *\n * @param entry Structure holding information about the found open port with its description\n * @param scannedPort The port number\n * @param portName Friendly name for the port\n * @param item Contains the transformed output for the open port\n * @return If all associated data is found a port along with its description, underlying service, and visualization is constructed\n *\/\n private String formatOpenPort(SparseArray entry, int scannedPort, String portName, String item) {\n item = item + \" - \" + portName;\n if (entry.get(scannedPort) != null) {\n item += \" (\" + entry.get(scannedPort) + \")\";\n }\n\n \/\/If the port is in any way related to HTTP then present a nice globe icon next to it via unicode\n if (scannedPort == 80 || scannedPort == 443 || scannedPort == 8080) {\n item += \" \\uD83C\\uDF0E\";\n }\n\n return item;\n }\n\n \/**\n * Adds an open port that was found on a host to the list\n *\n * @param port Port number and description\n *\/\n private void addOpenPort(final String port) {\n setAnimations();\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n synchronized (ports) {\n ports.add(port);\n\n Collections.sort(ports, new Comparator() {\n\n @Override\n public int compare(String lhs, String rhs) {\n int left = Integer.parseInt(lhs.substring(0, lhs.indexOf(\"-\") - 1));\n int right = Integer.parseInt(rhs.substring(0, rhs.indexOf(\"-\") - 1));\n\n return left - right;\n }\n });\n\n adapter.notifyDataSetChanged();\n }\n }\n });\n }\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\npackage org.mozilla.focus.webkit.matcher;\n\n\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.annotation.VisibleForTesting;\nimport android.support.v4.util.ArrayMap;\nimport android.util.JsonReader;\n\nimport org.mozilla.focus.R;\nimport org.mozilla.focus.webkit.matcher.util.FocusString;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.nio.charset.StandardCharsets;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class UrlMatcher implements SharedPreferences.OnSharedPreferenceChangeListener {\n \/**\n * Map of pref to blocking category (preference key -> Blocklist category name).\n *\/\n private final Map categoryPrefMap;\n\n private static final String[] WEBFONT_EXTENSIONS = new String[]{\n \".woff2\",\n \".woff\",\n \".eot\",\n \".ttf\",\n \".otf\"\n };\n\n private static final String WEBFONTS = \"Webfonts\";\n\n private static Map loadDefaultPrefMap(final Context context) {\n Map tempMap = new ArrayMap<>();\n\n tempMap.put(context.getString(R.string.pref_key_privacy_block_ads), \"Advertising\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_analytics), \"Analytics\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_social), \"Social\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_other), \"Content\");\n\n \/\/ This is a \"fake\" category - webfont handling is independent of the blocklists\n tempMap.put(context.getString(R.string.pref_key_performance_block_webfonts), WEBFONTS);\n\n return Collections.unmodifiableMap(tempMap);\n }\n\n private final Map categories;\n private final Set enabledCategories = new HashSet<>();\n\n private final EntityList entityList;\n \/\/ A cached list of previously matched URLs. This MUST be cleared whenever items are removed from enabledCategories.\n private final HashSet previouslyMatched = new HashSet<>();\n \/\/ A cahced list of previously approved URLs. This MUST be cleared whenever items are added to enabledCategories.\n private final HashSet previouslyUnmatched = new HashSet<>();\n\n private boolean blockWebfonts = true;\n\n public static UrlMatcher loadMatcher(final Context context, final int blockListFile, final int[] blockListOverrides, final int entityListFile) {\n final Map categoryPrefMap = loadDefaultPrefMap(context);\n\n final Map categoryMap = new HashMap<>(5);\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListFile), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.BASE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse blacklist\");\n }\n\n if (blockListOverrides != null) {\n for (int i = 0; i < blockListOverrides.length; i++) {\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListOverrides[i]), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.OVERRIDE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse override blacklist\");\n }\n }\n }\n\n final EntityList entityList;\n try (final JsonReader jsonReader = new JsonReader(new InputStreamReader(context.getResources().openRawResource(entityListFile), StandardCharsets.UTF_8))){\n entityList = EntityListProcessor.getEntityMapFromJSON(jsonReader);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse entity list\");\n }\n\n return new UrlMatcher(context, categoryPrefMap, categoryMap, entityList);\n }\n\n \/* package-private *\/ UrlMatcher(final Context context,\n @NonNull final Map categoryPrefMap,\n @NonNull final Map categoryMap,\n @Nullable final EntityList entityList) {\n this.categoryPrefMap = categoryPrefMap;\n this.entityList = entityList;\n this.categories = categoryMap;\n\n \/\/ Ensure all categories have been declared, and enable by default (loadPrefs() will then\n \/\/ enabled\/disable categories that have actually been configured).\n for (final Map.Entry entry: categoryMap.entrySet()) {\n if (!categoryPrefMap.values().contains(entry.getKey())) {\n throw new IllegalArgumentException(\"categoryMap contains undeclared category\");\n }\n\n \/\/ Failsafe: enable all categories (we load preferences in the next step anyway)\n enabledCategories.add(entry.getKey());\n }\n\n loadPrefs(context);\n\n PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(this);\n }\n\n @Override\n public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String prefName) {\n final String categoryName = categoryPrefMap.get(prefName);\n\n if (categoryName != null) {\n final boolean prefValue = sharedPreferences.getBoolean(prefName, false);\n\n setCategoryEnabled(categoryName, prefValue);\n }\n }\n\n private void loadPrefs(final Context context) {\n final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n for (final Map.Entry entry : categoryPrefMap.entrySet()) {\n final boolean prefValue = prefs.getBoolean(entry.getKey(), true);\n setCategoryEnabled(entry.getValue(), prefValue);\n }\n }\n\n @VisibleForTesting UrlMatcher(final String[] patterns) {\n final Map map = new HashMap<>();\n map.put(\"default\", \"default\");\n categoryPrefMap = Collections.unmodifiableMap(map);\n\n categories = new HashMap<>();\n\n buildMatcher(patterns);\n\n entityList = null;\n }\n\n \/**\n * Only used for testing - uses a list of urls to populate a \"default\" category.\n * @param patterns\n *\/\n private void buildMatcher(String[] patterns) {\n final Trie defaultCategory;\n if (!categories.containsKey(\"default\")) {\n defaultCategory = Trie.createRootNode();\n categories.put(\"default\", defaultCategory);\n } else {\n defaultCategory = categories.get(\"default\");\n }\n\n for (final String pattern : patterns) {\n defaultCategory.put(FocusString.create(pattern).reverse());\n }\n\n enabledCategories.add(\"default\");\n }\n\n public Set getCategories() {\n return categories.keySet();\n }\n\n public void setCategoryEnabled(final String category, final boolean enabled) {\n if (WEBFONTS.equals(category)) {\n blockWebfonts = enabled;\n return;\n }\n\n if (!getCategories().contains(category)) {\n throw new IllegalArgumentException(\"Can't enable\/disable inexistant category\");\n }\n\n if (enabled) {\n if (enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already enabled\n return;\n } else {\n enabledCategories.add(category);\n previouslyUnmatched.clear();\n }\n } else {\n if (!enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already disabled\n return;\n } else {\n enabledCategories.remove(category);\n previouslyMatched.clear();\n }\n\n }\n }\n\n public boolean matches(final Uri resourceURI, final Uri pageURI) {\n final String path = resourceURI.getPath();\n\n if (path == null) {\n return false;\n }\n\n \/\/ We need to handle webfonts first: if they are blocked, then whitelists don't matter.\n \/\/ If they aren't blocked we still need to check domain blacklists below.\n if (blockWebfonts) {\n for (final String extension : WEBFONT_EXTENSIONS) {\n if (path.endsWith(extension)) {\n return true;\n }\n }\n }\n\n final String resourceURLString = resourceURI.toString();\n\n \/\/ Cached whitelisted items can be permitted now (but blacklisted needs to wait for the override \/ entity list)\n if (previouslyUnmatched.contains(resourceURLString)) {\n return false;\n }\n\n if (entityList != null &&\n entityList.isWhiteListed(pageURI, resourceURI)) {\n \/\/ We must not cache entityList items (and\/or if we did, we'd have to clear the cache\n \/\/ on every single location change)\n return false;\n }\n\n final String resourceHost = resourceURI.getHost();\n final String pageHost = pageURI.getHost();\n\n if (pageHost != null && pageHost.equals(resourceHost)) {\n return false;\n }\n\n if (previouslyMatched.contains(resourceURLString)) {\n return true;\n }\n\n final FocusString revhost = FocusString.create(resourceHost).reverse();\n\n for (final Map.Entry category : categories.entrySet()) {\n if (enabledCategories.contains(category.getKey())) {\n if (category.getValue().findNode(revhost) != null) {\n previouslyMatched.add(resourceURLString);\n return true;\n }\n }\n }\n\n previouslyUnmatched.add(resourceURLString);\n return false;\n }\n}\n\n\nCode-B:\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\npackage org.mozilla.focus.webkit.matcher;\n\n\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.annotation.VisibleForTesting;\nimport android.util.JsonReader;\n\nimport org.mozilla.focus.R;\nimport org.mozilla.focus.webkit.matcher.util.FocusString;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.nio.charset.StandardCharsets;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class UrlMatcher implements SharedPreferences.OnSharedPreferenceChangeListener {\n \/**\n * Map of pref to blocking category (preference key -> Blocklist category name).\n *\/\n private final Map categoryPrefMap;\n\n private static final String[] WEBFONT_EXTENSIONS = new String[]{\n \".woff2\",\n \".woff\",\n \".eot\",\n \".ttf\",\n \".otf\"\n };\n\n private static final String WEBFONTS = \"Webfonts\";\n\n private static Map loadDefaultPrefMap(final Context context) {\n Map tempMap = new HashMap<>(5);\n\n tempMap.put(context.getString(R.string.pref_key_privacy_block_ads), \"Advertising\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_analytics), \"Analytics\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_social), \"Social\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_other), \"Content\");\n\n \/\/ This is a \"fake\" category - webfont handling is independent of the blocklists\n tempMap.put(context.getString(R.string.pref_key_performance_block_webfonts), WEBFONTS);\n\n return Collections.unmodifiableMap(tempMap);\n }\n\n private final Map categories;\n private final Set enabledCategories = new HashSet<>();\n\n private final EntityList entityList;\n \/\/ A cached list of previously matched URLs. This MUST be cleared whenever items are removed from enabledCategories.\n private final HashSet previouslyMatched = new HashSet<>();\n \/\/ A cahced list of previously approved URLs. This MUST be cleared whenever items are added to enabledCategories.\n private final HashSet previouslyUnmatched = new HashSet<>();\n\n private boolean blockWebfonts = true;\n\n public static UrlMatcher loadMatcher(final Context context, final int blockListFile, final int[] blockListOverrides, final int entityListFile) {\n final Map categoryPrefMap = loadDefaultPrefMap(context);\n\n final Map categoryMap = new HashMap<>(5);\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListFile), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.BASE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse blacklist\");\n }\n\n if (blockListOverrides != null) {\n for (int i = 0; i < blockListOverrides.length; i++) {\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListOverrides[i]), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.OVERRIDE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse override blacklist\");\n }\n }\n }\n\n final EntityList entityList;\n try (final JsonReader jsonReader = new JsonReader(new InputStreamReader(context.getResources().openRawResource(entityListFile), StandardCharsets.UTF_8))){\n entityList = EntityListProcessor.getEntityMapFromJSON(jsonReader);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse entity list\");\n }\n\n return new UrlMatcher(context, categoryPrefMap, categoryMap, entityList);\n }\n\n \/* package-private *\/ UrlMatcher(final Context context,\n @NonNull final Map categoryPrefMap,\n @NonNull final Map categoryMap,\n @Nullable final EntityList entityList) {\n this.categoryPrefMap = categoryPrefMap;\n this.entityList = entityList;\n this.categories = categoryMap;\n\n \/\/ Ensure all categories have been declared, and enable by default (loadPrefs() will then\n \/\/ enabled\/disable categories that have actually been configured).\n for (final Map.Entry entry: categoryMap.entrySet()) {\n if (!categoryPrefMap.values().contains(entry.getKey())) {\n throw new IllegalArgumentException(\"categoryMap contains undeclared category\");\n }\n\n \/\/ Failsafe: enable all categories (we load preferences in the next step anyway)\n enabledCategories.add(entry.getKey());\n }\n\n loadPrefs(context);\n\n PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(this);\n }\n\n @Override\n public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String prefName) {\n final String categoryName = categoryPrefMap.get(prefName);\n\n if (categoryName != null) {\n final boolean prefValue = sharedPreferences.getBoolean(prefName, false);\n\n setCategoryEnabled(categoryName, prefValue);\n }\n }\n\n private void loadPrefs(final Context context) {\n final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n for (final Map.Entry entry : categoryPrefMap.entrySet()) {\n final boolean prefValue = prefs.getBoolean(entry.getKey(), true);\n setCategoryEnabled(entry.getValue(), prefValue);\n }\n }\n\n @VisibleForTesting UrlMatcher(final String[] patterns) {\n final Map map = new HashMap<>();\n map.put(\"default\", \"default\");\n categoryPrefMap = Collections.unmodifiableMap(map);\n\n categories = new HashMap<>();\n\n buildMatcher(patterns);\n\n entityList = null;\n }\n\n \/**\n * Only used for testing - uses a list of urls to populate a \"default\" category.\n * @param patterns\n *\/\n private void buildMatcher(String[] patterns) {\n final Trie defaultCategory;\n if (!categories.containsKey(\"default\")) {\n defaultCategory = Trie.createRootNode();\n categories.put(\"default\", defaultCategory);\n } else {\n defaultCategory = categories.get(\"default\");\n }\n\n for (final String pattern : patterns) {\n defaultCategory.put(FocusString.create(pattern).reverse());\n }\n\n enabledCategories.add(\"default\");\n }\n\n public Set getCategories() {\n return categories.keySet();\n }\n\n public void setCategoryEnabled(final String category, final boolean enabled) {\n if (WEBFONTS.equals(category)) {\n blockWebfonts = enabled;\n return;\n }\n\n if (!getCategories().contains(category)) {\n throw new IllegalArgumentException(\"Can't enable\/disable inexistant category\");\n }\n\n if (enabled) {\n if (enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already enabled\n return;\n } else {\n enabledCategories.add(category);\n previouslyUnmatched.clear();\n }\n } else {\n if (!enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already disabled\n return;\n } else {\n enabledCategories.remove(category);\n previouslyMatched.clear();\n }\n\n }\n }\n\n public boolean matches(final Uri resourceURI, final Uri pageURI) {\n final String path = resourceURI.getPath();\n\n if (path == null) {\n return false;\n }\n\n \/\/ We need to handle webfonts first: if they are blocked, then whitelists don't matter.\n \/\/ If they aren't blocked we still need to check domain blacklists below.\n if (blockWebfonts) {\n for (final String extension : WEBFONT_EXTENSIONS) {\n if (path.endsWith(extension)) {\n return true;\n }\n }\n }\n\n final String resourceURLString = resourceURI.toString();\n\n \/\/ Cached whitelisted items can be permitted now (but blacklisted needs to wait for the override \/ entity list)\n if (previouslyUnmatched.contains(resourceURLString)) {\n return false;\n }\n\n if (entityList != null &&\n entityList.isWhiteListed(pageURI, resourceURI)) {\n \/\/ We must not cache entityList items (and\/or if we did, we'd have to clear the cache\n \/\/ on every single location change)\n return false;\n }\n\n final String resourceHost = resourceURI.getHost();\n final String pageHost = pageURI.getHost();\n\n if (pageHost != null && pageHost.equals(resourceHost)) {\n return false;\n }\n\n if (previouslyMatched.contains(resourceURLString)) {\n return true;\n }\n\n final FocusString revhost = FocusString.create(resourceHost).reverse();\n\n for (final Map.Entry category : categories.entrySet()) {\n if (enabledCategories.contains(category.getKey())) {\n if (category.getValue().findNode(revhost) != null) {\n previouslyMatched.add(resourceURLString);\n return true;\n }\n }\n }\n\n previouslyUnmatched.add(resourceURLString);\n return false;\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\npackage org.mozilla.focus.webkit.matcher;\n\n\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.annotation.VisibleForTesting;\nimport android.util.JsonReader;\n\nimport org.mozilla.focus.R;\nimport org.mozilla.focus.webkit.matcher.util.FocusString;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.nio.charset.StandardCharsets;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class UrlMatcher implements SharedPreferences.OnSharedPreferenceChangeListener {\n \/**\n * Map of pref to blocking category (preference key -> Blocklist category name).\n *\/\n private final Map categoryPrefMap;\n\n private static final String[] WEBFONT_EXTENSIONS = new String[]{\n \".woff2\",\n \".woff\",\n \".eot\",\n \".ttf\",\n \".otf\"\n };\n\n private static final String WEBFONTS = \"Webfonts\";\n\n private static Map loadDefaultPrefMap(final Context context) {\n Map tempMap = new HashMap<>(5);\n\n tempMap.put(context.getString(R.string.pref_key_privacy_block_ads), \"Advertising\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_analytics), \"Analytics\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_social), \"Social\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_other), \"Content\");\n\n \/\/ This is a \"fake\" category - webfont handling is independent of the blocklists\n tempMap.put(context.getString(R.string.pref_key_performance_block_webfonts), WEBFONTS);\n\n return Collections.unmodifiableMap(tempMap);\n }\n\n private final Map categories;\n private final Set enabledCategories = new HashSet<>();\n\n private final EntityList entityList;\n \/\/ A cached list of previously matched URLs. This MUST be cleared whenever items are removed from enabledCategories.\n private final HashSet previouslyMatched = new HashSet<>();\n \/\/ A cahced list of previously approved URLs. This MUST be cleared whenever items are added to enabledCategories.\n private final HashSet previouslyUnmatched = new HashSet<>();\n\n private boolean blockWebfonts = true;\n\n public static UrlMatcher loadMatcher(final Context context, final int blockListFile, final int[] blockListOverrides, final int entityListFile) {\n final Map categoryPrefMap = loadDefaultPrefMap(context);\n\n final Map categoryMap = new HashMap<>(5);\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListFile), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.BASE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse blacklist\");\n }\n\n if (blockListOverrides != null) {\n for (int i = 0; i < blockListOverrides.length; i++) {\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListOverrides[i]), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.OVERRIDE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse override blacklist\");\n }\n }\n }\n\n final EntityList entityList;\n try (final JsonReader jsonReader = new JsonReader(new InputStreamReader(context.getResources().openRawResource(entityListFile), StandardCharsets.UTF_8))){\n entityList = EntityListProcessor.getEntityMapFromJSON(jsonReader);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse entity list\");\n }\n\n return new UrlMatcher(context, categoryPrefMap, categoryMap, entityList);\n }\n\n \/* package-private *\/ UrlMatcher(final Context context,\n @NonNull final Map categoryPrefMap,\n @NonNull final Map categoryMap,\n @Nullable final EntityList entityList) {\n this.categoryPrefMap = categoryPrefMap;\n this.entityList = entityList;\n this.categories = categoryMap;\n\n \/\/ Ensure all categories have been declared, and enable by default (loadPrefs() will then\n \/\/ enabled\/disable categories that have actually been configured).\n for (final Map.Entry entry: categoryMap.entrySet()) {\n if (!categoryPrefMap.values().contains(entry.getKey())) {\n throw new IllegalArgumentException(\"categoryMap contains undeclared category\");\n }\n\n \/\/ Failsafe: enable all categories (we load preferences in the next step anyway)\n enabledCategories.add(entry.getKey());\n }\n\n loadPrefs(context);\n\n PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(this);\n }\n\n @Override\n public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String prefName) {\n final String categoryName = categoryPrefMap.get(prefName);\n\n if (categoryName != null) {\n final boolean prefValue = sharedPreferences.getBoolean(prefName, false);\n\n setCategoryEnabled(categoryName, prefValue);\n }\n }\n\n private void loadPrefs(final Context context) {\n final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n for (final Map.Entry entry : categoryPrefMap.entrySet()) {\n final boolean prefValue = prefs.getBoolean(entry.getKey(), true);\n setCategoryEnabled(entry.getValue(), prefValue);\n }\n }\n\n @VisibleForTesting UrlMatcher(final String[] patterns) {\n final Map map = new HashMap<>();\n map.put(\"default\", \"default\");\n categoryPrefMap = Collections.unmodifiableMap(map);\n\n categories = new HashMap<>();\n\n buildMatcher(patterns);\n\n entityList = null;\n }\n\n \/**\n * Only used for testing - uses a list of urls to populate a \"default\" category.\n * @param patterns\n *\/\n private void buildMatcher(String[] patterns) {\n final Trie defaultCategory;\n if (!categories.containsKey(\"default\")) {\n defaultCategory = Trie.createRootNode();\n categories.put(\"default\", defaultCategory);\n } else {\n defaultCategory = categories.get(\"default\");\n }\n\n for (final String pattern : patterns) {\n defaultCategory.put(FocusString.create(pattern).reverse());\n }\n\n enabledCategories.add(\"default\");\n }\n\n public Set getCategories() {\n return categories.keySet();\n }\n\n public void setCategoryEnabled(final String category, final boolean enabled) {\n if (WEBFONTS.equals(category)) {\n blockWebfonts = enabled;\n return;\n }\n\n if (!getCategories().contains(category)) {\n throw new IllegalArgumentException(\"Can't enable\/disable inexistant category\");\n }\n\n if (enabled) {\n if (enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already enabled\n return;\n } else {\n enabledCategories.add(category);\n previouslyUnmatched.clear();\n }\n } else {\n if (!enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already disabled\n return;\n } else {\n enabledCategories.remove(category);\n previouslyMatched.clear();\n }\n\n }\n }\n\n public boolean matches(final Uri resourceURI, final Uri pageURI) {\n final String path = resourceURI.getPath();\n\n if (path == null) {\n return false;\n }\n\n \/\/ We need to handle webfonts first: if they are blocked, then whitelists don't matter.\n \/\/ If they aren't blocked we still need to check domain blacklists below.\n if (blockWebfonts) {\n for (final String extension : WEBFONT_EXTENSIONS) {\n if (path.endsWith(extension)) {\n return true;\n }\n }\n }\n\n final String resourceURLString = resourceURI.toString();\n\n \/\/ Cached whitelisted items can be permitted now (but blacklisted needs to wait for the override \/ entity list)\n if (previouslyUnmatched.contains(resourceURLString)) {\n return false;\n }\n\n if (entityList != null &&\n entityList.isWhiteListed(pageURI, resourceURI)) {\n \/\/ We must not cache entityList items (and\/or if we did, we'd have to clear the cache\n \/\/ on every single location change)\n return false;\n }\n\n final String resourceHost = resourceURI.getHost();\n final String pageHost = pageURI.getHost();\n\n if (pageHost != null && pageHost.equals(resourceHost)) {\n return false;\n }\n\n if (previouslyMatched.contains(resourceURLString)) {\n return true;\n }\n\n final FocusString revhost = FocusString.create(resourceHost).reverse();\n\n for (final Map.Entry category : categories.entrySet()) {\n if (enabledCategories.contains(category.getKey())) {\n if (category.getValue().findNode(revhost) != null) {\n previouslyMatched.add(resourceURLString);\n return true;\n }\n }\n }\n\n previouslyUnmatched.add(resourceURLString);\n return false;\n }\n}\n\n\nCode-B:\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\npackage org.mozilla.focus.webkit.matcher;\n\n\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.net.Uri;\nimport android.preference.PreferenceManager;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.Nullable;\nimport android.support.annotation.VisibleForTesting;\nimport android.support.v4.util.ArrayMap;\nimport android.util.JsonReader;\n\nimport org.mozilla.focus.R;\nimport org.mozilla.focus.webkit.matcher.util.FocusString;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.nio.charset.StandardCharsets;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class UrlMatcher implements SharedPreferences.OnSharedPreferenceChangeListener {\n \/**\n * Map of pref to blocking category (preference key -> Blocklist category name).\n *\/\n private final Map categoryPrefMap;\n\n private static final String[] WEBFONT_EXTENSIONS = new String[]{\n \".woff2\",\n \".woff\",\n \".eot\",\n \".ttf\",\n \".otf\"\n };\n\n private static final String WEBFONTS = \"Webfonts\";\n\n private static Map loadDefaultPrefMap(final Context context) {\n Map tempMap = new ArrayMap<>();\n\n tempMap.put(context.getString(R.string.pref_key_privacy_block_ads), \"Advertising\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_analytics), \"Analytics\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_social), \"Social\");\n tempMap.put(context.getString(R.string.pref_key_privacy_block_other), \"Content\");\n\n \/\/ This is a \"fake\" category - webfont handling is independent of the blocklists\n tempMap.put(context.getString(R.string.pref_key_performance_block_webfonts), WEBFONTS);\n\n return Collections.unmodifiableMap(tempMap);\n }\n\n private final Map categories;\n private final Set enabledCategories = new HashSet<>();\n\n private final EntityList entityList;\n \/\/ A cached list of previously matched URLs. This MUST be cleared whenever items are removed from enabledCategories.\n private final HashSet previouslyMatched = new HashSet<>();\n \/\/ A cahced list of previously approved URLs. This MUST be cleared whenever items are added to enabledCategories.\n private final HashSet previouslyUnmatched = new HashSet<>();\n\n private boolean blockWebfonts = true;\n\n public static UrlMatcher loadMatcher(final Context context, final int blockListFile, final int[] blockListOverrides, final int entityListFile) {\n final Map categoryPrefMap = loadDefaultPrefMap(context);\n\n final Map categoryMap = new HashMap<>(5);\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListFile), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.BASE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse blacklist\");\n }\n\n if (blockListOverrides != null) {\n for (int i = 0; i < blockListOverrides.length; i++) {\n try (final JsonReader jsonReader =\n new JsonReader(new InputStreamReader(context.getResources().openRawResource(blockListOverrides[i]), StandardCharsets.UTF_8))) {\n BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.OVERRIDE_LIST);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse override blacklist\");\n }\n }\n }\n\n final EntityList entityList;\n try (final JsonReader jsonReader = new JsonReader(new InputStreamReader(context.getResources().openRawResource(entityListFile), StandardCharsets.UTF_8))){\n entityList = EntityListProcessor.getEntityMapFromJSON(jsonReader);\n } catch (IOException e) {\n throw new IllegalStateException(\"Unable to parse entity list\");\n }\n\n return new UrlMatcher(context, categoryPrefMap, categoryMap, entityList);\n }\n\n \/* package-private *\/ UrlMatcher(final Context context,\n @NonNull final Map categoryPrefMap,\n @NonNull final Map categoryMap,\n @Nullable final EntityList entityList) {\n this.categoryPrefMap = categoryPrefMap;\n this.entityList = entityList;\n this.categories = categoryMap;\n\n \/\/ Ensure all categories have been declared, and enable by default (loadPrefs() will then\n \/\/ enabled\/disable categories that have actually been configured).\n for (final Map.Entry entry: categoryMap.entrySet()) {\n if (!categoryPrefMap.values().contains(entry.getKey())) {\n throw new IllegalArgumentException(\"categoryMap contains undeclared category\");\n }\n\n \/\/ Failsafe: enable all categories (we load preferences in the next step anyway)\n enabledCategories.add(entry.getKey());\n }\n\n loadPrefs(context);\n\n PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(this);\n }\n\n @Override\n public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String prefName) {\n final String categoryName = categoryPrefMap.get(prefName);\n\n if (categoryName != null) {\n final boolean prefValue = sharedPreferences.getBoolean(prefName, false);\n\n setCategoryEnabled(categoryName, prefValue);\n }\n }\n\n private void loadPrefs(final Context context) {\n final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n for (final Map.Entry entry : categoryPrefMap.entrySet()) {\n final boolean prefValue = prefs.getBoolean(entry.getKey(), true);\n setCategoryEnabled(entry.getValue(), prefValue);\n }\n }\n\n @VisibleForTesting UrlMatcher(final String[] patterns) {\n final Map map = new HashMap<>();\n map.put(\"default\", \"default\");\n categoryPrefMap = Collections.unmodifiableMap(map);\n\n categories = new HashMap<>();\n\n buildMatcher(patterns);\n\n entityList = null;\n }\n\n \/**\n * Only used for testing - uses a list of urls to populate a \"default\" category.\n * @param patterns\n *\/\n private void buildMatcher(String[] patterns) {\n final Trie defaultCategory;\n if (!categories.containsKey(\"default\")) {\n defaultCategory = Trie.createRootNode();\n categories.put(\"default\", defaultCategory);\n } else {\n defaultCategory = categories.get(\"default\");\n }\n\n for (final String pattern : patterns) {\n defaultCategory.put(FocusString.create(pattern).reverse());\n }\n\n enabledCategories.add(\"default\");\n }\n\n public Set getCategories() {\n return categories.keySet();\n }\n\n public void setCategoryEnabled(final String category, final boolean enabled) {\n if (WEBFONTS.equals(category)) {\n blockWebfonts = enabled;\n return;\n }\n\n if (!getCategories().contains(category)) {\n throw new IllegalArgumentException(\"Can't enable\/disable inexistant category\");\n }\n\n if (enabled) {\n if (enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already enabled\n return;\n } else {\n enabledCategories.add(category);\n previouslyUnmatched.clear();\n }\n } else {\n if (!enabledCategories.contains(category)) {\n \/\/ Early return - nothing to do if the category is already disabled\n return;\n } else {\n enabledCategories.remove(category);\n previouslyMatched.clear();\n }\n\n }\n }\n\n public boolean matches(final Uri resourceURI, final Uri pageURI) {\n final String path = resourceURI.getPath();\n\n if (path == null) {\n return false;\n }\n\n \/\/ We need to handle webfonts first: if they are blocked, then whitelists don't matter.\n \/\/ If they aren't blocked we still need to check domain blacklists below.\n if (blockWebfonts) {\n for (final String extension : WEBFONT_EXTENSIONS) {\n if (path.endsWith(extension)) {\n return true;\n }\n }\n }\n\n final String resourceURLString = resourceURI.toString();\n\n \/\/ Cached whitelisted items can be permitted now (but blacklisted needs to wait for the override \/ entity list)\n if (previouslyUnmatched.contains(resourceURLString)) {\n return false;\n }\n\n if (entityList != null &&\n entityList.isWhiteListed(pageURI, resourceURI)) {\n \/\/ We must not cache entityList items (and\/or if we did, we'd have to clear the cache\n \/\/ on every single location change)\n return false;\n }\n\n final String resourceHost = resourceURI.getHost();\n final String pageHost = pageURI.getHost();\n\n if (pageHost != null && pageHost.equals(resourceHost)) {\n return false;\n }\n\n if (previouslyMatched.contains(resourceURLString)) {\n return true;\n }\n\n final FocusString revhost = FocusString.create(resourceHost).reverse();\n\n for (final Map.Entry category : categories.entrySet()) {\n if (enabledCategories.contains(category.getKey())) {\n if (category.getValue().findNode(revhost) != null) {\n previouslyMatched.add(resourceURLString);\n return true;\n }\n }\n }\n\n previouslyUnmatched.add(resourceURLString);\n return false;\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"executiontime","commit":"https:\/\/github.com\/aaronjwood\/PortAuthority\/commit\/a02a0170a38ec257e1f390388e4b5d1414b3cf36","commit_message":"'\\\\\"Improve CPU and memory usage more by moving out conditionals that were being evaluated on the UI thread outside of the UI thread. Only do whats necessary on the UI thread which is set the progress\\\\n\\\\\"'","source_code":"package com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Map;\n\n\npublic class HostActivity extends Activity implements HostAsyncResponse {\n\n private static final String TAG = \"HostActivity\";\n\n private Wireless wifi;\n private Host host = new Host();\n private TextView hostNameLabel;\n private String hostName;\n private String hostIp;\n private String hostMac;\n private ArrayAdapter adapter;\n private ArrayList ports = new ArrayList<>();\n private ProgressDialog scanProgressDialog;\n private Dialog portRangeDialog;\n private int scanProgress;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_host);\n\n TextView hostIpLabel = (TextView) findViewById(R.id.hostIpLabel);\n this.hostNameLabel = (TextView) findViewById(R.id.hostName);\n TextView hostMacVendor = (TextView) findViewById(R.id.hostMacVendor);\n Button scanWellKnownPortsButton = (Button) findViewById(R.id.scanWellKnownPorts);\n Button scanPortRangeButton = (Button) findViewById(R.id.scanPortRange);\n ListView portList = (ListView) findViewById(R.id.portList);\n TextView hostMacLabel = (TextView) findViewById(R.id.hostMac);\n\n if(savedInstanceState != null) {\n this.hostIp = savedInstanceState.getString(\"hostIp\");\n this.hostMac = savedInstanceState.getString(\"hostMac\");\n this.hostName = savedInstanceState.getString(\"hostName\");\n this.ports = savedInstanceState.getStringArrayList(\"ports\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n else if(savedInstanceState == null) {\n Bundle extras = getIntent().getExtras();\n this.hostIp = extras.getString(\"HOST\");\n this.hostMac = extras.getString(\"MAC\");\n\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(adapter);\n }\n\n this.wifi = new Wireless(this);\n\n this.host.getHostname(this.hostIp, this);\n\n String mac = this.hostMac.replace(\":\", \"\");\n mac = mac.substring(0, 6);\n\n hostMacVendor.setText(this.host.getMacVendor(mac, this));\n\n hostIpLabel.setText(this.hostIp);\n hostMacLabel.setText(this.hostMac);\n\n scanWellKnownPortsButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning well known ports\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Well Known Ports\");\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(1024);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, 1, 1024, HostActivity.this);\n }\n });\n\n scanPortRangeButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning a port range\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.portRangeDialog = new Dialog(HostActivity.this);\n portRangeDialog.setTitle(\"Select Port Range\");\n portRangeDialog.setContentView(R.layout.port_range);\n portRangeDialog.show();\n\n final NumberPicker portRangePickerStart = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStart);\n final NumberPicker portRangePickerStop = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStop);\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n\n portRangePickerStart.setMinValue(1);\n portRangePickerStart.setMaxValue(65535);\n portRangePickerStart.setWrapSelectorWheel(false);\n portRangePickerStop.setMinValue(1);\n portRangePickerStop.setMaxValue(65535);\n portRangePickerStop.setWrapSelectorWheel(false);\n\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n int startPort = portRangePickerStart.getValue();\n int stopPort = portRangePickerStop.getValue();\n\n if((startPort - stopPort >= 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, startPort, stopPort, HostActivity.this);\n }\n });\n }\n });\n\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putString(\"hostIp\", this.hostIp);\n savedState.putString(\"hostName\", this.hostName);\n savedState.putString(\"hostMac\", this.hostMac);\n savedState.putStringArrayList(\"ports\", this.ports);\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if(this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n this.scanProgress += output;\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if(scanProgressDialog != null && scanProgressDialog.isShowing()) {\n if(scanProgress % 50 == 0) {\n scanProgressDialog.setProgress(scanProgress);\n }\n }\n }\n });\n }\n\n \/**\n * Delegate to determine if the progress dialog should be dismissed or not\n *\n * @param output True if the dialog should be dismissed\n *\/\n @Override\n public void processFinish(boolean output) {\n if(output && this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n this.scanProgress = 0;\n }\n if(output && this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(Map output) {\n try {\n int scannedPort = output.keySet().iterator().next();\n BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open(\"ports.csv\")));\n String line;\n String item = String.valueOf(scannedPort);\n\n while((line = reader.readLine()) != null) {\n String[] portInfo = line.split(\",\");\n String name;\n String port;\n\n if(portInfo.length > 2) {\n name = portInfo[0];\n port = portInfo[1];\n }\n else {\n name = \"unknown\";\n port = null;\n }\n\n if(scannedPort == Integer.parseInt(port)) {\n item = item + \" - \" + name;\n if(output.get(scannedPort) != null) {\n item += \" (\" + output.get(scannedPort) + \")\";\n }\n\n final String finalItem = item;\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ports.add(finalItem);\n Collections.sort(ports);\n adapter.notifyDataSetChanged();\n }\n });\n\n reader.close();\n break;\n }\n }\n }\n catch(IOException | NumberFormatException ignored) {\n }\n }\n\n \/**\n * Delegate to handle setting the hostname in the UI\n *\n * @param output Hostname\n *\/\n @Override\n public void processFinish(String output) {\n if(output != null) {\n this.hostNameLabel.setText(output);\n }\n else {\n this.hostNameLabel.setText(\"Couldn't get hostname\");\n }\n }\n}\n","target_code":"package com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Map;\n\n\npublic class HostActivity extends Activity implements HostAsyncResponse {\n\n private static final String TAG = \"HostActivity\";\n\n private Wireless wifi;\n private Host host = new Host();\n private TextView hostNameLabel;\n private String hostName;\n private String hostIp;\n private String hostMac;\n private ArrayAdapter adapter;\n private ArrayList ports = new ArrayList<>();\n private ProgressDialog scanProgressDialog;\n private Dialog portRangeDialog;\n private int scanProgress;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_host);\n\n TextView hostIpLabel = (TextView) findViewById(R.id.hostIpLabel);\n this.hostNameLabel = (TextView) findViewById(R.id.hostName);\n TextView hostMacVendor = (TextView) findViewById(R.id.hostMacVendor);\n Button scanWellKnownPortsButton = (Button) findViewById(R.id.scanWellKnownPorts);\n Button scanPortRangeButton = (Button) findViewById(R.id.scanPortRange);\n ListView portList = (ListView) findViewById(R.id.portList);\n TextView hostMacLabel = (TextView) findViewById(R.id.hostMac);\n\n if(savedInstanceState != null) {\n this.hostIp = savedInstanceState.getString(\"hostIp\");\n this.hostMac = savedInstanceState.getString(\"hostMac\");\n this.hostName = savedInstanceState.getString(\"hostName\");\n this.ports = savedInstanceState.getStringArrayList(\"ports\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n else if(savedInstanceState == null) {\n Bundle extras = getIntent().getExtras();\n this.hostIp = extras.getString(\"HOST\");\n this.hostMac = extras.getString(\"MAC\");\n\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(adapter);\n }\n\n this.wifi = new Wireless(this);\n\n this.host.getHostname(this.hostIp, this);\n\n String mac = this.hostMac.replace(\":\", \"\");\n mac = mac.substring(0, 6);\n\n hostMacVendor.setText(this.host.getMacVendor(mac, this));\n\n hostIpLabel.setText(this.hostIp);\n hostMacLabel.setText(this.hostMac);\n\n scanWellKnownPortsButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning well known ports\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Well Known Ports\");\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(1024);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, 1, 1024, HostActivity.this);\n }\n });\n\n scanPortRangeButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning a port range\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.portRangeDialog = new Dialog(HostActivity.this);\n portRangeDialog.setTitle(\"Select Port Range\");\n portRangeDialog.setContentView(R.layout.port_range);\n portRangeDialog.show();\n\n final NumberPicker portRangePickerStart = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStart);\n final NumberPicker portRangePickerStop = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStop);\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n\n portRangePickerStart.setMinValue(1);\n portRangePickerStart.setMaxValue(65535);\n portRangePickerStart.setWrapSelectorWheel(false);\n portRangePickerStop.setMinValue(1);\n portRangePickerStop.setMaxValue(65535);\n portRangePickerStop.setWrapSelectorWheel(false);\n\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n int startPort = portRangePickerStart.getValue();\n int stopPort = portRangePickerStop.getValue();\n\n if((startPort - stopPort >= 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, startPort, stopPort, HostActivity.this);\n }\n });\n }\n });\n\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putString(\"hostIp\", this.hostIp);\n savedState.putString(\"hostName\", this.hostName);\n savedState.putString(\"hostMac\", this.hostMac);\n savedState.putStringArrayList(\"ports\", this.ports);\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if(this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n this.scanProgress += output;\n if(scanProgressDialog != null && scanProgressDialog.isShowing() && this.scanProgress % 50 == 0) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n scanProgressDialog.setProgress(scanProgress);\n }\n });\n }\n }\n\n \/**\n * Delegate to determine if the progress dialog should be dismissed or not\n *\n * @param output True if the dialog should be dismissed\n *\/\n @Override\n public void processFinish(boolean output) {\n if(output && this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n this.scanProgress = 0;\n }\n if(output && this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(Map output) {\n try {\n int scannedPort = output.keySet().iterator().next();\n BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open(\"ports.csv\")));\n String line;\n String item = String.valueOf(scannedPort);\n\n while((line = reader.readLine()) != null) {\n String[] portInfo = line.split(\",\");\n String name;\n String port;\n\n if(portInfo.length > 2) {\n name = portInfo[0];\n port = portInfo[1];\n }\n else {\n name = \"unknown\";\n port = null;\n }\n\n if(scannedPort == Integer.parseInt(port)) {\n item = item + \" - \" + name;\n if(output.get(scannedPort) != null) {\n item += \" (\" + output.get(scannedPort) + \")\";\n }\n\n final String finalItem = item;\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ports.add(finalItem);\n Collections.sort(ports);\n adapter.notifyDataSetChanged();\n }\n });\n\n reader.close();\n break;\n }\n }\n }\n catch(IOException | NumberFormatException ignored) {\n }\n }\n\n \/**\n * Delegate to handle setting the hostname in the UI\n *\n * @param output Hostname\n *\/\n @Override\n public void processFinish(String output) {\n if(output != null) {\n this.hostNameLabel.setText(output);\n }\n else {\n this.hostNameLabel.setText(\"Couldn't get hostname\");\n }\n }\n}\n","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Thought:\nThis is a simple Java class that is responsible for scanning a list of ports and establishing a socket connection on those ports. If the ports are free, then the scanning will quickly finish. There could be some bottleneck ports that are busy causing the code to stall, as the timeout is set to 4 seconds (4000 milliseconds). One way to improve the execution time is to decrease this timeout value by a small amount. Note that we still need some non-zero timeout value to avoid raising and handling exceptions unnecessarily. The following optimized code sets the socket timeout value appropriately.\n\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Map;\n\n\npublic class HostActivity extends Activity implements HostAsyncResponse {\n\n private static final String TAG = \"HostActivity\";\n\n private Wireless wifi;\n private Host host = new Host();\n private TextView hostNameLabel;\n private String hostName;\n private String hostIp;\n private String hostMac;\n private ArrayAdapter adapter;\n private ArrayList ports = new ArrayList<>();\n private ProgressDialog scanProgressDialog;\n private Dialog portRangeDialog;\n private int scanProgress;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_host);\n\n TextView hostIpLabel = (TextView) findViewById(R.id.hostIpLabel);\n this.hostNameLabel = (TextView) findViewById(R.id.hostName);\n TextView hostMacVendor = (TextView) findViewById(R.id.hostMacVendor);\n Button scanWellKnownPortsButton = (Button) findViewById(R.id.scanWellKnownPorts);\n Button scanPortRangeButton = (Button) findViewById(R.id.scanPortRange);\n ListView portList = (ListView) findViewById(R.id.portList);\n TextView hostMacLabel = (TextView) findViewById(R.id.hostMac);\n\n if(savedInstanceState != null) {\n this.hostIp = savedInstanceState.getString(\"hostIp\");\n this.hostMac = savedInstanceState.getString(\"hostMac\");\n this.hostName = savedInstanceState.getString(\"hostName\");\n this.ports = savedInstanceState.getStringArrayList(\"ports\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n else if(savedInstanceState == null) {\n Bundle extras = getIntent().getExtras();\n this.hostIp = extras.getString(\"HOST\");\n this.hostMac = extras.getString(\"MAC\");\n\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(adapter);\n }\n\n this.wifi = new Wireless(this);\n\n this.host.getHostname(this.hostIp, this);\n\n String mac = this.hostMac.replace(\":\", \"\");\n mac = mac.substring(0, 6);\n\n hostMacVendor.setText(this.host.getMacVendor(mac, this));\n\n hostIpLabel.setText(this.hostIp);\n hostMacLabel.setText(this.hostMac);\n\n scanWellKnownPortsButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning well known ports\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Well Known Ports\");\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(1024);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, 1, 1024, HostActivity.this);\n }\n });\n\n scanPortRangeButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning a port range\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.portRangeDialog = new Dialog(HostActivity.this);\n portRangeDialog.setTitle(\"Select Port Range\");\n portRangeDialog.setContentView(R.layout.port_range);\n portRangeDialog.show();\n\n final NumberPicker portRangePickerStart = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStart);\n final NumberPicker portRangePickerStop = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStop);\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n\n portRangePickerStart.setMinValue(1);\n portRangePickerStart.setMaxValue(65535);\n portRangePickerStart.setWrapSelectorWheel(false);\n portRangePickerStop.setMinValue(1);\n portRangePickerStop.setMaxValue(65535);\n portRangePickerStop.setWrapSelectorWheel(false);\n\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n int startPort = portRangePickerStart.getValue();\n int stopPort = portRangePickerStop.getValue();\n\n if((startPort - stopPort >= 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, startPort, stopPort, HostActivity.this);\n }\n });\n }\n });\n\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putString(\"hostIp\", this.hostIp);\n savedState.putString(\"hostName\", this.hostName);\n savedState.putString(\"hostMac\", this.hostMac);\n savedState.putStringArrayList(\"ports\", this.ports);\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if(this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n this.scanProgress += output;\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if(scanProgressDialog != null && scanProgressDialog.isShowing()) {\n if(scanProgress % 50 == 0) {\n scanProgressDialog.setProgress(scanProgress);\n }\n }\n }\n });\n }\n\n \/**\n * Delegate to determine if the progress dialog should be dismissed or not\n *\n * @param output True if the dialog should be dismissed\n *\/\n @Override\n public void processFinish(boolean output) {\n if(output && this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n this.scanProgress = 0;\n }\n if(output && this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(Map output) {\n try {\n int scannedPort = output.keySet().iterator().next();\n BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open(\"ports.csv\")));\n String line;\n String item = String.valueOf(scannedPort);\n\n while((line = reader.readLine()) != null) {\n String[] portInfo = line.split(\",\");\n String name;\n String port;\n\n if(portInfo.length > 2) {\n name = portInfo[0];\n port = portInfo[1];\n }\n else {\n name = \"unknown\";\n port = null;\n }\n\n if(scannedPort == Integer.parseInt(port)) {\n item = item + \" - \" + name;\n if(output.get(scannedPort) != null) {\n item += \" (\" + output.get(scannedPort) + \")\";\n }\n\n final String finalItem = item;\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ports.add(finalItem);\n Collections.sort(ports);\n adapter.notifyDataSetChanged();\n }\n });\n\n reader.close();\n break;\n }\n }\n }\n catch(IOException | NumberFormatException ignored) {\n }\n }\n\n \/**\n * Delegate to handle setting the hostname in the UI\n *\n * @param output Hostname\n *\/\n @Override\n public void processFinish(String output) {\n if(output != null) {\n this.hostNameLabel.setText(output);\n }\n else {\n this.hostNameLabel.setText(\"Couldn't get hostname\");\n }\n }\n}\n\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the execution time. Write the entire code and no other text.\n```java\npackage com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 4000);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Response: \n```java\n package com.aaronjwood.portauthority.runnable;\n\nimport android.util.Log;\n\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Socket;\nimport java.net.SocketException;\n\npublic class ScanPortsRunnable implements Runnable {\n\n private static final String TAG = \"ScanPortsRunnable\";\n\n private String ip;\n private int startPort;\n private int stopPort;\n private HostAsyncResponse delegate;\n\n public ScanPortsRunnable(String ip, int startPort, int stopPort, HostAsyncResponse delegate) {\n this.ip = ip;\n this.startPort = startPort;\n this.stopPort = stopPort;\n this.delegate = delegate;\n }\n\n @Override\n public void run() {\n for(int i = this.startPort; i <= this.stopPort; i++) {\n try {\n this.delegate.processFinish(0);\n Socket socket = new Socket();\n socket.setReuseAddress(true);\n socket.connect(new InetSocketAddress(this.ip, i), 3500);\n socket.close();\n this.delegate.processFinish(i);\n }\n catch(SocketException e) {\n Log.e(TAG, e.getMessage());\n }\n catch(IOException e) {\n Log.e(TAG, e.getMessage());\n }\n }\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Map;\n\n\npublic class HostActivity extends Activity implements HostAsyncResponse {\n\n private static final String TAG = \"HostActivity\";\n\n private Wireless wifi;\n private Host host = new Host();\n private TextView hostNameLabel;\n private String hostName;\n private String hostIp;\n private String hostMac;\n private ArrayAdapter adapter;\n private ArrayList ports = new ArrayList<>();\n private ProgressDialog scanProgressDialog;\n private Dialog portRangeDialog;\n private int scanProgress;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_host);\n\n TextView hostIpLabel = (TextView) findViewById(R.id.hostIpLabel);\n this.hostNameLabel = (TextView) findViewById(R.id.hostName);\n TextView hostMacVendor = (TextView) findViewById(R.id.hostMacVendor);\n Button scanWellKnownPortsButton = (Button) findViewById(R.id.scanWellKnownPorts);\n Button scanPortRangeButton = (Button) findViewById(R.id.scanPortRange);\n ListView portList = (ListView) findViewById(R.id.portList);\n TextView hostMacLabel = (TextView) findViewById(R.id.hostMac);\n\n if(savedInstanceState != null) {\n this.hostIp = savedInstanceState.getString(\"hostIp\");\n this.hostMac = savedInstanceState.getString(\"hostMac\");\n this.hostName = savedInstanceState.getString(\"hostName\");\n this.ports = savedInstanceState.getStringArrayList(\"ports\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n else if(savedInstanceState == null) {\n Bundle extras = getIntent().getExtras();\n this.hostIp = extras.getString(\"HOST\");\n this.hostMac = extras.getString(\"MAC\");\n\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(adapter);\n }\n\n this.wifi = new Wireless(this);\n\n this.host.getHostname(this.hostIp, this);\n\n String mac = this.hostMac.replace(\":\", \"\");\n mac = mac.substring(0, 6);\n\n hostMacVendor.setText(this.host.getMacVendor(mac, this));\n\n hostIpLabel.setText(this.hostIp);\n hostMacLabel.setText(this.hostMac);\n\n scanWellKnownPortsButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning well known ports\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Well Known Ports\");\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(1024);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, 1, 1024, HostActivity.this);\n }\n });\n\n scanPortRangeButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning a port range\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.portRangeDialog = new Dialog(HostActivity.this);\n portRangeDialog.setTitle(\"Select Port Range\");\n portRangeDialog.setContentView(R.layout.port_range);\n portRangeDialog.show();\n\n final NumberPicker portRangePickerStart = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStart);\n final NumberPicker portRangePickerStop = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStop);\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n\n portRangePickerStart.setMinValue(1);\n portRangePickerStart.setMaxValue(65535);\n portRangePickerStart.setWrapSelectorWheel(false);\n portRangePickerStop.setMinValue(1);\n portRangePickerStop.setMaxValue(65535);\n portRangePickerStop.setWrapSelectorWheel(false);\n\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n int startPort = portRangePickerStart.getValue();\n int stopPort = portRangePickerStop.getValue();\n\n if((startPort - stopPort >= 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, startPort, stopPort, HostActivity.this);\n }\n });\n }\n });\n\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putString(\"hostIp\", this.hostIp);\n savedState.putString(\"hostName\", this.hostName);\n savedState.putString(\"hostMac\", this.hostMac);\n savedState.putStringArrayList(\"ports\", this.ports);\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if(this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n this.scanProgress += output;\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if(scanProgressDialog != null && scanProgressDialog.isShowing()) {\n if(scanProgress % 50 == 0) {\n scanProgressDialog.setProgress(scanProgress);\n }\n }\n }\n });\n }\n\n \/**\n * Delegate to determine if the progress dialog should be dismissed or not\n *\n * @param output True if the dialog should be dismissed\n *\/\n @Override\n public void processFinish(boolean output) {\n if(output && this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n this.scanProgress = 0;\n }\n if(output && this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(Map output) {\n try {\n int scannedPort = output.keySet().iterator().next();\n BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open(\"ports.csv\")));\n String line;\n String item = String.valueOf(scannedPort);\n\n while((line = reader.readLine()) != null) {\n String[] portInfo = line.split(\",\");\n String name;\n String port;\n\n if(portInfo.length > 2) {\n name = portInfo[0];\n port = portInfo[1];\n }\n else {\n name = \"unknown\";\n port = null;\n }\n\n if(scannedPort == Integer.parseInt(port)) {\n item = item + \" - \" + name;\n if(output.get(scannedPort) != null) {\n item += \" (\" + output.get(scannedPort) + \")\";\n }\n\n final String finalItem = item;\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ports.add(finalItem);\n Collections.sort(ports);\n adapter.notifyDataSetChanged();\n }\n });\n\n reader.close();\n break;\n }\n }\n }\n catch(IOException | NumberFormatException ignored) {\n }\n }\n\n \/**\n * Delegate to handle setting the hostname in the UI\n *\n * @param output Hostname\n *\/\n @Override\n public void processFinish(String output) {\n if(output != null) {\n this.hostNameLabel.setText(output);\n }\n else {\n this.hostNameLabel.setText(\"Couldn't get hostname\");\n }\n }\n}\n\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the execution time. Write the entire code and no other text:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Map;\n\n\npublic class HostActivity extends Activity implements HostAsyncResponse {\n\n private static final String TAG = \"HostActivity\";\n\n private Wireless wifi;\n private Host host = new Host();\n private TextView hostNameLabel;\n private String hostName;\n private String hostIp;\n private String hostMac;\n private ArrayAdapter adapter;\n private ArrayList ports = new ArrayList<>();\n private ProgressDialog scanProgressDialog;\n private Dialog portRangeDialog;\n private int scanProgress;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_host);\n\n TextView hostIpLabel = (TextView) findViewById(R.id.hostIpLabel);\n this.hostNameLabel = (TextView) findViewById(R.id.hostName);\n TextView hostMacVendor = (TextView) findViewById(R.id.hostMacVendor);\n Button scanWellKnownPortsButton = (Button) findViewById(R.id.scanWellKnownPorts);\n Button scanPortRangeButton = (Button) findViewById(R.id.scanPortRange);\n ListView portList = (ListView) findViewById(R.id.portList);\n TextView hostMacLabel = (TextView) findViewById(R.id.hostMac);\n\n if(savedInstanceState != null) {\n this.hostIp = savedInstanceState.getString(\"hostIp\");\n this.hostMac = savedInstanceState.getString(\"hostMac\");\n this.hostName = savedInstanceState.getString(\"hostName\");\n this.ports = savedInstanceState.getStringArrayList(\"ports\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n else if(savedInstanceState == null) {\n Bundle extras = getIntent().getExtras();\n this.hostIp = extras.getString(\"HOST\");\n this.hostMac = extras.getString(\"MAC\");\n\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(adapter);\n }\n\n this.wifi = new Wireless(this);\n\n this.host.getHostname(this.hostIp, this);\n\n String mac = this.hostMac.replace(\":\", \"\");\n mac = mac.substring(0, 6);\n\n hostMacVendor.setText(this.host.getMacVendor(mac, this));\n\n hostIpLabel.setText(this.hostIp);\n hostMacLabel.setText(this.hostMac);\n\n scanWellKnownPortsButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning well known ports\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Well Known Ports\");\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(1024);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, 1, 1024, HostActivity.this);\n }\n });\n\n scanPortRangeButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning a port range\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.portRangeDialog = new Dialog(HostActivity.this);\n portRangeDialog.setTitle(\"Select Port Range\");\n portRangeDialog.setContentView(R.layout.port_range);\n portRangeDialog.show();\n\n final NumberPicker portRangePickerStart = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStart);\n final NumberPicker portRangePickerStop = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStop);\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n\n portRangePickerStart.setMinValue(1);\n portRangePickerStart.setMaxValue(65535);\n portRangePickerStart.setWrapSelectorWheel(false);\n portRangePickerStop.setMinValue(1);\n portRangePickerStop.setMaxValue(65535);\n portRangePickerStop.setWrapSelectorWheel(false);\n\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n int startPort = portRangePickerStart.getValue();\n int stopPort = portRangePickerStop.getValue();\n\n if((startPort - stopPort >= 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, startPort, stopPort, HostActivity.this);\n }\n });\n }\n });\n\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putString(\"hostIp\", this.hostIp);\n savedState.putString(\"hostName\", this.hostName);\n savedState.putString(\"hostMac\", this.hostMac);\n savedState.putStringArrayList(\"ports\", this.ports);\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if(this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n this.scanProgress += output;\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if(scanProgressDialog != null && scanProgressDialog.isShowing()) {\n if(scanProgress % 50 == 0) {\n scanProgressDialog.setProgress(scanProgress);\n }\n }\n }\n });\n }\n\n \/**\n * Delegate to determine if the progress dialog should be dismissed or not\n *\n * @param output True if the dialog should be dismissed\n *\/\n @Override\n public void processFinish(boolean output) {\n if(output && this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n this.scanProgress = 0;\n }\n if(output && this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(Map output) {\n try {\n int scannedPort = output.keySet().iterator().next();\n BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open(\"ports.csv\")));\n String line;\n String item = String.valueOf(scannedPort);\n\n while((line = reader.readLine()) != null) {\n String[] portInfo = line.split(\",\");\n String name;\n String port;\n\n if(portInfo.length > 2) {\n name = portInfo[0];\n port = portInfo[1];\n }\n else {\n name = \"unknown\";\n port = null;\n }\n\n if(scannedPort == Integer.parseInt(port)) {\n item = item + \" - \" + name;\n if(output.get(scannedPort) != null) {\n item += \" (\" + output.get(scannedPort) + \")\";\n }\n\n final String finalItem = item;\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ports.add(finalItem);\n Collections.sort(ports);\n adapter.notifyDataSetChanged();\n }\n });\n\n reader.close();\n break;\n }\n }\n }\n catch(IOException | NumberFormatException ignored) {\n }\n }\n\n \/**\n * Delegate to handle setting the hostname in the UI\n *\n * @param output Hostname\n *\/\n @Override\n public void processFinish(String output) {\n if(output != null) {\n this.hostNameLabel.setText(output);\n }\n else {\n this.hostNameLabel.setText(\"Couldn't get hostname\");\n }\n }\n}\n\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nImprove CPU and memory usage in processFinish function. Write the entire code and no other text in the response.\n\n### Concepts:\n[in] processFinish function\n[hint] Move out conditionals that are being evaluated on the UI thread outside of the UI thread. Only do what is necessary on the UI thread which is to set the progress.\n\n### Given program:\n```java\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Map;\n\n\npublic class HostActivity extends Activity implements HostAsyncResponse {\n\n private static final String TAG = \"HostActivity\";\n\n private Wireless wifi;\n private Host host = new Host();\n private TextView hostNameLabel;\n private String hostName;\n private String hostIp;\n private String hostMac;\n private ArrayAdapter adapter;\n private ArrayList ports = new ArrayList<>();\n private ProgressDialog scanProgressDialog;\n private Dialog portRangeDialog;\n private int scanProgress;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_host);\n\n TextView hostIpLabel = (TextView) findViewById(R.id.hostIpLabel);\n this.hostNameLabel = (TextView) findViewById(R.id.hostName);\n TextView hostMacVendor = (TextView) findViewById(R.id.hostMacVendor);\n Button scanWellKnownPortsButton = (Button) findViewById(R.id.scanWellKnownPorts);\n Button scanPortRangeButton = (Button) findViewById(R.id.scanPortRange);\n ListView portList = (ListView) findViewById(R.id.portList);\n TextView hostMacLabel = (TextView) findViewById(R.id.hostMac);\n\n if(savedInstanceState != null) {\n this.hostIp = savedInstanceState.getString(\"hostIp\");\n this.hostMac = savedInstanceState.getString(\"hostMac\");\n this.hostName = savedInstanceState.getString(\"hostName\");\n this.ports = savedInstanceState.getStringArrayList(\"ports\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n else if(savedInstanceState == null) {\n Bundle extras = getIntent().getExtras();\n this.hostIp = extras.getString(\"HOST\");\n this.hostMac = extras.getString(\"MAC\");\n\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(adapter);\n }\n\n this.wifi = new Wireless(this);\n\n this.host.getHostname(this.hostIp, this);\n\n String mac = this.hostMac.replace(\":\", \"\");\n mac = mac.substring(0, 6);\n\n hostMacVendor.setText(this.host.getMacVendor(mac, this));\n\n hostIpLabel.setText(this.hostIp);\n hostMacLabel.setText(this.hostMac);\n\n scanWellKnownPortsButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning well known ports\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Well Known Ports\");\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(1024);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, 1, 1024, HostActivity.this);\n }\n });\n\n scanPortRangeButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning a port range\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.portRangeDialog = new Dialog(HostActivity.this);\n portRangeDialog.setTitle(\"Select Port Range\");\n portRangeDialog.setContentView(R.layout.port_range);\n portRangeDialog.show();\n\n final NumberPicker portRangePickerStart = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStart);\n final NumberPicker portRangePickerStop = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStop);\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n\n portRangePickerStart.setMinValue(1);\n portRangePickerStart.setMaxValue(65535);\n portRangePickerStart.setWrapSelectorWheel(false);\n portRangePickerStop.setMinValue(1);\n portRangePickerStop.setMaxValue(65535);\n portRangePickerStop.setWrapSelectorWheel(false);\n\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n int startPort = portRangePickerStart.getValue();\n int stopPort = portRangePickerStop.getValue();\n\n if((startPort - stopPort >= 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, startPort, stopPort, HostActivity.this);\n }\n });\n }\n });\n\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putString(\"hostIp\", this.hostIp);\n savedState.putString(\"hostName\", this.hostName);\n savedState.putString(\"hostMac\", this.hostMac);\n savedState.putStringArrayList(\"ports\", this.ports);\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if(this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n this.scanProgress += output;\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if(scanProgressDialog != null && scanProgressDialog.isShowing()) {\n if(scanProgress % 50 == 0) {\n scanProgressDialog.setProgress(scanProgress);\n }\n }\n }\n });\n }\n\n \/**\n * Delegate to determine if the progress dialog should be dismissed or not\n *\n * @param output True if the dialog should be dismissed\n *\/\n @Override\n public void processFinish(boolean output) {\n if(output && this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n this.scanProgress = 0;\n }\n if(output && this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(Map output) {\n try {\n int scannedPort = output.keySet().iterator().next();\n BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open(\"ports.csv\")));\n String line;\n String item = String.valueOf(scannedPort);\n\n while((line = reader.readLine()) != null) {\n String[] portInfo = line.split(\",\");\n String name;\n String port;\n\n if(portInfo.length > 2) {\n name = portInfo[0];\n port = portInfo[1];\n }\n else {\n name = \"unknown\";\n port = null;\n }\n\n if(scannedPort == Integer.parseInt(port)) {\n item = item + \" - \" + name;\n if(output.get(scannedPort) != null) {\n item += \" (\" + output.get(scannedPort) + \")\";\n }\n\n final String finalItem = item;\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ports.add(finalItem);\n Collections.sort(ports);\n adapter.notifyDataSetChanged();\n }\n });\n\n reader.close();\n break;\n }\n }\n }\n catch(IOException | NumberFormatException ignored) {\n }\n }\n\n \/**\n * Delegate to handle setting the hostname in the UI\n *\n * @param output Hostname\n *\/\n @Override\n public void processFinish(String output) {\n if(output != null) {\n this.hostNameLabel.setText(output);\n }\n else {\n this.hostNameLabel.setText(\"Couldn't get hostname\");\n }\n }\n}\n\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport android.content.Context;\n\nimport android.content.pm.PackageInfo;\nimport android.text.TextUtils;\nimport android.util.DisplayMetrics;\nimport android.util.Log;\nimport com.nostra13.universalimageloader.utils.StorageUtils;\n\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.security.cert.Certificate;\nimport java.security.cert.CertificateEncodingException;\nimport java.text.SimpleDateFormat;\nimport java.security.MessageDigest;\nimport java.util.*;\n\npublic final class Utils {\n\n public static final int BUFFER_SIZE = 4096;\n\n \/\/ The date format used for storing dates (e.g. lastupdated, added) in the\n \/\/ database.\n public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.ENGLISH);\n\n private static final String[] FRIENDLY_SIZE_FORMAT = {\n \"%.0f B\", \"%.0f KiB\", \"%.1f MiB\", \"%.2f GiB\" };\n\n public static final SimpleDateFormat LOG_DATE_FORMAT =\n new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.ENGLISH);\n\n public static String getIconsDir(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n String iconsDir;\n if (metrics.densityDpi >= 640) {\n iconsDir = \"\/icons-640\/\";\n } else if (metrics.densityDpi >= 480) {\n iconsDir = \"\/icons-480\/\";\n } else if (metrics.densityDpi >= 320) {\n iconsDir = \"\/icons-320\/\";\n } else if (metrics.densityDpi >= 240) {\n iconsDir = \"\/icons-240\/\";\n } else if (metrics.densityDpi >= 160) {\n iconsDir = \"\/icons-160\/\";\n } else {\n iconsDir = \"\/icons-120\/\";\n }\n return iconsDir;\n }\n\n public static void copy(InputStream input, OutputStream output)\n throws IOException {\n copy(input, output, null, null);\n }\n\n public static void copy(InputStream input, OutputStream output,\n ProgressListener progressListener,\n ProgressListener.Event templateProgressEvent)\n throws IOException {\n byte[] buffer = new byte[BUFFER_SIZE];\n int bytesRead = 0;\n while (true) {\n int count = input.read(buffer);\n if (count == -1) {\n break;\n }\n if (progressListener != null) {\n bytesRead += count;\n templateProgressEvent.progress = bytesRead;\n progressListener.onProgress(templateProgressEvent);\n }\n output.write(buffer, 0, count);\n }\n output.flush();\n }\n\n public static void closeQuietly(Closeable closeable) {\n if (closeable == null) {\n return;\n }\n try {\n closeable.close();\n } catch (IOException ioe) {\n \/\/ ignore\n }\n }\n\n public static String getFriendlySize(int size) {\n double s = size;\n int i = 0;\n while (i < FRIENDLY_SIZE_FORMAT.length - 1 && s >= 1024) {\n s = (100 * s \/ 1024) \/ 100.0;\n i++;\n }\n return String.format(FRIENDLY_SIZE_FORMAT[i], s);\n }\n\n private static final String[] androidVersionNames = {\n \"?\", \/\/ 0, undefined\n \"1.0\", \/\/ 1\n \"1.1\", \/\/ 2\n \"1.5\", \/\/ 3\n \"1.6\", \/\/ 4\n \"2.0\", \/\/ 5\n \"2.0.1\", \/\/ 6\n \"2.1\", \/\/ 7\n \"2.2\", \/\/ 8\n \"2.3\", \/\/ 9\n \"2.3.3\", \/\/ 10\n \"3.0\", \/\/ 11\n \"3.1\", \/\/ 12\n \"3.2\", \/\/ 13\n \"4.0\", \/\/ 14\n \"4.0.3\", \/\/ 15\n \"4.1\", \/\/ 16\n \"4.2\", \/\/ 17\n \"4.3\", \/\/ 18\n \"4.4\" \/\/ 19\n };\n\n public static String getAndroidVersionName(int sdkLevel) {\n if (sdkLevel < 0 || sdkLevel > 19) return androidVersionNames[0];\n return androidVersionNames[sdkLevel];\n }\n\n public static int countSubstringOccurrence(File file, String substring) throws IOException {\n int count = 0;\n FileReader input = null;\n try {\n int currentSubstringIndex = 0;\n char[] buffer = new char[4096];\n\n input = new FileReader(file);\n int numRead = input.read(buffer);\n while(numRead != -1) {\n\n for (char c : buffer) {\n if (c == substring.charAt(currentSubstringIndex)) {\n currentSubstringIndex ++;\n if (currentSubstringIndex == substring.length()) {\n count ++;\n currentSubstringIndex = 0;\n }\n } else {\n currentSubstringIndex = 0;\n }\n }\n numRead = input.read(buffer);\n }\n } finally {\n closeQuietly(input);\n }\n return count;\n }\n\n \/\/ return a fingerprint formatted for display\n public static String formatFingerprint(String fingerprint) {\n if (fingerprint.length() != 62) \/\/ SHA-256 is 62 hex chars\n return \"BAD FINGERPRINT\";\n String displayFP = fingerprint.substring(0, 2);\n for (int i = 2; i < fingerprint.length(); i = i + 2)\n displayFP += \" \" + fingerprint.substring(i, i + 2);\n return displayFP;\n }\n\n public static File getApkCacheDir(Context context) {\n File apkCacheDir = new File(\n StorageUtils.getCacheDirectory(context, true), \"apks\");\n if (!apkCacheDir.exists()) {\n apkCacheDir.mkdir();\n }\n return apkCacheDir;\n }\n\n public static Map getInstalledApps(Context context) {\n return installedApkCache.getApks(context);\n }\n\n public static void clearInstalledApksCache() {\n installedApkCache.emptyCache();\n }\n\n public static String calcFingerprint(String keyHexString) {\n if (TextUtils.isEmpty(keyHexString))\n return null;\n else\n return calcFingerprint(Hasher.unhex(keyHexString));\n }\n\n public static String calcFingerprint(Certificate cert) {\n try {\n return calcFingerprint(cert.getEncoded());\n } catch (CertificateEncodingException e) {\n return null;\n }\n }\n\n public static String calcFingerprint(byte[] key) {\n String ret = null;\n try {\n \/\/ keytool -list -v gives you the SHA-256 fingerprint\n MessageDigest digest = MessageDigest.getInstance(\"SHA-256\");\n digest.update(key);\n byte[] fingerprint = digest.digest();\n Formatter formatter = new Formatter(new StringBuilder());\n for (int i = 1; i < fingerprint.length; i++) {\n formatter.format(\"%02X\", fingerprint[i]);\n }\n ret = formatter.toString();\n formatter.close();\n } catch (Exception e) {\n Log.w(\"FDroid\", \"Unable to get certificate fingerprint.\\n\"\n + Log.getStackTraceString(e));\n }\n return ret;\n }\n\n public static class CommaSeparatedList implements Iterable {\n private String value;\n\n private CommaSeparatedList(String list) {\n value = list;\n }\n\n public static CommaSeparatedList make(List list) {\n if (list == null || list.size() == 0)\n return null;\n else {\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < list.size(); i ++) {\n if (i > 0) {\n sb.append(',');\n }\n sb.append(list.get(i));\n }\n return new CommaSeparatedList(sb.toString());\n }\n }\n\n public static CommaSeparatedList make(String list) {\n if (list == null || list.length() == 0)\n return null;\n else\n return new CommaSeparatedList(list);\n }\n\n public static String str(CommaSeparatedList instance) {\n return (instance == null ? null : instance.toString());\n }\n\n @Override\n public String toString() {\n return value;\n }\n\n public String toPrettyString() {\n return value.replaceAll(\",\", \", \");\n }\n\n @Override\n public Iterator iterator() {\n TextUtils.SimpleStringSplitter splitter = new TextUtils.SimpleStringSplitter(',');\n splitter.setString(value);\n return splitter.iterator();\n }\n\n public boolean contains(String v) {\n for (String s : this) {\n if (s.equals(v))\n return true;\n }\n return false;\n }\n }\n\n private static InstalledApkCache installedApkCache = null;\n\n \/**\n * We do a lot of querying of the installed app's. As a result, we like\n * to cache this information quite heavily (and flush the cache when new\n * apps are installed). The caching implementation needs to be setup like\n * this so that it is possible to mock for testing purposes.\n *\/\n public static void setupInstalledApkCache(InstalledApkCache cache) {\n installedApkCache = cache;\n }\n\n public static class InstalledApkCache {\n\n protected Map installedApks = null;\n\n protected Map buildAppList(Context context) {\n Map info = new HashMap();\n Log.d(\"FDroid\", \"Reading installed packages\");\n List installedPackages = context.getPackageManager().getInstalledPackages(0);\n for (PackageInfo appInfo : installedPackages) {\n info.put(appInfo.packageName, appInfo);\n }\n return info;\n }\n\n public Map getApks(Context context) {\n if (installedApks == null) {\n installedApks = buildAppList(context);\n }\n return installedApks;\n }\n\n public void emptyCache() {\n installedApks = null;\n }\n\n }\n\n\n}\n\n\nCode-B:\n\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport android.content.Context;\n\nimport android.content.pm.PackageInfo;\nimport android.text.TextUtils;\nimport android.util.DisplayMetrics;\nimport android.util.Log;\nimport com.nostra13.universalimageloader.utils.StorageUtils;\n\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.security.cert.Certificate;\nimport java.security.cert.CertificateEncodingException;\nimport java.text.SimpleDateFormat;\nimport java.security.MessageDigest;\nimport java.util.*;\n\npublic final class Utils {\n\n public static final int BUFFER_SIZE = 4096;\n\n \/\/ The date format used for storing dates (e.g. lastupdated, added) in the\n \/\/ database.\n public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.ENGLISH);\n\n private static final String[] FRIENDLY_SIZE_FORMAT = {\n \"%.0f B\", \"%.0f KiB\", \"%.1f MiB\", \"%.2f GiB\" };\n\n public static final SimpleDateFormat LOG_DATE_FORMAT =\n new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.ENGLISH);\n\n public static String getIconsDir(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n String iconsDir;\n if (metrics.densityDpi >= 640) {\n iconsDir = \"\/icons-640\/\";\n } else if (metrics.densityDpi >= 480) {\n iconsDir = \"\/icons-480\/\";\n } else if (metrics.densityDpi >= 320) {\n iconsDir = \"\/icons-320\/\";\n } else if (metrics.densityDpi >= 240) {\n iconsDir = \"\/icons-240\/\";\n } else if (metrics.densityDpi >= 160) {\n iconsDir = \"\/icons-160\/\";\n } else {\n iconsDir = \"\/icons-120\/\";\n }\n return iconsDir;\n }\n\n public static void copy(InputStream input, OutputStream output)\n throws IOException {\n copy(input, output, null, null);\n }\n\n public static void copy(InputStream input, OutputStream output,\n ProgressListener progressListener,\n ProgressListener.Event templateProgressEvent)\n throws IOException {\n byte[] buffer = new byte[BUFFER_SIZE];\n int bytesRead = 0;\n while (true) {\n int count = input.read(buffer);\n if (count == -1) {\n break;\n }\n if (progressListener != null) {\n bytesRead += count;\n templateProgressEvent.progress = bytesRead;\n progressListener.onProgress(templateProgressEvent);\n }\n output.write(buffer, 0, count);\n }\n output.flush();\n }\n\n public static void closeQuietly(Closeable closeable) {\n if (closeable == null) {\n return;\n }\n try {\n closeable.close();\n } catch (IOException ioe) {\n \/\/ ignore\n }\n }\n\n public static String getFriendlySize(int size) {\n double s = size;\n int i = 0;\n while (i < FRIENDLY_SIZE_FORMAT.length - 1 && s >= 1024) {\n s = (100 * s \/ 1024) \/ 100.0;\n i++;\n }\n return String.format(FRIENDLY_SIZE_FORMAT[i], s);\n }\n\n public static String getAndroidVersionName(int sdkLevel) {\n if (sdkLevel < 1) return null;\n switch (sdkLevel) {\n case 19: return \"4.4\";\n case 18: return \"4.3\";\n case 17: return \"4.2\";\n case 16: return \"4.1\";\n case 15: return \"4.0.3\";\n case 14: return \"4.0\";\n case 13: return \"3.2\";\n case 12: return \"3.1\";\n case 11: return \"3.0\";\n case 10: return \"2.3.3\";\n case 9: return \"2.3\";\n case 8: return \"2.2\";\n case 7: return \"2.1\";\n case 6: return \"2.0.1\";\n case 5: return \"2.0\";\n case 4: return \"1.6\";\n case 3: return \"1.5\";\n case 2: return \"1.1\";\n case 1: return \"1.0\";\n default: return \"?\";\n }\n }\n\n public static int countSubstringOccurrence(File file, String substring) throws IOException {\n int count = 0;\n FileReader input = null;\n try {\n int currentSubstringIndex = 0;\n char[] buffer = new char[4096];\n\n input = new FileReader(file);\n int numRead = input.read(buffer);\n while(numRead != -1) {\n\n for (char c : buffer) {\n if (c == substring.charAt(currentSubstringIndex)) {\n currentSubstringIndex ++;\n if (currentSubstringIndex == substring.length()) {\n count ++;\n currentSubstringIndex = 0;\n }\n } else {\n currentSubstringIndex = 0;\n }\n }\n numRead = input.read(buffer);\n }\n } finally {\n closeQuietly(input);\n }\n return count;\n }\n\n \/\/ return a fingerprint formatted for display\n public static String formatFingerprint(String fingerprint) {\n if (fingerprint.length() != 62) \/\/ SHA-256 is 62 hex chars\n return \"BAD FINGERPRINT\";\n String displayFP = fingerprint.substring(0, 2);\n for (int i = 2; i < fingerprint.length(); i = i + 2)\n displayFP += \" \" + fingerprint.substring(i, i + 2);\n return displayFP;\n }\n\n public static File getApkCacheDir(Context context) {\n File apkCacheDir = new File(\n StorageUtils.getCacheDirectory(context, true), \"apks\");\n if (!apkCacheDir.exists()) {\n apkCacheDir.mkdir();\n }\n return apkCacheDir;\n }\n\n public static Map getInstalledApps(Context context) {\n return installedApkCache.getApks(context);\n }\n\n public static void clearInstalledApksCache() {\n installedApkCache.emptyCache();\n }\n\n public static String calcFingerprint(String keyHexString) {\n if (TextUtils.isEmpty(keyHexString))\n return null;\n else\n return calcFingerprint(Hasher.unhex(keyHexString));\n }\n\n public static String calcFingerprint(Certificate cert) {\n try {\n return calcFingerprint(cert.getEncoded());\n } catch (CertificateEncodingException e) {\n return null;\n }\n }\n\n public static String calcFingerprint(byte[] key) {\n String ret = null;\n try {\n \/\/ keytool -list -v gives you the SHA-256 fingerprint\n MessageDigest digest = MessageDigest.getInstance(\"SHA-256\");\n digest.update(key);\n byte[] fingerprint = digest.digest();\n Formatter formatter = new Formatter(new StringBuilder());\n for (int i = 1; i < fingerprint.length; i++) {\n formatter.format(\"%02X\", fingerprint[i]);\n }\n ret = formatter.toString();\n formatter.close();\n } catch (Exception e) {\n Log.w(\"FDroid\", \"Unable to get certificate fingerprint.\\n\"\n + Log.getStackTraceString(e));\n }\n return ret;\n }\n\n public static class CommaSeparatedList implements Iterable {\n private String value;\n\n private CommaSeparatedList(String list) {\n value = list;\n }\n\n public static CommaSeparatedList make(List list) {\n if (list == null || list.size() == 0)\n return null;\n else {\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < list.size(); i ++) {\n if (i > 0) {\n sb.append(',');\n }\n sb.append(list.get(i));\n }\n return new CommaSeparatedList(sb.toString());\n }\n }\n\n public static CommaSeparatedList make(String list) {\n if (list == null || list.length() == 0)\n return null;\n else\n return new CommaSeparatedList(list);\n }\n\n public static String str(CommaSeparatedList instance) {\n return (instance == null ? null : instance.toString());\n }\n\n @Override\n public String toString() {\n return value;\n }\n\n public String toPrettyString() {\n return value.replaceAll(\",\", \", \");\n }\n\n @Override\n public Iterator iterator() {\n TextUtils.SimpleStringSplitter splitter = new TextUtils.SimpleStringSplitter(',');\n splitter.setString(value);\n return splitter.iterator();\n }\n\n public boolean contains(String v) {\n for (String s : this) {\n if (s.equals(v))\n return true;\n }\n return false;\n }\n }\n\n private static InstalledApkCache installedApkCache = null;\n\n \/**\n * We do a lot of querying of the installed app's. As a result, we like\n * to cache this information quite heavily (and flush the cache when new\n * apps are installed). The caching implementation needs to be setup like\n * this so that it is possible to mock for testing purposes.\n *\/\n public static void setupInstalledApkCache(InstalledApkCache cache) {\n installedApkCache = cache;\n }\n\n public static class InstalledApkCache {\n\n protected Map installedApks = null;\n\n protected Map buildAppList(Context context) {\n Map info = new HashMap();\n Log.d(\"FDroid\", \"Reading installed packages\");\n List installedPackages = context.getPackageManager().getInstalledPackages(0);\n for (PackageInfo appInfo : installedPackages) {\n info.put(appInfo.packageName, appInfo);\n }\n return info;\n }\n\n public Map getApks(Context context) {\n if (installedApks == null) {\n installedApks = buildAppList(context);\n }\n return installedApks;\n }\n\n public void emptyCache() {\n installedApks = null;\n }\n\n }\n\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\n\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport android.content.Context;\n\nimport android.content.pm.PackageInfo;\nimport android.text.TextUtils;\nimport android.util.DisplayMetrics;\nimport android.util.Log;\nimport com.nostra13.universalimageloader.utils.StorageUtils;\n\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.security.cert.Certificate;\nimport java.security.cert.CertificateEncodingException;\nimport java.text.SimpleDateFormat;\nimport java.security.MessageDigest;\nimport java.util.*;\n\npublic final class Utils {\n\n public static final int BUFFER_SIZE = 4096;\n\n \/\/ The date format used for storing dates (e.g. lastupdated, added) in the\n \/\/ database.\n public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.ENGLISH);\n\n private static final String[] FRIENDLY_SIZE_FORMAT = {\n \"%.0f B\", \"%.0f KiB\", \"%.1f MiB\", \"%.2f GiB\" };\n\n public static final SimpleDateFormat LOG_DATE_FORMAT =\n new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.ENGLISH);\n\n public static String getIconsDir(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n String iconsDir;\n if (metrics.densityDpi >= 640) {\n iconsDir = \"\/icons-640\/\";\n } else if (metrics.densityDpi >= 480) {\n iconsDir = \"\/icons-480\/\";\n } else if (metrics.densityDpi >= 320) {\n iconsDir = \"\/icons-320\/\";\n } else if (metrics.densityDpi >= 240) {\n iconsDir = \"\/icons-240\/\";\n } else if (metrics.densityDpi >= 160) {\n iconsDir = \"\/icons-160\/\";\n } else {\n iconsDir = \"\/icons-120\/\";\n }\n return iconsDir;\n }\n\n public static void copy(InputStream input, OutputStream output)\n throws IOException {\n copy(input, output, null, null);\n }\n\n public static void copy(InputStream input, OutputStream output,\n ProgressListener progressListener,\n ProgressListener.Event templateProgressEvent)\n throws IOException {\n byte[] buffer = new byte[BUFFER_SIZE];\n int bytesRead = 0;\n while (true) {\n int count = input.read(buffer);\n if (count == -1) {\n break;\n }\n if (progressListener != null) {\n bytesRead += count;\n templateProgressEvent.progress = bytesRead;\n progressListener.onProgress(templateProgressEvent);\n }\n output.write(buffer, 0, count);\n }\n output.flush();\n }\n\n public static void closeQuietly(Closeable closeable) {\n if (closeable == null) {\n return;\n }\n try {\n closeable.close();\n } catch (IOException ioe) {\n \/\/ ignore\n }\n }\n\n public static String getFriendlySize(int size) {\n double s = size;\n int i = 0;\n while (i < FRIENDLY_SIZE_FORMAT.length - 1 && s >= 1024) {\n s = (100 * s \/ 1024) \/ 100.0;\n i++;\n }\n return String.format(FRIENDLY_SIZE_FORMAT[i], s);\n }\n\n public static String getAndroidVersionName(int sdkLevel) {\n if (sdkLevel < 1) return null;\n switch (sdkLevel) {\n case 19: return \"4.4\";\n case 18: return \"4.3\";\n case 17: return \"4.2\";\n case 16: return \"4.1\";\n case 15: return \"4.0.3\";\n case 14: return \"4.0\";\n case 13: return \"3.2\";\n case 12: return \"3.1\";\n case 11: return \"3.0\";\n case 10: return \"2.3.3\";\n case 9: return \"2.3\";\n case 8: return \"2.2\";\n case 7: return \"2.1\";\n case 6: return \"2.0.1\";\n case 5: return \"2.0\";\n case 4: return \"1.6\";\n case 3: return \"1.5\";\n case 2: return \"1.1\";\n case 1: return \"1.0\";\n default: return \"?\";\n }\n }\n\n public static int countSubstringOccurrence(File file, String substring) throws IOException {\n int count = 0;\n FileReader input = null;\n try {\n int currentSubstringIndex = 0;\n char[] buffer = new char[4096];\n\n input = new FileReader(file);\n int numRead = input.read(buffer);\n while(numRead != -1) {\n\n for (char c : buffer) {\n if (c == substring.charAt(currentSubstringIndex)) {\n currentSubstringIndex ++;\n if (currentSubstringIndex == substring.length()) {\n count ++;\n currentSubstringIndex = 0;\n }\n } else {\n currentSubstringIndex = 0;\n }\n }\n numRead = input.read(buffer);\n }\n } finally {\n closeQuietly(input);\n }\n return count;\n }\n\n \/\/ return a fingerprint formatted for display\n public static String formatFingerprint(String fingerprint) {\n if (fingerprint.length() != 62) \/\/ SHA-256 is 62 hex chars\n return \"BAD FINGERPRINT\";\n String displayFP = fingerprint.substring(0, 2);\n for (int i = 2; i < fingerprint.length(); i = i + 2)\n displayFP += \" \" + fingerprint.substring(i, i + 2);\n return displayFP;\n }\n\n public static File getApkCacheDir(Context context) {\n File apkCacheDir = new File(\n StorageUtils.getCacheDirectory(context, true), \"apks\");\n if (!apkCacheDir.exists()) {\n apkCacheDir.mkdir();\n }\n return apkCacheDir;\n }\n\n public static Map getInstalledApps(Context context) {\n return installedApkCache.getApks(context);\n }\n\n public static void clearInstalledApksCache() {\n installedApkCache.emptyCache();\n }\n\n public static String calcFingerprint(String keyHexString) {\n if (TextUtils.isEmpty(keyHexString))\n return null;\n else\n return calcFingerprint(Hasher.unhex(keyHexString));\n }\n\n public static String calcFingerprint(Certificate cert) {\n try {\n return calcFingerprint(cert.getEncoded());\n } catch (CertificateEncodingException e) {\n return null;\n }\n }\n\n public static String calcFingerprint(byte[] key) {\n String ret = null;\n try {\n \/\/ keytool -list -v gives you the SHA-256 fingerprint\n MessageDigest digest = MessageDigest.getInstance(\"SHA-256\");\n digest.update(key);\n byte[] fingerprint = digest.digest();\n Formatter formatter = new Formatter(new StringBuilder());\n for (int i = 1; i < fingerprint.length; i++) {\n formatter.format(\"%02X\", fingerprint[i]);\n }\n ret = formatter.toString();\n formatter.close();\n } catch (Exception e) {\n Log.w(\"FDroid\", \"Unable to get certificate fingerprint.\\n\"\n + Log.getStackTraceString(e));\n }\n return ret;\n }\n\n public static class CommaSeparatedList implements Iterable {\n private String value;\n\n private CommaSeparatedList(String list) {\n value = list;\n }\n\n public static CommaSeparatedList make(List list) {\n if (list == null || list.size() == 0)\n return null;\n else {\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < list.size(); i ++) {\n if (i > 0) {\n sb.append(',');\n }\n sb.append(list.get(i));\n }\n return new CommaSeparatedList(sb.toString());\n }\n }\n\n public static CommaSeparatedList make(String list) {\n if (list == null || list.length() == 0)\n return null;\n else\n return new CommaSeparatedList(list);\n }\n\n public static String str(CommaSeparatedList instance) {\n return (instance == null ? null : instance.toString());\n }\n\n @Override\n public String toString() {\n return value;\n }\n\n public String toPrettyString() {\n return value.replaceAll(\",\", \", \");\n }\n\n @Override\n public Iterator iterator() {\n TextUtils.SimpleStringSplitter splitter = new TextUtils.SimpleStringSplitter(',');\n splitter.setString(value);\n return splitter.iterator();\n }\n\n public boolean contains(String v) {\n for (String s : this) {\n if (s.equals(v))\n return true;\n }\n return false;\n }\n }\n\n private static InstalledApkCache installedApkCache = null;\n\n \/**\n * We do a lot of querying of the installed app's. As a result, we like\n * to cache this information quite heavily (and flush the cache when new\n * apps are installed). The caching implementation needs to be setup like\n * this so that it is possible to mock for testing purposes.\n *\/\n public static void setupInstalledApkCache(InstalledApkCache cache) {\n installedApkCache = cache;\n }\n\n public static class InstalledApkCache {\n\n protected Map installedApks = null;\n\n protected Map buildAppList(Context context) {\n Map info = new HashMap();\n Log.d(\"FDroid\", \"Reading installed packages\");\n List installedPackages = context.getPackageManager().getInstalledPackages(0);\n for (PackageInfo appInfo : installedPackages) {\n info.put(appInfo.packageName, appInfo);\n }\n return info;\n }\n\n public Map getApks(Context context) {\n if (installedApks == null) {\n installedApks = buildAppList(context);\n }\n return installedApks;\n }\n\n public void emptyCache() {\n installedApks = null;\n }\n\n }\n\n\n}\n\n\nCode-B:\n\/*\n * Copyright (C) 2010-12 Ciaran Gultnieks, ciaran@ciarang.com\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 3\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\npackage org.fdroid.fdroid;\n\nimport android.content.Context;\n\nimport android.content.pm.PackageInfo;\nimport android.text.TextUtils;\nimport android.util.DisplayMetrics;\nimport android.util.Log;\nimport com.nostra13.universalimageloader.utils.StorageUtils;\n\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.InputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.security.cert.Certificate;\nimport java.security.cert.CertificateEncodingException;\nimport java.text.SimpleDateFormat;\nimport java.security.MessageDigest;\nimport java.util.*;\n\npublic final class Utils {\n\n public static final int BUFFER_SIZE = 4096;\n\n \/\/ The date format used for storing dates (e.g. lastupdated, added) in the\n \/\/ database.\n public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.ENGLISH);\n\n private static final String[] FRIENDLY_SIZE_FORMAT = {\n \"%.0f B\", \"%.0f KiB\", \"%.1f MiB\", \"%.2f GiB\" };\n\n public static final SimpleDateFormat LOG_DATE_FORMAT =\n new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.ENGLISH);\n\n public static String getIconsDir(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n String iconsDir;\n if (metrics.densityDpi >= 640) {\n iconsDir = \"\/icons-640\/\";\n } else if (metrics.densityDpi >= 480) {\n iconsDir = \"\/icons-480\/\";\n } else if (metrics.densityDpi >= 320) {\n iconsDir = \"\/icons-320\/\";\n } else if (metrics.densityDpi >= 240) {\n iconsDir = \"\/icons-240\/\";\n } else if (metrics.densityDpi >= 160) {\n iconsDir = \"\/icons-160\/\";\n } else {\n iconsDir = \"\/icons-120\/\";\n }\n return iconsDir;\n }\n\n public static void copy(InputStream input, OutputStream output)\n throws IOException {\n copy(input, output, null, null);\n }\n\n public static void copy(InputStream input, OutputStream output,\n ProgressListener progressListener,\n ProgressListener.Event templateProgressEvent)\n throws IOException {\n byte[] buffer = new byte[BUFFER_SIZE];\n int bytesRead = 0;\n while (true) {\n int count = input.read(buffer);\n if (count == -1) {\n break;\n }\n if (progressListener != null) {\n bytesRead += count;\n templateProgressEvent.progress = bytesRead;\n progressListener.onProgress(templateProgressEvent);\n }\n output.write(buffer, 0, count);\n }\n output.flush();\n }\n\n public static void closeQuietly(Closeable closeable) {\n if (closeable == null) {\n return;\n }\n try {\n closeable.close();\n } catch (IOException ioe) {\n \/\/ ignore\n }\n }\n\n public static String getFriendlySize(int size) {\n double s = size;\n int i = 0;\n while (i < FRIENDLY_SIZE_FORMAT.length - 1 && s >= 1024) {\n s = (100 * s \/ 1024) \/ 100.0;\n i++;\n }\n return String.format(FRIENDLY_SIZE_FORMAT[i], s);\n }\n\n private static final String[] androidVersionNames = {\n \"?\", \/\/ 0, undefined\n \"1.0\", \/\/ 1\n \"1.1\", \/\/ 2\n \"1.5\", \/\/ 3\n \"1.6\", \/\/ 4\n \"2.0\", \/\/ 5\n \"2.0.1\", \/\/ 6\n \"2.1\", \/\/ 7\n \"2.2\", \/\/ 8\n \"2.3\", \/\/ 9\n \"2.3.3\", \/\/ 10\n \"3.0\", \/\/ 11\n \"3.1\", \/\/ 12\n \"3.2\", \/\/ 13\n \"4.0\", \/\/ 14\n \"4.0.3\", \/\/ 15\n \"4.1\", \/\/ 16\n \"4.2\", \/\/ 17\n \"4.3\", \/\/ 18\n \"4.4\" \/\/ 19\n };\n\n public static String getAndroidVersionName(int sdkLevel) {\n if (sdkLevel < 0 || sdkLevel > 19) return androidVersionNames[0];\n return androidVersionNames[sdkLevel];\n }\n\n public static int countSubstringOccurrence(File file, String substring) throws IOException {\n int count = 0;\n FileReader input = null;\n try {\n int currentSubstringIndex = 0;\n char[] buffer = new char[4096];\n\n input = new FileReader(file);\n int numRead = input.read(buffer);\n while(numRead != -1) {\n\n for (char c : buffer) {\n if (c == substring.charAt(currentSubstringIndex)) {\n currentSubstringIndex ++;\n if (currentSubstringIndex == substring.length()) {\n count ++;\n currentSubstringIndex = 0;\n }\n } else {\n currentSubstringIndex = 0;\n }\n }\n numRead = input.read(buffer);\n }\n } finally {\n closeQuietly(input);\n }\n return count;\n }\n\n \/\/ return a fingerprint formatted for display\n public static String formatFingerprint(String fingerprint) {\n if (fingerprint.length() != 62) \/\/ SHA-256 is 62 hex chars\n return \"BAD FINGERPRINT\";\n String displayFP = fingerprint.substring(0, 2);\n for (int i = 2; i < fingerprint.length(); i = i + 2)\n displayFP += \" \" + fingerprint.substring(i, i + 2);\n return displayFP;\n }\n\n public static File getApkCacheDir(Context context) {\n File apkCacheDir = new File(\n StorageUtils.getCacheDirectory(context, true), \"apks\");\n if (!apkCacheDir.exists()) {\n apkCacheDir.mkdir();\n }\n return apkCacheDir;\n }\n\n public static Map getInstalledApps(Context context) {\n return installedApkCache.getApks(context);\n }\n\n public static void clearInstalledApksCache() {\n installedApkCache.emptyCache();\n }\n\n public static String calcFingerprint(String keyHexString) {\n if (TextUtils.isEmpty(keyHexString))\n return null;\n else\n return calcFingerprint(Hasher.unhex(keyHexString));\n }\n\n public static String calcFingerprint(Certificate cert) {\n try {\n return calcFingerprint(cert.getEncoded());\n } catch (CertificateEncodingException e) {\n return null;\n }\n }\n\n public static String calcFingerprint(byte[] key) {\n String ret = null;\n try {\n \/\/ keytool -list -v gives you the SHA-256 fingerprint\n MessageDigest digest = MessageDigest.getInstance(\"SHA-256\");\n digest.update(key);\n byte[] fingerprint = digest.digest();\n Formatter formatter = new Formatter(new StringBuilder());\n for (int i = 1; i < fingerprint.length; i++) {\n formatter.format(\"%02X\", fingerprint[i]);\n }\n ret = formatter.toString();\n formatter.close();\n } catch (Exception e) {\n Log.w(\"FDroid\", \"Unable to get certificate fingerprint.\\n\"\n + Log.getStackTraceString(e));\n }\n return ret;\n }\n\n public static class CommaSeparatedList implements Iterable {\n private String value;\n\n private CommaSeparatedList(String list) {\n value = list;\n }\n\n public static CommaSeparatedList make(List list) {\n if (list == null || list.size() == 0)\n return null;\n else {\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < list.size(); i ++) {\n if (i > 0) {\n sb.append(',');\n }\n sb.append(list.get(i));\n }\n return new CommaSeparatedList(sb.toString());\n }\n }\n\n public static CommaSeparatedList make(String list) {\n if (list == null || list.length() == 0)\n return null;\n else\n return new CommaSeparatedList(list);\n }\n\n public static String str(CommaSeparatedList instance) {\n return (instance == null ? null : instance.toString());\n }\n\n @Override\n public String toString() {\n return value;\n }\n\n public String toPrettyString() {\n return value.replaceAll(\",\", \", \");\n }\n\n @Override\n public Iterator iterator() {\n TextUtils.SimpleStringSplitter splitter = new TextUtils.SimpleStringSplitter(',');\n splitter.setString(value);\n return splitter.iterator();\n }\n\n public boolean contains(String v) {\n for (String s : this) {\n if (s.equals(v))\n return true;\n }\n return false;\n }\n }\n\n private static InstalledApkCache installedApkCache = null;\n\n \/**\n * We do a lot of querying of the installed app's. As a result, we like\n * to cache this information quite heavily (and flush the cache when new\n * apps are installed). The caching implementation needs to be setup like\n * this so that it is possible to mock for testing purposes.\n *\/\n public static void setupInstalledApkCache(InstalledApkCache cache) {\n installedApkCache = cache;\n }\n\n public static class InstalledApkCache {\n\n protected Map installedApks = null;\n\n protected Map buildAppList(Context context) {\n Map info = new HashMap();\n Log.d(\"FDroid\", \"Reading installed packages\");\n List installedPackages = context.getPackageManager().getInstalledPackages(0);\n for (PackageInfo appInfo : installedPackages) {\n info.put(appInfo.packageName, appInfo);\n }\n return info;\n }\n\n public Map getApks(Context context) {\n if (installedApks == null) {\n installedApks = buildAppList(context);\n }\n return installedApks;\n }\n\n public void emptyCache() {\n installedApks = null;\n }\n\n }\n\n\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"framerate","commit":"https:\/\/github.com\/erikusaj\/fdroidTvClient\/commit\/8faf151c9038a3f9c8d7749ba9eced7c8ef2d1f0","commit_message":"'\\\\\"Remove 1 second pause between installing and updating UI.\\\\n\\\\nThis was implemented before because the main screen of the three tab\\\\nlayout needed to update in response to the list of installed apps being\\\\ninstalled. When we scan the list of installed apps upon starting\\\\nF-Droid","source_code":"package org.fdroid.fdroid.data;\n\nimport android.app.IntentService;\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.Signature;\nimport android.net.Uri;\nimport android.os.Process;\nimport android.support.annotation.Nullable;\n\nimport org.acra.ACRA;\nimport org.fdroid.fdroid.Hasher;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Schema.InstalledAppTable;\n\nimport java.io.File;\nimport java.io.FilenameFilter;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\n\nimport rx.functions.Action1;\nimport rx.schedulers.Schedulers;\nimport rx.subjects.PublishSubject;\n\n\/**\n * Handles all updates to {@link InstalledAppProvider}, whether checking the contents\n * versus what Android says is installed, or processing {@link Intent}s that come\n * from {@link android.content.BroadcastReceiver}s for {@link Intent#ACTION_PACKAGE_ADDED}\n * and {@link Intent#ACTION_PACKAGE_REMOVED}\n * \n * Since {@link android.content.ContentProvider#insert(Uri, ContentValues)} does not check\n * for duplicate records, it is entirely the job of this service to ensure that it is not\n * inserting duplicate versions of the same installed APK. On that note,\n * {@link #insertAppIntoDb(Context, PackageInfo, String, String)} and\n * {@link #deleteAppFromDb(Context, String)} are both static methods to enable easy testing\n * of this stuff.\n *\/\npublic class InstalledAppProviderService extends IntentService {\n private static final String TAG = \"InstalledAppProviderSer\";\n\n private static final String ACTION_INSERT = \"org.fdroid.fdroid.data.action.INSERT\";\n private static final String ACTION_DELETE = \"org.fdroid.fdroid.data.action.DELETE\";\n\n private static final String EXTRA_PACKAGE_INFO = \"org.fdroid.fdroid.data.extra.PACKAGE_INFO\";\n\n \/**\n * This is for notifing the users of this {@link android.content.ContentProvider}\n * that the contents has changed. Since {@link Intent}s can come in slow\n * or fast, and this can trigger a lot of UI updates, the actual\n * notifications are rate limited to one per second.\n *\/\n private PublishSubject notifyEvents;\n\n public InstalledAppProviderService() {\n super(\"InstalledAppProviderService\");\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n notifyEvents = PublishSubject.create();\n notifyEvents.debounce(1, TimeUnit.SECONDS)\n .subscribeOn(Schedulers.newThread())\n .subscribe(new Action1() {\n @Override\n public void call(Void voidArg) {\n Utils.debugLog(TAG, \"Notifying content providers (so they can update the relevant views).\");\n getContentResolver().notifyChange(AppProvider.getContentUri(), null);\n getContentResolver().notifyChange(ApkProvider.getContentUri(), null);\n }\n });\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, PackageInfo packageInfo) {\n insert(context, Utils.getPackageUri(packageInfo.packageName), packageInfo);\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, Uri uri) {\n insert(context, uri, null);\n }\n\n private static void insert(Context context, Uri uri, PackageInfo packageInfo) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_INSERT);\n intent.setData(uri);\n intent.putExtra(EXTRA_PACKAGE_INFO, packageInfo);\n context.startService(intent);\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, String packageName) {\n delete(context, Utils.getPackageUri(packageName));\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, Uri uri) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_DELETE);\n intent.setData(uri);\n context.startService(intent);\n }\n\n \/**\n * Make sure that {@link InstalledAppProvider}, our database of installed apps,\n * is in sync with what the {@link PackageManager} tells us is installed. Once\n * completed, the relevant {@link android.content.ContentProvider}s will be\n * notified of any changes to installed statuses.\n *

\n * The installed app cache could get out of sync, e.g. if F-Droid crashed\/ or\n * ran out of battery half way through responding to {@link Intent#ACTION_PACKAGE_ADDED}.\n * This method returns immediately, and will continue to work in an\n * {@link IntentService}. It doesn't really matter where we put this in the\n * bootstrap process, because it runs in its own thread, at the lowest priority:\n * {@link Process#THREAD_PRIORITY_LOWEST}.\n *

\n * APKs installed in {@code \/system} will often have zeroed out timestamps, like\n * 2008-01-01 (ziptime) or 2009-01-01. So instead anything older than 2010 every\n * time since we have no way to know whether an APK wasn't changed as part of an\n * OTA update. An OTA update could change the APK without changing the\n * {@link PackageInfo#versionCode} or {@link PackageInfo#lastUpdateTime}.\n *\n * @see issue #819<\/a>\n *\/\n public static void compareToPackageManager(Context context) {\n Map cachedInfo = InstalledAppProvider.Helper.all(context);\n\n List packageInfoList = context.getPackageManager()\n .getInstalledPackages(PackageManager.GET_SIGNATURES);\n for (PackageInfo packageInfo : packageInfoList) {\n if (cachedInfo.containsKey(packageInfo.packageName)) {\n if (packageInfo.lastUpdateTime < 1262300400000L \/\/ 2010-01-01 00:00\n || packageInfo.lastUpdateTime > cachedInfo.get(packageInfo.packageName)) {\n insert(context, packageInfo);\n }\n cachedInfo.remove(packageInfo.packageName);\n } else {\n insert(context, packageInfo);\n }\n }\n\n for (String packageName : cachedInfo.keySet()) {\n delete(context, packageName);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n if (intent == null) {\n return;\n }\n\n String packageName = intent.getData().getSchemeSpecificPart();\n final String action = intent.getAction();\n if (ACTION_INSERT.equals(action)) {\n PackageInfo packageInfo = getPackageInfo(intent, packageName);\n if (packageInfo != null) {\n File apk = new File(packageInfo.applicationInfo.publicSourceDir);\n if (apk.isDirectory()) {\n FilenameFilter filter = new FilenameFilter() {\n @Override\n public boolean accept(File dir, String name) {\n return name.endsWith(\".apk\");\n }\n };\n File[] files = apk.listFiles(filter);\n if (files == null) {\n String msg = packageName + \" sourceDir has no APKs: \"\n + apk.getAbsolutePath();\n Utils.debugLog(TAG, msg);\n ACRA.getErrorReporter().handleException(new IllegalArgumentException(msg), false);\n return;\n }\n apk = files[0];\n }\n if (apk.exists() && apk.canRead()) {\n try {\n String hashType = \"sha256\";\n String hash = Utils.getBinaryHash(apk, hashType);\n insertAppIntoDb(this, packageInfo, hashType, hash);\n } catch (IllegalArgumentException e) {\n Utils.debugLog(TAG, e.getMessage());\n ACRA.getErrorReporter().handleException(e, false);\n return;\n }\n }\n }\n } else if (ACTION_DELETE.equals(action)) {\n deleteAppFromDb(this, packageName);\n }\n notifyEvents.onNext(null);\n }\n\n \/**\n * This class will either have received an intent from the {@link InstalledAppProviderService}\n * itself, while iterating over installed apps, or from a {@link Intent#ACTION_PACKAGE_ADDED}\n * broadcast. In the first case, it will already have a {@link PackageInfo} for us. However if\n * it is from the later case, we'll need to query the {@link PackageManager} ourselves to get\n * this info.\n *

\n * Can still return null, as there is potentially race conditions to do with uninstalling apps\n * such that querying the {@link PackageManager} for a given package may throw an exception.\n *\/\n @Nullable\n private PackageInfo getPackageInfo(Intent intent, String packageName) {\n PackageInfo packageInfo = intent.getParcelableExtra(EXTRA_PACKAGE_INFO);\n if (packageInfo != null) {\n return packageInfo;\n }\n\n try {\n return getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n \/**\n * @param hash Although the has could be calculated within this function, it is helpful to inject\n * the hash so as to be able to use this method during testing. Otherwise, the\n * hashing method will try to hash a non-existent .apk file and try to insert NULL\n * into the database when under test.\n *\/\n static void insertAppIntoDb(Context context, PackageInfo packageInfo, String hashType, String hash) {\n Uri uri = InstalledAppProvider.getContentUri();\n ContentValues contentValues = new ContentValues();\n contentValues.put(InstalledAppTable.Cols.PACKAGE_NAME, packageInfo.packageName);\n contentValues.put(InstalledAppTable.Cols.VERSION_CODE, packageInfo.versionCode);\n contentValues.put(InstalledAppTable.Cols.VERSION_NAME, packageInfo.versionName);\n contentValues.put(InstalledAppTable.Cols.APPLICATION_LABEL,\n InstalledAppProvider.getApplicationLabel(context, packageInfo.packageName));\n contentValues.put(InstalledAppTable.Cols.SIGNATURE, getPackageSig(packageInfo));\n contentValues.put(InstalledAppTable.Cols.LAST_UPDATE_TIME, packageInfo.lastUpdateTime);\n\n contentValues.put(InstalledAppTable.Cols.HASH_TYPE, hashType);\n contentValues.put(InstalledAppTable.Cols.HASH, hash);\n\n context.getContentResolver().insert(uri, contentValues);\n }\n\n static void deleteAppFromDb(Context context, String packageName) {\n Uri uri = InstalledAppProvider.getAppUri(packageName);\n context.getContentResolver().delete(uri, null, null);\n }\n\n private static String getPackageSig(PackageInfo info) {\n if (info == null || info.signatures == null || info.signatures.length < 1) {\n return \"\";\n }\n Signature sig = info.signatures[0];\n String sigHash = \"\";\n try {\n Hasher hash = new Hasher(\"MD5\", sig.toCharsString().getBytes());\n sigHash = hash.getHash();\n } catch (NoSuchAlgorithmException e) {\n \/\/ ignore\n }\n return sigHash;\n }\n\n}","target_code":"package org.fdroid.fdroid.data;\n\nimport android.app.IntentService;\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.Signature;\nimport android.net.Uri;\nimport android.os.Process;\nimport android.support.annotation.Nullable;\n\nimport org.acra.ACRA;\nimport org.fdroid.fdroid.Hasher;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Schema.InstalledAppTable;\n\nimport java.io.File;\nimport java.io.FilenameFilter;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.List;\nimport java.util.Map;\n\nimport rx.functions.Action1;\nimport rx.schedulers.Schedulers;\nimport rx.subjects.PublishSubject;\n\n\/**\n * Handles all updates to {@link InstalledAppProvider}, whether checking the contents\n * versus what Android says is installed, or processing {@link Intent}s that come\n * from {@link android.content.BroadcastReceiver}s for {@link Intent#ACTION_PACKAGE_ADDED}\n * and {@link Intent#ACTION_PACKAGE_REMOVED}\n * \n * Since {@link android.content.ContentProvider#insert(Uri, ContentValues)} does not check\n * for duplicate records, it is entirely the job of this service to ensure that it is not\n * inserting duplicate versions of the same installed APK. On that note,\n * {@link #insertAppIntoDb(Context, PackageInfo, String, String)} and\n * {@link #deleteAppFromDb(Context, String)} are both static methods to enable easy testing\n * of this stuff.\n *\/\npublic class InstalledAppProviderService extends IntentService {\n private static final String TAG = \"InstalledAppProviderSer\";\n\n private static final String ACTION_INSERT = \"org.fdroid.fdroid.data.action.INSERT\";\n private static final String ACTION_DELETE = \"org.fdroid.fdroid.data.action.DELETE\";\n\n private static final String EXTRA_PACKAGE_INFO = \"org.fdroid.fdroid.data.extra.PACKAGE_INFO\";\n\n \/**\n * This is for notifing the users of this {@link android.content.ContentProvider}\n * that the contents has changed. Since {@link Intent}s can come in slow\n * or fast, and this can trigger a lot of UI updates, the actual\n * notifications are rate limited to one per second.\n *\/\n private PublishSubject notifyEvents;\n\n public InstalledAppProviderService() {\n super(\"InstalledAppProviderService\");\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n notifyEvents = PublishSubject.create();\n notifyEvents\n .subscribeOn(Schedulers.newThread())\n .subscribe(new Action1() {\n @Override\n public void call(Void voidArg) {\n Utils.debugLog(TAG, \"Notifying content providers (so they can update the relevant views).\");\n getContentResolver().notifyChange(AppProvider.getContentUri(), null);\n getContentResolver().notifyChange(ApkProvider.getContentUri(), null);\n }\n });\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, PackageInfo packageInfo) {\n insert(context, Utils.getPackageUri(packageInfo.packageName), packageInfo);\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, Uri uri) {\n insert(context, uri, null);\n }\n\n private static void insert(Context context, Uri uri, PackageInfo packageInfo) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_INSERT);\n intent.setData(uri);\n intent.putExtra(EXTRA_PACKAGE_INFO, packageInfo);\n context.startService(intent);\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, String packageName) {\n delete(context, Utils.getPackageUri(packageName));\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, Uri uri) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_DELETE);\n intent.setData(uri);\n context.startService(intent);\n }\n\n \/**\n * Make sure that {@link InstalledAppProvider}, our database of installed apps,\n * is in sync with what the {@link PackageManager} tells us is installed. Once\n * completed, the relevant {@link android.content.ContentProvider}s will be\n * notified of any changes to installed statuses.\n *

\n * The installed app cache could get out of sync, e.g. if F-Droid crashed\/ or\n * ran out of battery half way through responding to {@link Intent#ACTION_PACKAGE_ADDED}.\n * This method returns immediately, and will continue to work in an\n * {@link IntentService}. It doesn't really matter where we put this in the\n * bootstrap process, because it runs in its own thread, at the lowest priority:\n * {@link Process#THREAD_PRIORITY_LOWEST}.\n *

\n * APKs installed in {@code \/system} will often have zeroed out timestamps, like\n * 2008-01-01 (ziptime) or 2009-01-01. So instead anything older than 2010 every\n * time since we have no way to know whether an APK wasn't changed as part of an\n * OTA update. An OTA update could change the APK without changing the\n * {@link PackageInfo#versionCode} or {@link PackageInfo#lastUpdateTime}.\n *\n * @see issue #819<\/a>\n *\/\n public static void compareToPackageManager(Context context) {\n Map cachedInfo = InstalledAppProvider.Helper.all(context);\n\n List packageInfoList = context.getPackageManager()\n .getInstalledPackages(PackageManager.GET_SIGNATURES);\n for (PackageInfo packageInfo : packageInfoList) {\n if (cachedInfo.containsKey(packageInfo.packageName)) {\n if (packageInfo.lastUpdateTime < 1262300400000L \/\/ 2010-01-01 00:00\n || packageInfo.lastUpdateTime > cachedInfo.get(packageInfo.packageName)) {\n insert(context, packageInfo);\n }\n cachedInfo.remove(packageInfo.packageName);\n } else {\n insert(context, packageInfo);\n }\n }\n\n for (String packageName : cachedInfo.keySet()) {\n delete(context, packageName);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n if (intent == null) {\n return;\n }\n\n String packageName = intent.getData().getSchemeSpecificPart();\n final String action = intent.getAction();\n if (ACTION_INSERT.equals(action)) {\n PackageInfo packageInfo = getPackageInfo(intent, packageName);\n if (packageInfo != null) {\n File apk = new File(packageInfo.applicationInfo.publicSourceDir);\n if (apk.isDirectory()) {\n FilenameFilter filter = new FilenameFilter() {\n @Override\n public boolean accept(File dir, String name) {\n return name.endsWith(\".apk\");\n }\n };\n File[] files = apk.listFiles(filter);\n if (files == null) {\n String msg = packageName + \" sourceDir has no APKs: \"\n + apk.getAbsolutePath();\n Utils.debugLog(TAG, msg);\n ACRA.getErrorReporter().handleException(new IllegalArgumentException(msg), false);\n return;\n }\n apk = files[0];\n }\n if (apk.exists() && apk.canRead()) {\n try {\n String hashType = \"sha256\";\n String hash = Utils.getBinaryHash(apk, hashType);\n insertAppIntoDb(this, packageInfo, hashType, hash);\n } catch (IllegalArgumentException e) {\n Utils.debugLog(TAG, e.getMessage());\n ACRA.getErrorReporter().handleException(e, false);\n return;\n }\n }\n }\n } else if (ACTION_DELETE.equals(action)) {\n deleteAppFromDb(this, packageName);\n }\n notifyEvents.onNext(null);\n }\n\n \/**\n * This class will either have received an intent from the {@link InstalledAppProviderService}\n * itself, while iterating over installed apps, or from a {@link Intent#ACTION_PACKAGE_ADDED}\n * broadcast. In the first case, it will already have a {@link PackageInfo} for us. However if\n * it is from the later case, we'll need to query the {@link PackageManager} ourselves to get\n * this info.\n *

\n * Can still return null, as there is potentially race conditions to do with uninstalling apps\n * such that querying the {@link PackageManager} for a given package may throw an exception.\n *\/\n @Nullable\n private PackageInfo getPackageInfo(Intent intent, String packageName) {\n PackageInfo packageInfo = intent.getParcelableExtra(EXTRA_PACKAGE_INFO);\n if (packageInfo != null) {\n return packageInfo;\n }\n\n try {\n return getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n \/**\n * @param hash Although the has could be calculated within this function, it is helpful to inject\n * the hash so as to be able to use this method during testing. Otherwise, the\n * hashing method will try to hash a non-existent .apk file and try to insert NULL\n * into the database when under test.\n *\/\n static void insertAppIntoDb(Context context, PackageInfo packageInfo, String hashType, String hash) {\n Uri uri = InstalledAppProvider.getContentUri();\n ContentValues contentValues = new ContentValues();\n contentValues.put(InstalledAppTable.Cols.PACKAGE_NAME, packageInfo.packageName);\n contentValues.put(InstalledAppTable.Cols.VERSION_CODE, packageInfo.versionCode);\n contentValues.put(InstalledAppTable.Cols.VERSION_NAME, packageInfo.versionName);\n contentValues.put(InstalledAppTable.Cols.APPLICATION_LABEL,\n InstalledAppProvider.getApplicationLabel(context, packageInfo.packageName));\n contentValues.put(InstalledAppTable.Cols.SIGNATURE, getPackageSig(packageInfo));\n contentValues.put(InstalledAppTable.Cols.LAST_UPDATE_TIME, packageInfo.lastUpdateTime);\n\n contentValues.put(InstalledAppTable.Cols.HASH_TYPE, hashType);\n contentValues.put(InstalledAppTable.Cols.HASH, hash);\n\n context.getContentResolver().insert(uri, contentValues);\n }\n\n static void deleteAppFromDb(Context context, String packageName) {\n Uri uri = InstalledAppProvider.getAppUri(packageName);\n context.getContentResolver().delete(uri, null, null);\n }\n\n private static String getPackageSig(PackageInfo info) {\n if (info == null || info.signatures == null || info.signatures.length < 1) {\n return \"\";\n }\n Signature sig = info.signatures[0];\n String sigHash = \"\";\n try {\n Hasher hash = new Hasher(\"MD5\", sig.toCharsString().getBytes());\n sigHash = hash.getHash();\n } catch (NoSuchAlgorithmException e) {\n \/\/ ignore\n }\n return sigHash;\n }\n\n}","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the frame rate. Write the entire code and no other text.\n```java\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n SearchEngineManager.getInstance().init(this);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n```\n\n### Thought:\nThe onCreate() function performs necessary initializations such as loading certain preferences, and sets up SearchEngineManager instance. However, loading preferences depends on the Search Engine manager, because the default search engine preference uses the search engine manager; we therefore need to ensure that preferences aren't loaded until search engines are loaded, to avoid potential hangup of the application for a fresh install. The following optimized code first initializes the search engine manager and then loads preferences.\n\n### Response:\n ```java\n \/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n SearchEngineManager.getInstance().init(this);\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the frame rate. Write the entire code and no other text:\npackage org.fdroid.fdroid.data;\n\nimport android.app.IntentService;\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.Signature;\nimport android.net.Uri;\nimport android.os.Process;\nimport android.support.annotation.Nullable;\n\nimport org.acra.ACRA;\nimport org.fdroid.fdroid.Hasher;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Schema.InstalledAppTable;\n\nimport java.io.File;\nimport java.io.FilenameFilter;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\n\nimport rx.functions.Action1;\nimport rx.schedulers.Schedulers;\nimport rx.subjects.PublishSubject;\n\n\/**\n * Handles all updates to {@link InstalledAppProvider}, whether checking the contents\n * versus what Android says is installed, or processing {@link Intent}s that come\n * from {@link android.content.BroadcastReceiver}s for {@link Intent#ACTION_PACKAGE_ADDED}\n * and {@link Intent#ACTION_PACKAGE_REMOVED}\n * \n * Since {@link android.content.ContentProvider#insert(Uri, ContentValues)} does not check\n * for duplicate records, it is entirely the job of this service to ensure that it is not\n * inserting duplicate versions of the same installed APK. On that note,\n * {@link #insertAppIntoDb(Context, PackageInfo, String, String)} and\n * {@link #deleteAppFromDb(Context, String)} are both static methods to enable easy testing\n * of this stuff.\n *\/\npublic class InstalledAppProviderService extends IntentService {\n private static final String TAG = \"InstalledAppProviderSer\";\n\n private static final String ACTION_INSERT = \"org.fdroid.fdroid.data.action.INSERT\";\n private static final String ACTION_DELETE = \"org.fdroid.fdroid.data.action.DELETE\";\n\n private static final String EXTRA_PACKAGE_INFO = \"org.fdroid.fdroid.data.extra.PACKAGE_INFO\";\n\n \/**\n * This is for notifing the users of this {@link android.content.ContentProvider}\n * that the contents has changed. Since {@link Intent}s can come in slow\n * or fast, and this can trigger a lot of UI updates, the actual\n * notifications are rate limited to one per second.\n *\/\n private PublishSubject notifyEvents;\n\n public InstalledAppProviderService() {\n super(\"InstalledAppProviderService\");\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n notifyEvents = PublishSubject.create();\n notifyEvents.debounce(1, TimeUnit.SECONDS)\n .subscribeOn(Schedulers.newThread())\n .subscribe(new Action1() {\n @Override\n public void call(Void voidArg) {\n Utils.debugLog(TAG, \"Notifying content providers (so they can update the relevant views).\");\n getContentResolver().notifyChange(AppProvider.getContentUri(), null);\n getContentResolver().notifyChange(ApkProvider.getContentUri(), null);\n }\n });\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, PackageInfo packageInfo) {\n insert(context, Utils.getPackageUri(packageInfo.packageName), packageInfo);\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, Uri uri) {\n insert(context, uri, null);\n }\n\n private static void insert(Context context, Uri uri, PackageInfo packageInfo) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_INSERT);\n intent.setData(uri);\n intent.putExtra(EXTRA_PACKAGE_INFO, packageInfo);\n context.startService(intent);\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, String packageName) {\n delete(context, Utils.getPackageUri(packageName));\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, Uri uri) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_DELETE);\n intent.setData(uri);\n context.startService(intent);\n }\n\n \/**\n * Make sure that {@link InstalledAppProvider}, our database of installed apps,\n * is in sync with what the {@link PackageManager} tells us is installed. Once\n * completed, the relevant {@link android.content.ContentProvider}s will be\n * notified of any changes to installed statuses.\n *

\n * The installed app cache could get out of sync, e.g. if F-Droid crashed\/ or\n * ran out of battery half way through responding to {@link Intent#ACTION_PACKAGE_ADDED}.\n * This method returns immediately, and will continue to work in an\n * {@link IntentService}. It doesn't really matter where we put this in the\n * bootstrap process, because it runs in its own thread, at the lowest priority:\n * {@link Process#THREAD_PRIORITY_LOWEST}.\n *

\n * APKs installed in {@code \/system} will often have zeroed out timestamps, like\n * 2008-01-01 (ziptime) or 2009-01-01. So instead anything older than 2010 every\n * time since we have no way to know whether an APK wasn't changed as part of an\n * OTA update. An OTA update could change the APK without changing the\n * {@link PackageInfo#versionCode} or {@link PackageInfo#lastUpdateTime}.\n *\n * @see issue #819<\/a>\n *\/\n public static void compareToPackageManager(Context context) {\n Map cachedInfo = InstalledAppProvider.Helper.all(context);\n\n List packageInfoList = context.getPackageManager()\n .getInstalledPackages(PackageManager.GET_SIGNATURES);\n for (PackageInfo packageInfo : packageInfoList) {\n if (cachedInfo.containsKey(packageInfo.packageName)) {\n if (packageInfo.lastUpdateTime < 1262300400000L \/\/ 2010-01-01 00:00\n || packageInfo.lastUpdateTime > cachedInfo.get(packageInfo.packageName)) {\n insert(context, packageInfo);\n }\n cachedInfo.remove(packageInfo.packageName);\n } else {\n insert(context, packageInfo);\n }\n }\n\n for (String packageName : cachedInfo.keySet()) {\n delete(context, packageName);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n if (intent == null) {\n return;\n }\n\n String packageName = intent.getData().getSchemeSpecificPart();\n final String action = intent.getAction();\n if (ACTION_INSERT.equals(action)) {\n PackageInfo packageInfo = getPackageInfo(intent, packageName);\n if (packageInfo != null) {\n File apk = new File(packageInfo.applicationInfo.publicSourceDir);\n if (apk.isDirectory()) {\n FilenameFilter filter = new FilenameFilter() {\n @Override\n public boolean accept(File dir, String name) {\n return name.endsWith(\".apk\");\n }\n };\n File[] files = apk.listFiles(filter);\n if (files == null) {\n String msg = packageName + \" sourceDir has no APKs: \"\n + apk.getAbsolutePath();\n Utils.debugLog(TAG, msg);\n ACRA.getErrorReporter().handleException(new IllegalArgumentException(msg), false);\n return;\n }\n apk = files[0];\n }\n if (apk.exists() && apk.canRead()) {\n try {\n String hashType = \"sha256\";\n String hash = Utils.getBinaryHash(apk, hashType);\n insertAppIntoDb(this, packageInfo, hashType, hash);\n } catch (IllegalArgumentException e) {\n Utils.debugLog(TAG, e.getMessage());\n ACRA.getErrorReporter().handleException(e, false);\n return;\n }\n }\n }\n } else if (ACTION_DELETE.equals(action)) {\n deleteAppFromDb(this, packageName);\n }\n notifyEvents.onNext(null);\n }\n\n \/**\n * This class will either have received an intent from the {@link InstalledAppProviderService}\n * itself, while iterating over installed apps, or from a {@link Intent#ACTION_PACKAGE_ADDED}\n * broadcast. In the first case, it will already have a {@link PackageInfo} for us. However if\n * it is from the later case, we'll need to query the {@link PackageManager} ourselves to get\n * this info.\n *

\n * Can still return null, as there is potentially race conditions to do with uninstalling apps\n * such that querying the {@link PackageManager} for a given package may throw an exception.\n *\/\n @Nullable\n private PackageInfo getPackageInfo(Intent intent, String packageName) {\n PackageInfo packageInfo = intent.getParcelableExtra(EXTRA_PACKAGE_INFO);\n if (packageInfo != null) {\n return packageInfo;\n }\n\n try {\n return getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n \/**\n * @param hash Although the has could be calculated within this function, it is helpful to inject\n * the hash so as to be able to use this method during testing. Otherwise, the\n * hashing method will try to hash a non-existent .apk file and try to insert NULL\n * into the database when under test.\n *\/\n static void insertAppIntoDb(Context context, PackageInfo packageInfo, String hashType, String hash) {\n Uri uri = InstalledAppProvider.getContentUri();\n ContentValues contentValues = new ContentValues();\n contentValues.put(InstalledAppTable.Cols.PACKAGE_NAME, packageInfo.packageName);\n contentValues.put(InstalledAppTable.Cols.VERSION_CODE, packageInfo.versionCode);\n contentValues.put(InstalledAppTable.Cols.VERSION_NAME, packageInfo.versionName);\n contentValues.put(InstalledAppTable.Cols.APPLICATION_LABEL,\n InstalledAppProvider.getApplicationLabel(context, packageInfo.packageName));\n contentValues.put(InstalledAppTable.Cols.SIGNATURE, getPackageSig(packageInfo));\n contentValues.put(InstalledAppTable.Cols.LAST_UPDATE_TIME, packageInfo.lastUpdateTime);\n\n contentValues.put(InstalledAppTable.Cols.HASH_TYPE, hashType);\n contentValues.put(InstalledAppTable.Cols.HASH, hash);\n\n context.getContentResolver().insert(uri, contentValues);\n }\n\n static void deleteAppFromDb(Context context, String packageName) {\n Uri uri = InstalledAppProvider.getAppUri(packageName);\n context.getContentResolver().delete(uri, null, null);\n }\n\n private static String getPackageSig(PackageInfo info) {\n if (info == null || info.signatures == null || info.signatures.length < 1) {\n return \"\";\n }\n Signature sig = info.signatures[0];\n String sigHash = \"\";\n try {\n Hasher hash = new Hasher(\"MD5\", sig.toCharsString().getBytes());\n sigHash = hash.getHash();\n } catch (NoSuchAlgorithmException e) {\n \/\/ ignore\n }\n return sigHash;\n }\n\n}\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the frame rate. Write the entire code and no other text.\n```java\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n SearchEngineManager.getInstance().init(this);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n```\n### Response:\n ```java\n \/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n SearchEngineManager.getInstance().init(this);\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the frame rate. Write the entire code and no other text:\npackage org.fdroid.fdroid.data;\n\nimport android.app.IntentService;\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.Signature;\nimport android.net.Uri;\nimport android.os.Process;\nimport android.support.annotation.Nullable;\n\nimport org.acra.ACRA;\nimport org.fdroid.fdroid.Hasher;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Schema.InstalledAppTable;\n\nimport java.io.File;\nimport java.io.FilenameFilter;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\n\nimport rx.functions.Action1;\nimport rx.schedulers.Schedulers;\nimport rx.subjects.PublishSubject;\n\n\/**\n * Handles all updates to {@link InstalledAppProvider}, whether checking the contents\n * versus what Android says is installed, or processing {@link Intent}s that come\n * from {@link android.content.BroadcastReceiver}s for {@link Intent#ACTION_PACKAGE_ADDED}\n * and {@link Intent#ACTION_PACKAGE_REMOVED}\n * \n * Since {@link android.content.ContentProvider#insert(Uri, ContentValues)} does not check\n * for duplicate records, it is entirely the job of this service to ensure that it is not\n * inserting duplicate versions of the same installed APK. On that note,\n * {@link #insertAppIntoDb(Context, PackageInfo, String, String)} and\n * {@link #deleteAppFromDb(Context, String)} are both static methods to enable easy testing\n * of this stuff.\n *\/\npublic class InstalledAppProviderService extends IntentService {\n private static final String TAG = \"InstalledAppProviderSer\";\n\n private static final String ACTION_INSERT = \"org.fdroid.fdroid.data.action.INSERT\";\n private static final String ACTION_DELETE = \"org.fdroid.fdroid.data.action.DELETE\";\n\n private static final String EXTRA_PACKAGE_INFO = \"org.fdroid.fdroid.data.extra.PACKAGE_INFO\";\n\n \/**\n * This is for notifing the users of this {@link android.content.ContentProvider}\n * that the contents has changed. Since {@link Intent}s can come in slow\n * or fast, and this can trigger a lot of UI updates, the actual\n * notifications are rate limited to one per second.\n *\/\n private PublishSubject notifyEvents;\n\n public InstalledAppProviderService() {\n super(\"InstalledAppProviderService\");\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n notifyEvents = PublishSubject.create();\n notifyEvents.debounce(1, TimeUnit.SECONDS)\n .subscribeOn(Schedulers.newThread())\n .subscribe(new Action1() {\n @Override\n public void call(Void voidArg) {\n Utils.debugLog(TAG, \"Notifying content providers (so they can update the relevant views).\");\n getContentResolver().notifyChange(AppProvider.getContentUri(), null);\n getContentResolver().notifyChange(ApkProvider.getContentUri(), null);\n }\n });\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, PackageInfo packageInfo) {\n insert(context, Utils.getPackageUri(packageInfo.packageName), packageInfo);\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, Uri uri) {\n insert(context, uri, null);\n }\n\n private static void insert(Context context, Uri uri, PackageInfo packageInfo) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_INSERT);\n intent.setData(uri);\n intent.putExtra(EXTRA_PACKAGE_INFO, packageInfo);\n context.startService(intent);\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, String packageName) {\n delete(context, Utils.getPackageUri(packageName));\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, Uri uri) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_DELETE);\n intent.setData(uri);\n context.startService(intent);\n }\n\n \/**\n * Make sure that {@link InstalledAppProvider}, our database of installed apps,\n * is in sync with what the {@link PackageManager} tells us is installed. Once\n * completed, the relevant {@link android.content.ContentProvider}s will be\n * notified of any changes to installed statuses.\n *

\n * The installed app cache could get out of sync, e.g. if F-Droid crashed\/ or\n * ran out of battery half way through responding to {@link Intent#ACTION_PACKAGE_ADDED}.\n * This method returns immediately, and will continue to work in an\n * {@link IntentService}. It doesn't really matter where we put this in the\n * bootstrap process, because it runs in its own thread, at the lowest priority:\n * {@link Process#THREAD_PRIORITY_LOWEST}.\n *

\n * APKs installed in {@code \/system} will often have zeroed out timestamps, like\n * 2008-01-01 (ziptime) or 2009-01-01. So instead anything older than 2010 every\n * time since we have no way to know whether an APK wasn't changed as part of an\n * OTA update. An OTA update could change the APK without changing the\n * {@link PackageInfo#versionCode} or {@link PackageInfo#lastUpdateTime}.\n *\n * @see issue #819<\/a>\n *\/\n public static void compareToPackageManager(Context context) {\n Map cachedInfo = InstalledAppProvider.Helper.all(context);\n\n List packageInfoList = context.getPackageManager()\n .getInstalledPackages(PackageManager.GET_SIGNATURES);\n for (PackageInfo packageInfo : packageInfoList) {\n if (cachedInfo.containsKey(packageInfo.packageName)) {\n if (packageInfo.lastUpdateTime < 1262300400000L \/\/ 2010-01-01 00:00\n || packageInfo.lastUpdateTime > cachedInfo.get(packageInfo.packageName)) {\n insert(context, packageInfo);\n }\n cachedInfo.remove(packageInfo.packageName);\n } else {\n insert(context, packageInfo);\n }\n }\n\n for (String packageName : cachedInfo.keySet()) {\n delete(context, packageName);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n if (intent == null) {\n return;\n }\n\n String packageName = intent.getData().getSchemeSpecificPart();\n final String action = intent.getAction();\n if (ACTION_INSERT.equals(action)) {\n PackageInfo packageInfo = getPackageInfo(intent, packageName);\n if (packageInfo != null) {\n File apk = new File(packageInfo.applicationInfo.publicSourceDir);\n if (apk.isDirectory()) {\n FilenameFilter filter = new FilenameFilter() {\n @Override\n public boolean accept(File dir, String name) {\n return name.endsWith(\".apk\");\n }\n };\n File[] files = apk.listFiles(filter);\n if (files == null) {\n String msg = packageName + \" sourceDir has no APKs: \"\n + apk.getAbsolutePath();\n Utils.debugLog(TAG, msg);\n ACRA.getErrorReporter().handleException(new IllegalArgumentException(msg), false);\n return;\n }\n apk = files[0];\n }\n if (apk.exists() && apk.canRead()) {\n try {\n String hashType = \"sha256\";\n String hash = Utils.getBinaryHash(apk, hashType);\n insertAppIntoDb(this, packageInfo, hashType, hash);\n } catch (IllegalArgumentException e) {\n Utils.debugLog(TAG, e.getMessage());\n ACRA.getErrorReporter().handleException(e, false);\n return;\n }\n }\n }\n } else if (ACTION_DELETE.equals(action)) {\n deleteAppFromDb(this, packageName);\n }\n notifyEvents.onNext(null);\n }\n\n \/**\n * This class will either have received an intent from the {@link InstalledAppProviderService}\n * itself, while iterating over installed apps, or from a {@link Intent#ACTION_PACKAGE_ADDED}\n * broadcast. In the first case, it will already have a {@link PackageInfo} for us. However if\n * it is from the later case, we'll need to query the {@link PackageManager} ourselves to get\n * this info.\n *

\n * Can still return null, as there is potentially race conditions to do with uninstalling apps\n * such that querying the {@link PackageManager} for a given package may throw an exception.\n *\/\n @Nullable\n private PackageInfo getPackageInfo(Intent intent, String packageName) {\n PackageInfo packageInfo = intent.getParcelableExtra(EXTRA_PACKAGE_INFO);\n if (packageInfo != null) {\n return packageInfo;\n }\n\n try {\n return getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n \/**\n * @param hash Although the has could be calculated within this function, it is helpful to inject\n * the hash so as to be able to use this method during testing. Otherwise, the\n * hashing method will try to hash a non-existent .apk file and try to insert NULL\n * into the database when under test.\n *\/\n static void insertAppIntoDb(Context context, PackageInfo packageInfo, String hashType, String hash) {\n Uri uri = InstalledAppProvider.getContentUri();\n ContentValues contentValues = new ContentValues();\n contentValues.put(InstalledAppTable.Cols.PACKAGE_NAME, packageInfo.packageName);\n contentValues.put(InstalledAppTable.Cols.VERSION_CODE, packageInfo.versionCode);\n contentValues.put(InstalledAppTable.Cols.VERSION_NAME, packageInfo.versionName);\n contentValues.put(InstalledAppTable.Cols.APPLICATION_LABEL,\n InstalledAppProvider.getApplicationLabel(context, packageInfo.packageName));\n contentValues.put(InstalledAppTable.Cols.SIGNATURE, getPackageSig(packageInfo));\n contentValues.put(InstalledAppTable.Cols.LAST_UPDATE_TIME, packageInfo.lastUpdateTime);\n\n contentValues.put(InstalledAppTable.Cols.HASH_TYPE, hashType);\n contentValues.put(InstalledAppTable.Cols.HASH, hash);\n\n context.getContentResolver().insert(uri, contentValues);\n }\n\n static void deleteAppFromDb(Context context, String packageName) {\n Uri uri = InstalledAppProvider.getAppUri(packageName);\n context.getContentResolver().delete(uri, null, null);\n }\n\n private static String getPackageSig(PackageInfo info) {\n if (info == null || info.signatures == null || info.signatures.length < 1) {\n return \"\";\n }\n Signature sig = info.signatures[0];\n String sigHash = \"\";\n try {\n Hasher hash = new Hasher(\"MD5\", sig.toCharsString().getBytes());\n sigHash = hash.getHash();\n } catch (NoSuchAlgorithmException e) {\n \/\/ ignore\n }\n return sigHash;\n }\n\n}\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the frame rate. Write the entire code and no other text:\npackage org.fdroid.fdroid.data;\n\nimport android.app.IntentService;\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.Signature;\nimport android.net.Uri;\nimport android.os.Process;\nimport android.support.annotation.Nullable;\n\nimport org.acra.ACRA;\nimport org.fdroid.fdroid.Hasher;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Schema.InstalledAppTable;\n\nimport java.io.File;\nimport java.io.FilenameFilter;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\n\nimport rx.functions.Action1;\nimport rx.schedulers.Schedulers;\nimport rx.subjects.PublishSubject;\n\n\/**\n * Handles all updates to {@link InstalledAppProvider}, whether checking the contents\n * versus what Android says is installed, or processing {@link Intent}s that come\n * from {@link android.content.BroadcastReceiver}s for {@link Intent#ACTION_PACKAGE_ADDED}\n * and {@link Intent#ACTION_PACKAGE_REMOVED}\n * \n * Since {@link android.content.ContentProvider#insert(Uri, ContentValues)} does not check\n * for duplicate records, it is entirely the job of this service to ensure that it is not\n * inserting duplicate versions of the same installed APK. On that note,\n * {@link #insertAppIntoDb(Context, PackageInfo, String, String)} and\n * {@link #deleteAppFromDb(Context, String)} are both static methods to enable easy testing\n * of this stuff.\n *\/\npublic class InstalledAppProviderService extends IntentService {\n private static final String TAG = \"InstalledAppProviderSer\";\n\n private static final String ACTION_INSERT = \"org.fdroid.fdroid.data.action.INSERT\";\n private static final String ACTION_DELETE = \"org.fdroid.fdroid.data.action.DELETE\";\n\n private static final String EXTRA_PACKAGE_INFO = \"org.fdroid.fdroid.data.extra.PACKAGE_INFO\";\n\n \/**\n * This is for notifing the users of this {@link android.content.ContentProvider}\n * that the contents has changed. Since {@link Intent}s can come in slow\n * or fast, and this can trigger a lot of UI updates, the actual\n * notifications are rate limited to one per second.\n *\/\n private PublishSubject notifyEvents;\n\n public InstalledAppProviderService() {\n super(\"InstalledAppProviderService\");\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n notifyEvents = PublishSubject.create();\n notifyEvents.debounce(1, TimeUnit.SECONDS)\n .subscribeOn(Schedulers.newThread())\n .subscribe(new Action1() {\n @Override\n public void call(Void voidArg) {\n Utils.debugLog(TAG, \"Notifying content providers (so they can update the relevant views).\");\n getContentResolver().notifyChange(AppProvider.getContentUri(), null);\n getContentResolver().notifyChange(ApkProvider.getContentUri(), null);\n }\n });\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, PackageInfo packageInfo) {\n insert(context, Utils.getPackageUri(packageInfo.packageName), packageInfo);\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, Uri uri) {\n insert(context, uri, null);\n }\n\n private static void insert(Context context, Uri uri, PackageInfo packageInfo) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_INSERT);\n intent.setData(uri);\n intent.putExtra(EXTRA_PACKAGE_INFO, packageInfo);\n context.startService(intent);\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, String packageName) {\n delete(context, Utils.getPackageUri(packageName));\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, Uri uri) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_DELETE);\n intent.setData(uri);\n context.startService(intent);\n }\n\n \/**\n * Make sure that {@link InstalledAppProvider}, our database of installed apps,\n * is in sync with what the {@link PackageManager} tells us is installed. Once\n * completed, the relevant {@link android.content.ContentProvider}s will be\n * notified of any changes to installed statuses.\n *

\n * The installed app cache could get out of sync, e.g. if F-Droid crashed\/ or\n * ran out of battery half way through responding to {@link Intent#ACTION_PACKAGE_ADDED}.\n * This method returns immediately, and will continue to work in an\n * {@link IntentService}. It doesn't really matter where we put this in the\n * bootstrap process, because it runs in its own thread, at the lowest priority:\n * {@link Process#THREAD_PRIORITY_LOWEST}.\n *

\n * APKs installed in {@code \/system} will often have zeroed out timestamps, like\n * 2008-01-01 (ziptime) or 2009-01-01. So instead anything older than 2010 every\n * time since we have no way to know whether an APK wasn't changed as part of an\n * OTA update. An OTA update could change the APK without changing the\n * {@link PackageInfo#versionCode} or {@link PackageInfo#lastUpdateTime}.\n *\n * @see issue #819<\/a>\n *\/\n public static void compareToPackageManager(Context context) {\n Map cachedInfo = InstalledAppProvider.Helper.all(context);\n\n List packageInfoList = context.getPackageManager()\n .getInstalledPackages(PackageManager.GET_SIGNATURES);\n for (PackageInfo packageInfo : packageInfoList) {\n if (cachedInfo.containsKey(packageInfo.packageName)) {\n if (packageInfo.lastUpdateTime < 1262300400000L \/\/ 2010-01-01 00:00\n || packageInfo.lastUpdateTime > cachedInfo.get(packageInfo.packageName)) {\n insert(context, packageInfo);\n }\n cachedInfo.remove(packageInfo.packageName);\n } else {\n insert(context, packageInfo);\n }\n }\n\n for (String packageName : cachedInfo.keySet()) {\n delete(context, packageName);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n if (intent == null) {\n return;\n }\n\n String packageName = intent.getData().getSchemeSpecificPart();\n final String action = intent.getAction();\n if (ACTION_INSERT.equals(action)) {\n PackageInfo packageInfo = getPackageInfo(intent, packageName);\n if (packageInfo != null) {\n File apk = new File(packageInfo.applicationInfo.publicSourceDir);\n if (apk.isDirectory()) {\n FilenameFilter filter = new FilenameFilter() {\n @Override\n public boolean accept(File dir, String name) {\n return name.endsWith(\".apk\");\n }\n };\n File[] files = apk.listFiles(filter);\n if (files == null) {\n String msg = packageName + \" sourceDir has no APKs: \"\n + apk.getAbsolutePath();\n Utils.debugLog(TAG, msg);\n ACRA.getErrorReporter().handleException(new IllegalArgumentException(msg), false);\n return;\n }\n apk = files[0];\n }\n if (apk.exists() && apk.canRead()) {\n try {\n String hashType = \"sha256\";\n String hash = Utils.getBinaryHash(apk, hashType);\n insertAppIntoDb(this, packageInfo, hashType, hash);\n } catch (IllegalArgumentException e) {\n Utils.debugLog(TAG, e.getMessage());\n ACRA.getErrorReporter().handleException(e, false);\n return;\n }\n }\n }\n } else if (ACTION_DELETE.equals(action)) {\n deleteAppFromDb(this, packageName);\n }\n notifyEvents.onNext(null);\n }\n\n \/**\n * This class will either have received an intent from the {@link InstalledAppProviderService}\n * itself, while iterating over installed apps, or from a {@link Intent#ACTION_PACKAGE_ADDED}\n * broadcast. In the first case, it will already have a {@link PackageInfo} for us. However if\n * it is from the later case, we'll need to query the {@link PackageManager} ourselves to get\n * this info.\n *

\n * Can still return null, as there is potentially race conditions to do with uninstalling apps\n * such that querying the {@link PackageManager} for a given package may throw an exception.\n *\/\n @Nullable\n private PackageInfo getPackageInfo(Intent intent, String packageName) {\n PackageInfo packageInfo = intent.getParcelableExtra(EXTRA_PACKAGE_INFO);\n if (packageInfo != null) {\n return packageInfo;\n }\n\n try {\n return getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n \/**\n * @param hash Although the has could be calculated within this function, it is helpful to inject\n * the hash so as to be able to use this method during testing. Otherwise, the\n * hashing method will try to hash a non-existent .apk file and try to insert NULL\n * into the database when under test.\n *\/\n static void insertAppIntoDb(Context context, PackageInfo packageInfo, String hashType, String hash) {\n Uri uri = InstalledAppProvider.getContentUri();\n ContentValues contentValues = new ContentValues();\n contentValues.put(InstalledAppTable.Cols.PACKAGE_NAME, packageInfo.packageName);\n contentValues.put(InstalledAppTable.Cols.VERSION_CODE, packageInfo.versionCode);\n contentValues.put(InstalledAppTable.Cols.VERSION_NAME, packageInfo.versionName);\n contentValues.put(InstalledAppTable.Cols.APPLICATION_LABEL,\n InstalledAppProvider.getApplicationLabel(context, packageInfo.packageName));\n contentValues.put(InstalledAppTable.Cols.SIGNATURE, getPackageSig(packageInfo));\n contentValues.put(InstalledAppTable.Cols.LAST_UPDATE_TIME, packageInfo.lastUpdateTime);\n\n contentValues.put(InstalledAppTable.Cols.HASH_TYPE, hashType);\n contentValues.put(InstalledAppTable.Cols.HASH, hash);\n\n context.getContentResolver().insert(uri, contentValues);\n }\n\n static void deleteAppFromDb(Context context, String packageName) {\n Uri uri = InstalledAppProvider.getAppUri(packageName);\n context.getContentResolver().delete(uri, null, null);\n }\n\n private static String getPackageSig(PackageInfo info) {\n if (info == null || info.signatures == null || info.signatures.length < 1) {\n return \"\";\n }\n Signature sig = info.signatures[0];\n String sigHash = \"\";\n try {\n Hasher hash = new Hasher(\"MD5\", sig.toCharsString().getBytes());\n sigHash = hash.getHash();\n } catch (NoSuchAlgorithmException e) {\n \/\/ ignore\n }\n return sigHash;\n }\n\n}\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nRemove 1 second pause between installing and updating UI of the android application to improve bandwidth usage. Write the entire code and no other text in the response.\n\n### Concepts:\n[-] java.util.concurrent.TimeUnit\n\n### Given program:\n```java\npackage org.fdroid.fdroid.data;\n\nimport android.app.IntentService;\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.Signature;\nimport android.net.Uri;\nimport android.os.Process;\nimport android.support.annotation.Nullable;\n\nimport org.acra.ACRA;\nimport org.fdroid.fdroid.Hasher;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Schema.InstalledAppTable;\n\nimport java.io.File;\nimport java.io.FilenameFilter;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\n\nimport rx.functions.Action1;\nimport rx.schedulers.Schedulers;\nimport rx.subjects.PublishSubject;\n\n\/**\n * Handles all updates to {@link InstalledAppProvider}, whether checking the contents\n * versus what Android says is installed, or processing {@link Intent}s that come\n * from {@link android.content.BroadcastReceiver}s for {@link Intent#ACTION_PACKAGE_ADDED}\n * and {@link Intent#ACTION_PACKAGE_REMOVED}\n * \n * Since {@link android.content.ContentProvider#insert(Uri, ContentValues)} does not check\n * for duplicate records, it is entirely the job of this service to ensure that it is not\n * inserting duplicate versions of the same installed APK. On that note,\n * {@link #insertAppIntoDb(Context, PackageInfo, String, String)} and\n * {@link #deleteAppFromDb(Context, String)} are both static methods to enable easy testing\n * of this stuff.\n *\/\npublic class InstalledAppProviderService extends IntentService {\n private static final String TAG = \"InstalledAppProviderSer\";\n\n private static final String ACTION_INSERT = \"org.fdroid.fdroid.data.action.INSERT\";\n private static final String ACTION_DELETE = \"org.fdroid.fdroid.data.action.DELETE\";\n\n private static final String EXTRA_PACKAGE_INFO = \"org.fdroid.fdroid.data.extra.PACKAGE_INFO\";\n\n \/**\n * This is for notifing the users of this {@link android.content.ContentProvider}\n * that the contents has changed. Since {@link Intent}s can come in slow\n * or fast, and this can trigger a lot of UI updates, the actual\n * notifications are rate limited to one per second.\n *\/\n private PublishSubject notifyEvents;\n\n public InstalledAppProviderService() {\n super(\"InstalledAppProviderService\");\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n notifyEvents = PublishSubject.create();\n notifyEvents.debounce(1, TimeUnit.SECONDS)\n .subscribeOn(Schedulers.newThread())\n .subscribe(new Action1() {\n @Override\n public void call(Void voidArg) {\n Utils.debugLog(TAG, \"Notifying content providers (so they can update the relevant views).\");\n getContentResolver().notifyChange(AppProvider.getContentUri(), null);\n getContentResolver().notifyChange(ApkProvider.getContentUri(), null);\n }\n });\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, PackageInfo packageInfo) {\n insert(context, Utils.getPackageUri(packageInfo.packageName), packageInfo);\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, Uri uri) {\n insert(context, uri, null);\n }\n\n private static void insert(Context context, Uri uri, PackageInfo packageInfo) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_INSERT);\n intent.setData(uri);\n intent.putExtra(EXTRA_PACKAGE_INFO, packageInfo);\n context.startService(intent);\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, String packageName) {\n delete(context, Utils.getPackageUri(packageName));\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, Uri uri) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_DELETE);\n intent.setData(uri);\n context.startService(intent);\n }\n\n \/**\n * Make sure that {@link InstalledAppProvider}, our database of installed apps,\n * is in sync with what the {@link PackageManager} tells us is installed. Once\n * completed, the relevant {@link android.content.ContentProvider}s will be\n * notified of any changes to installed statuses.\n *

\n * The installed app cache could get out of sync, e.g. if F-Droid crashed\/ or\n * ran out of battery half way through responding to {@link Intent#ACTION_PACKAGE_ADDED}.\n * This method returns immediately, and will continue to work in an\n * {@link IntentService}. It doesn't really matter where we put this in the\n * bootstrap process, because it runs in its own thread, at the lowest priority:\n * {@link Process#THREAD_PRIORITY_LOWEST}.\n *

\n * APKs installed in {@code \/system} will often have zeroed out timestamps, like\n * 2008-01-01 (ziptime) or 2009-01-01. So instead anything older than 2010 every\n * time since we have no way to know whether an APK wasn't changed as part of an\n * OTA update. An OTA update could change the APK without changing the\n * {@link PackageInfo#versionCode} or {@link PackageInfo#lastUpdateTime}.\n *\n * @see issue #819<\/a>\n *\/\n public static void compareToPackageManager(Context context) {\n Map cachedInfo = InstalledAppProvider.Helper.all(context);\n\n List packageInfoList = context.getPackageManager()\n .getInstalledPackages(PackageManager.GET_SIGNATURES);\n for (PackageInfo packageInfo : packageInfoList) {\n if (cachedInfo.containsKey(packageInfo.packageName)) {\n if (packageInfo.lastUpdateTime < 1262300400000L \/\/ 2010-01-01 00:00\n || packageInfo.lastUpdateTime > cachedInfo.get(packageInfo.packageName)) {\n insert(context, packageInfo);\n }\n cachedInfo.remove(packageInfo.packageName);\n } else {\n insert(context, packageInfo);\n }\n }\n\n for (String packageName : cachedInfo.keySet()) {\n delete(context, packageName);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n if (intent == null) {\n return;\n }\n\n String packageName = intent.getData().getSchemeSpecificPart();\n final String action = intent.getAction();\n if (ACTION_INSERT.equals(action)) {\n PackageInfo packageInfo = getPackageInfo(intent, packageName);\n if (packageInfo != null) {\n File apk = new File(packageInfo.applicationInfo.publicSourceDir);\n if (apk.isDirectory()) {\n FilenameFilter filter = new FilenameFilter() {\n @Override\n public boolean accept(File dir, String name) {\n return name.endsWith(\".apk\");\n }\n };\n File[] files = apk.listFiles(filter);\n if (files == null) {\n String msg = packageName + \" sourceDir has no APKs: \"\n + apk.getAbsolutePath();\n Utils.debugLog(TAG, msg);\n ACRA.getErrorReporter().handleException(new IllegalArgumentException(msg), false);\n return;\n }\n apk = files[0];\n }\n if (apk.exists() && apk.canRead()) {\n try {\n String hashType = \"sha256\";\n String hash = Utils.getBinaryHash(apk, hashType);\n insertAppIntoDb(this, packageInfo, hashType, hash);\n } catch (IllegalArgumentException e) {\n Utils.debugLog(TAG, e.getMessage());\n ACRA.getErrorReporter().handleException(e, false);\n return;\n }\n }\n }\n } else if (ACTION_DELETE.equals(action)) {\n deleteAppFromDb(this, packageName);\n }\n notifyEvents.onNext(null);\n }\n\n \/**\n * This class will either have received an intent from the {@link InstalledAppProviderService}\n * itself, while iterating over installed apps, or from a {@link Intent#ACTION_PACKAGE_ADDED}\n * broadcast. In the first case, it will already have a {@link PackageInfo} for us. However if\n * it is from the later case, we'll need to query the {@link PackageManager} ourselves to get\n * this info.\n *

\n * Can still return null, as there is potentially race conditions to do with uninstalling apps\n * such that querying the {@link PackageManager} for a given package may throw an exception.\n *\/\n @Nullable\n private PackageInfo getPackageInfo(Intent intent, String packageName) {\n PackageInfo packageInfo = intent.getParcelableExtra(EXTRA_PACKAGE_INFO);\n if (packageInfo != null) {\n return packageInfo;\n }\n\n try {\n return getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n \/**\n * @param hash Although the has could be calculated within this function, it is helpful to inject\n * the hash so as to be able to use this method during testing. Otherwise, the\n * hashing method will try to hash a non-existent .apk file and try to insert NULL\n * into the database when under test.\n *\/\n static void insertAppIntoDb(Context context, PackageInfo packageInfo, String hashType, String hash) {\n Uri uri = InstalledAppProvider.getContentUri();\n ContentValues contentValues = new ContentValues();\n contentValues.put(InstalledAppTable.Cols.PACKAGE_NAME, packageInfo.packageName);\n contentValues.put(InstalledAppTable.Cols.VERSION_CODE, packageInfo.versionCode);\n contentValues.put(InstalledAppTable.Cols.VERSION_NAME, packageInfo.versionName);\n contentValues.put(InstalledAppTable.Cols.APPLICATION_LABEL,\n InstalledAppProvider.getApplicationLabel(context, packageInfo.packageName));\n contentValues.put(InstalledAppTable.Cols.SIGNATURE, getPackageSig(packageInfo));\n contentValues.put(InstalledAppTable.Cols.LAST_UPDATE_TIME, packageInfo.lastUpdateTime);\n\n contentValues.put(InstalledAppTable.Cols.HASH_TYPE, hashType);\n contentValues.put(InstalledAppTable.Cols.HASH, hash);\n\n context.getContentResolver().insert(uri, contentValues);\n }\n\n static void deleteAppFromDb(Context context, String packageName) {\n Uri uri = InstalledAppProvider.getAppUri(packageName);\n context.getContentResolver().delete(uri, null, null);\n }\n\n private static String getPackageSig(PackageInfo info) {\n if (info == null || info.signatures == null || info.signatures.length < 1) {\n return \"\";\n }\n Signature sig = info.signatures[0];\n String sigHash = \"\";\n try {\n Hasher hash = new Hasher(\"MD5\", sig.toCharsString().getBytes());\n sigHash = hash.getHash();\n } catch (NoSuchAlgorithmException e) {\n \/\/ ignore\n }\n return sigHash;\n }\n\n}\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.database.Cursor;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.SparseArray;\nimport android.view.View;\nimport android.view.animation.AnimationUtils;\nimport android.view.animation.LayoutAnimationController;\nimport android.widget.AdapterView;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.db.Database;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.utils.Constants;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\n\npublic abstract class HostActivity extends AppCompatActivity implements HostAsyncResponse {\n\n protected int layout;\n protected ArrayAdapter adapter;\n protected ListView portList;\n protected ArrayList ports = new ArrayList<>();\n protected ProgressDialog scanProgressDialog;\n protected Dialog portRangeDialog;\n private Database db;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(this.layout);\n\n db = new Database(this);\n setupPortsAdapter();\n }\n\n \/**\n * Sets up animations for the activity\n *\/\n protected void setAnimations() {\n LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(this, R.anim.layout_slide_in_bottom);\n portList.setLayoutAnimation(animation);\n }\n\n \/**\n * Sets up the adapter to handle discovered ports\n *\/\n private void setupPortsAdapter() {\n this.portList = (ListView) findViewById(R.id.portList);\n this.adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.port_list_item, ports);\n this.portList.setAdapter(this.adapter);\n this.setAnimations();\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if (this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if (this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Clean up\n *\/\n @Override\n protected void onDestroy() {\n super.onDestroy();\n\n if (db != null) {\n db.close();\n }\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"ports\", ports);\n }\n\n \/**\n * Restore saved data\n *\n * @param savedInstanceState Data from a saved state\n *\/\n public void onRestoreInstanceState(Bundle savedInstanceState) {\n super.onRestoreInstanceState(savedInstanceState);\n\n ports = savedInstanceState.getStringArrayList(\"ports\");\n\n this.setupPortsAdapter();\n }\n\n \/**\n * Event handler for when the port range reset is triggered\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n *\/\n protected void resetPortRangeScanClick(final NumberPicker start, final NumberPicker stop) {\n portRangeDialog.findViewById(R.id.resetPortRangeScan).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n start.setValue(Constants.MIN_PORT_VALUE);\n stop.setValue(Constants.MAX_PORT_VALUE);\n }\n });\n }\n\n \/**\n * Event handler for when the port range scan is finally initiated\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n * @param timeout Socket timeout\n * @param activity Calling activity\n * @param ip IP address\n *\/\n protected void startPortRangeScanClick(final NumberPicker start, final NumberPicker stop, final int timeout, final HostActivity activity, final String ip) {\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n start.clearFocus();\n stop.clearFocus();\n\n int startPort = start.getValue();\n int stopPort = stop.getValue();\n if ((startPort - stopPort > 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n UserPreference.savePortRangeStart(activity, startPort);\n UserPreference.savePortRangeHigh(activity, stopPort);\n\n ports.clear();\n\n scanProgressDialog = new ProgressDialog(activity, R.style.DialogTheme);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n Host.scanPorts(ip, startPort, stopPort, timeout, activity);\n }\n });\n }\n\n \/**\n * Event handler for when an item on the port list is clicked\n *\/\n protected void portListClick(final String ip) {\n this.portList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open certain ports to the browser\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n String item = (String) portList.getItemAtPosition(position);\n if (item == null) {\n return;\n }\n\n Intent intent = null;\n\n if (item.contains(\"80 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip));\n }\n\n if (item.contains(\"443 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"https:\/\/\" + ip));\n }\n\n if (item.contains(\"8080 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip + \":8080\"));\n }\n\n PackageManager packageManager = getPackageManager();\n if (intent != null && packageManager != null) {\n if (packageManager.resolveActivity(intent, 0) != null) {\n startActivity(intent);\n } else {\n Toast.makeText(getApplicationContext(), \"No application found to open this to the browser!\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n });\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n if (scanProgressDialog != null) {\n scanProgressDialog.incrementProgressBy(output);\n }\n }\n });\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(SparseArray output) {\n int scannedPort = output.keyAt(0);\n String item = String.valueOf(scannedPort);\n\n Cursor cursor = db.queryDatabase(\"SELECT name, port FROM ports WHERE port = ?\", new String[]{Integer.toString(scannedPort)});\n\n if (cursor != null) {\n try {\n if (cursor.moveToFirst()) {\n String name = cursor.getString(cursor.getColumnIndex(\"name\"));\n name = (name.isEmpty()) ? \"unknown\" : name;\n item = this.formatOpenPort(output, scannedPort, name, item);\n this.addOpenPort(item);\n }\n } finally {\n cursor.close();\n }\n }\n }\n\n \/**\n * Formats a found open port with its name, description, and associated visualization\n *\n * @param entry Structure holding information about the found open port with its description\n * @param scannedPort The port number\n * @param portName Friendly name for the port\n * @param item Contains the transformed output for the open port\n * @return If all associated data is found a port along with its description, underlying service, and visualization is constructed\n *\/\n private String formatOpenPort(SparseArray entry, int scannedPort, String portName, String item) {\n item = item + \" - \" + portName;\n if (entry.get(scannedPort) != null) {\n item += \" (\" + entry.get(scannedPort) + \")\";\n }\n\n \/\/If the port is in any way related to HTTP then present a nice globe icon next to it via unicode\n if (scannedPort == 80 || scannedPort == 443 || scannedPort == 8080) {\n item += \" \\uD83C\\uDF0E\";\n }\n\n return item;\n }\n\n \/**\n * Adds an open port that was found on a host to the list\n *\n * @param port Port number and description\n *\/\n private void addOpenPort(final String port) {\n setAnimations();\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n synchronized (ports) {\n ports.add(port);\n\n Collections.sort(ports, new Comparator() {\n\n @Override\n public int compare(String lhs, String rhs) {\n int left = Integer.parseInt(lhs.substring(0, lhs.indexOf('-') - 1));\n int right = Integer.parseInt(rhs.substring(0, rhs.indexOf('-') - 1));\n\n return left - right;\n }\n });\n\n adapter.notifyDataSetChanged();\n }\n }\n });\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.database.Cursor;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.SparseArray;\nimport android.view.View;\nimport android.view.animation.AnimationUtils;\nimport android.view.animation.LayoutAnimationController;\nimport android.widget.AdapterView;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.db.Database;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.utils.Constants;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\n\npublic abstract class HostActivity extends AppCompatActivity implements HostAsyncResponse {\n\n protected int layout;\n protected ArrayAdapter adapter;\n protected ListView portList;\n protected ArrayList ports = new ArrayList<>();\n protected ProgressDialog scanProgressDialog;\n protected Dialog portRangeDialog;\n private Database db;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(this.layout);\n\n db = new Database(this);\n setupPortsAdapter();\n }\n\n \/**\n * Sets up animations for the activity\n *\/\n protected void setAnimations() {\n LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(this, R.anim.layout_slide_in_bottom);\n portList.setLayoutAnimation(animation);\n }\n\n \/**\n * Sets up the adapter to handle discovered ports\n *\/\n private void setupPortsAdapter() {\n this.portList = (ListView) findViewById(R.id.portList);\n this.adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.port_list_item, ports);\n this.portList.setAdapter(this.adapter);\n this.setAnimations();\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if (this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if (this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Clean up\n *\/\n @Override\n protected void onDestroy() {\n super.onDestroy();\n\n if (db != null) {\n db.close();\n }\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"ports\", ports);\n }\n\n \/**\n * Restore saved data\n *\n * @param savedInstanceState Data from a saved state\n *\/\n public void onRestoreInstanceState(Bundle savedInstanceState) {\n super.onRestoreInstanceState(savedInstanceState);\n\n ports = savedInstanceState.getStringArrayList(\"ports\");\n\n this.setupPortsAdapter();\n }\n\n \/**\n * Event handler for when the port range reset is triggered\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n *\/\n protected void resetPortRangeScanClick(final NumberPicker start, final NumberPicker stop) {\n portRangeDialog.findViewById(R.id.resetPortRangeScan).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n start.setValue(Constants.MIN_PORT_VALUE);\n stop.setValue(Constants.MAX_PORT_VALUE);\n }\n });\n }\n\n \/**\n * Event handler for when the port range scan is finally initiated\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n * @param timeout Socket timeout\n * @param activity Calling activity\n * @param ip IP address\n *\/\n protected void startPortRangeScanClick(final NumberPicker start, final NumberPicker stop, final int timeout, final HostActivity activity, final String ip) {\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n start.clearFocus();\n stop.clearFocus();\n\n int startPort = start.getValue();\n int stopPort = stop.getValue();\n if ((startPort - stopPort > 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n UserPreference.savePortRangeStart(activity, startPort);\n UserPreference.savePortRangeHigh(activity, stopPort);\n\n ports.clear();\n\n scanProgressDialog = new ProgressDialog(activity, R.style.DialogTheme);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n Host.scanPorts(ip, startPort, stopPort, timeout, activity);\n }\n });\n }\n\n \/**\n * Event handler for when an item on the port list is clicked\n *\/\n protected void portListClick(final String ip) {\n this.portList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open certain ports to the browser\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n String item = (String) portList.getItemAtPosition(position);\n if (item == null) {\n return;\n }\n\n Intent intent = null;\n\n if (item.contains(\"80 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip));\n }\n\n if (item.contains(\"443 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"https:\/\/\" + ip));\n }\n\n if (item.contains(\"8080 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip + \":8080\"));\n }\n\n PackageManager packageManager = getPackageManager();\n if (intent != null && packageManager != null) {\n if (packageManager.resolveActivity(intent, 0) != null) {\n startActivity(intent);\n } else {\n Toast.makeText(getApplicationContext(), \"No application found to open this to the browser!\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n });\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n if (scanProgressDialog != null) {\n scanProgressDialog.incrementProgressBy(output);\n }\n }\n });\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(SparseArray output) {\n int scannedPort = output.keyAt(0);\n String item = String.valueOf(scannedPort);\n\n Cursor cursor = db.queryDatabase(\"SELECT name, port FROM ports WHERE port = ?\", new String[]{Integer.toString(scannedPort)});\n\n if (cursor != null) {\n try {\n if (cursor.moveToFirst()) {\n String name = cursor.getString(cursor.getColumnIndex(\"name\"));\n name = (name.isEmpty()) ? \"unknown\" : name;\n item = this.formatOpenPort(output, scannedPort, name, item);\n this.addOpenPort(item);\n }\n } finally {\n cursor.close();\n }\n }\n }\n\n \/**\n * Formats a found open port with its name, description, and associated visualization\n *\n * @param entry Structure holding information about the found open port with its description\n * @param scannedPort The port number\n * @param portName Friendly name for the port\n * @param item Contains the transformed output for the open port\n * @return If all associated data is found a port along with its description, underlying service, and visualization is constructed\n *\/\n private String formatOpenPort(SparseArray entry, int scannedPort, String portName, String item) {\n item = item + \" - \" + portName;\n if (entry.get(scannedPort) != null) {\n item += \" (\" + entry.get(scannedPort) + \")\";\n }\n\n \/\/If the port is in any way related to HTTP then present a nice globe icon next to it via unicode\n if (scannedPort == 80 || scannedPort == 443 || scannedPort == 8080) {\n item += \" \\uD83C\\uDF0E\";\n }\n\n return item;\n }\n\n \/**\n * Adds an open port that was found on a host to the list\n *\n * @param port Port number and description\n *\/\n private void addOpenPort(final String port) {\n setAnimations();\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n synchronized (ports) {\n ports.add(port);\n\n Collections.sort(ports, new Comparator() {\n\n @Override\n public int compare(String lhs, String rhs) {\n int left = Integer.parseInt(lhs.substring(0, lhs.indexOf(\"-\") - 1));\n int right = Integer.parseInt(rhs.substring(0, rhs.indexOf(\"-\") - 1));\n\n return left - right;\n }\n });\n\n adapter.notifyDataSetChanged();\n }\n }\n });\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.database.Cursor;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.SparseArray;\nimport android.view.View;\nimport android.view.animation.AnimationUtils;\nimport android.view.animation.LayoutAnimationController;\nimport android.widget.AdapterView;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.db.Database;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.utils.Constants;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\n\npublic abstract class HostActivity extends AppCompatActivity implements HostAsyncResponse {\n\n protected int layout;\n protected ArrayAdapter adapter;\n protected ListView portList;\n protected ArrayList ports = new ArrayList<>();\n protected ProgressDialog scanProgressDialog;\n protected Dialog portRangeDialog;\n private Database db;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(this.layout);\n\n db = new Database(this);\n setupPortsAdapter();\n }\n\n \/**\n * Sets up animations for the activity\n *\/\n protected void setAnimations() {\n LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(this, R.anim.layout_slide_in_bottom);\n portList.setLayoutAnimation(animation);\n }\n\n \/**\n * Sets up the adapter to handle discovered ports\n *\/\n private void setupPortsAdapter() {\n this.portList = (ListView) findViewById(R.id.portList);\n this.adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.port_list_item, ports);\n this.portList.setAdapter(this.adapter);\n this.setAnimations();\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if (this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if (this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Clean up\n *\/\n @Override\n protected void onDestroy() {\n super.onDestroy();\n\n if (db != null) {\n db.close();\n }\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"ports\", ports);\n }\n\n \/**\n * Restore saved data\n *\n * @param savedInstanceState Data from a saved state\n *\/\n public void onRestoreInstanceState(Bundle savedInstanceState) {\n super.onRestoreInstanceState(savedInstanceState);\n\n ports = savedInstanceState.getStringArrayList(\"ports\");\n\n this.setupPortsAdapter();\n }\n\n \/**\n * Event handler for when the port range reset is triggered\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n *\/\n protected void resetPortRangeScanClick(final NumberPicker start, final NumberPicker stop) {\n portRangeDialog.findViewById(R.id.resetPortRangeScan).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n start.setValue(Constants.MIN_PORT_VALUE);\n stop.setValue(Constants.MAX_PORT_VALUE);\n }\n });\n }\n\n \/**\n * Event handler for when the port range scan is finally initiated\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n * @param timeout Socket timeout\n * @param activity Calling activity\n * @param ip IP address\n *\/\n protected void startPortRangeScanClick(final NumberPicker start, final NumberPicker stop, final int timeout, final HostActivity activity, final String ip) {\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n start.clearFocus();\n stop.clearFocus();\n\n int startPort = start.getValue();\n int stopPort = stop.getValue();\n if ((startPort - stopPort > 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n UserPreference.savePortRangeStart(activity, startPort);\n UserPreference.savePortRangeHigh(activity, stopPort);\n\n ports.clear();\n\n scanProgressDialog = new ProgressDialog(activity, R.style.DialogTheme);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n Host.scanPorts(ip, startPort, stopPort, timeout, activity);\n }\n });\n }\n\n \/**\n * Event handler for when an item on the port list is clicked\n *\/\n protected void portListClick(final String ip) {\n this.portList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open certain ports to the browser\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n String item = (String) portList.getItemAtPosition(position);\n if (item == null) {\n return;\n }\n\n Intent intent = null;\n\n if (item.contains(\"80 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip));\n }\n\n if (item.contains(\"443 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"https:\/\/\" + ip));\n }\n\n if (item.contains(\"8080 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip + \":8080\"));\n }\n\n PackageManager packageManager = getPackageManager();\n if (intent != null && packageManager != null) {\n if (packageManager.resolveActivity(intent, 0) != null) {\n startActivity(intent);\n } else {\n Toast.makeText(getApplicationContext(), \"No application found to open this to the browser!\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n });\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n if (scanProgressDialog != null) {\n scanProgressDialog.incrementProgressBy(output);\n }\n }\n });\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(SparseArray output) {\n int scannedPort = output.keyAt(0);\n String item = String.valueOf(scannedPort);\n\n Cursor cursor = db.queryDatabase(\"SELECT name, port FROM ports WHERE port = ?\", new String[]{Integer.toString(scannedPort)});\n\n if (cursor != null) {\n try {\n if (cursor.moveToFirst()) {\n String name = cursor.getString(cursor.getColumnIndex(\"name\"));\n name = (name.isEmpty()) ? \"unknown\" : name;\n item = this.formatOpenPort(output, scannedPort, name, item);\n this.addOpenPort(item);\n }\n } finally {\n cursor.close();\n }\n }\n }\n\n \/**\n * Formats a found open port with its name, description, and associated visualization\n *\n * @param entry Structure holding information about the found open port with its description\n * @param scannedPort The port number\n * @param portName Friendly name for the port\n * @param item Contains the transformed output for the open port\n * @return If all associated data is found a port along with its description, underlying service, and visualization is constructed\n *\/\n private String formatOpenPort(SparseArray entry, int scannedPort, String portName, String item) {\n item = item + \" - \" + portName;\n if (entry.get(scannedPort) != null) {\n item += \" (\" + entry.get(scannedPort) + \")\";\n }\n\n \/\/If the port is in any way related to HTTP then present a nice globe icon next to it via unicode\n if (scannedPort == 80 || scannedPort == 443 || scannedPort == 8080) {\n item += \" \\uD83C\\uDF0E\";\n }\n\n return item;\n }\n\n \/**\n * Adds an open port that was found on a host to the list\n *\n * @param port Port number and description\n *\/\n private void addOpenPort(final String port) {\n setAnimations();\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n synchronized (ports) {\n ports.add(port);\n\n Collections.sort(ports, new Comparator() {\n\n @Override\n public int compare(String lhs, String rhs) {\n int left = Integer.parseInt(lhs.substring(0, lhs.indexOf(\"-\") - 1));\n int right = Integer.parseInt(rhs.substring(0, rhs.indexOf(\"-\") - 1));\n\n return left - right;\n }\n });\n\n adapter.notifyDataSetChanged();\n }\n }\n });\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.database.Cursor;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.util.SparseArray;\nimport android.view.View;\nimport android.view.animation.AnimationUtils;\nimport android.view.animation.LayoutAnimationController;\nimport android.widget.AdapterView;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.db.Database;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\nimport com.aaronjwood.portauthority.utils.Constants;\nimport com.aaronjwood.portauthority.utils.UserPreference;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\n\npublic abstract class HostActivity extends AppCompatActivity implements HostAsyncResponse {\n\n protected int layout;\n protected ArrayAdapter adapter;\n protected ListView portList;\n protected ArrayList ports = new ArrayList<>();\n protected ProgressDialog scanProgressDialog;\n protected Dialog portRangeDialog;\n private Database db;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(this.layout);\n\n db = new Database(this);\n setupPortsAdapter();\n }\n\n \/**\n * Sets up animations for the activity\n *\/\n protected void setAnimations() {\n LayoutAnimationController animation = AnimationUtils.loadLayoutAnimation(this, R.anim.layout_slide_in_bottom);\n portList.setLayoutAnimation(animation);\n }\n\n \/**\n * Sets up the adapter to handle discovered ports\n *\/\n private void setupPortsAdapter() {\n this.portList = (ListView) findViewById(R.id.portList);\n this.adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.port_list_item, ports);\n this.portList.setAdapter(this.adapter);\n this.setAnimations();\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if (this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if (this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Clean up\n *\/\n @Override\n protected void onDestroy() {\n super.onDestroy();\n\n if (db != null) {\n db.close();\n }\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putStringArrayList(\"ports\", ports);\n }\n\n \/**\n * Restore saved data\n *\n * @param savedInstanceState Data from a saved state\n *\/\n public void onRestoreInstanceState(Bundle savedInstanceState) {\n super.onRestoreInstanceState(savedInstanceState);\n\n ports = savedInstanceState.getStringArrayList(\"ports\");\n\n this.setupPortsAdapter();\n }\n\n \/**\n * Event handler for when the port range reset is triggered\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n *\/\n protected void resetPortRangeScanClick(final NumberPicker start, final NumberPicker stop) {\n portRangeDialog.findViewById(R.id.resetPortRangeScan).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n start.setValue(Constants.MIN_PORT_VALUE);\n stop.setValue(Constants.MAX_PORT_VALUE);\n }\n });\n }\n\n \/**\n * Event handler for when the port range scan is finally initiated\n *\n * @param start Starting port picker\n * @param stop Stopping port picker\n * @param timeout Socket timeout\n * @param activity Calling activity\n * @param ip IP address\n *\/\n protected void startPortRangeScanClick(final NumberPicker start, final NumberPicker stop, final int timeout, final HostActivity activity, final String ip) {\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n start.clearFocus();\n stop.clearFocus();\n\n int startPort = start.getValue();\n int stopPort = stop.getValue();\n if ((startPort - stopPort > 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n UserPreference.savePortRangeStart(activity, startPort);\n UserPreference.savePortRangeHigh(activity, stopPort);\n\n ports.clear();\n\n scanProgressDialog = new ProgressDialog(activity, R.style.DialogTheme);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n Host.scanPorts(ip, startPort, stopPort, timeout, activity);\n }\n });\n }\n\n \/**\n * Event handler for when an item on the port list is clicked\n *\/\n protected void portListClick(final String ip) {\n this.portList.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n\n \/**\n * Click handler to open certain ports to the browser\n * @param parent\n * @param view\n * @param position\n * @param id\n *\/\n @Override\n public void onItemClick(AdapterView parent, View view, int position, long id) {\n String item = (String) portList.getItemAtPosition(position);\n if (item == null) {\n return;\n }\n\n Intent intent = null;\n\n if (item.contains(\"80 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip));\n }\n\n if (item.contains(\"443 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"https:\/\/\" + ip));\n }\n\n if (item.contains(\"8080 -\")) {\n intent = new Intent(Intent.ACTION_VIEW, Uri.parse(\"http:\/\/\" + ip + \":8080\"));\n }\n\n PackageManager packageManager = getPackageManager();\n if (intent != null && packageManager != null) {\n if (packageManager.resolveActivity(intent, 0) != null) {\n startActivity(intent);\n } else {\n Toast.makeText(getApplicationContext(), \"No application found to open this to the browser!\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n });\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n if (scanProgressDialog != null) {\n scanProgressDialog.incrementProgressBy(output);\n }\n }\n });\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(SparseArray output) {\n int scannedPort = output.keyAt(0);\n String item = String.valueOf(scannedPort);\n\n Cursor cursor = db.queryDatabase(\"SELECT name, port FROM ports WHERE port = ?\", new String[]{Integer.toString(scannedPort)});\n\n if (cursor != null) {\n try {\n if (cursor.moveToFirst()) {\n String name = cursor.getString(cursor.getColumnIndex(\"name\"));\n name = (name.isEmpty()) ? \"unknown\" : name;\n item = this.formatOpenPort(output, scannedPort, name, item);\n this.addOpenPort(item);\n }\n } finally {\n cursor.close();\n }\n }\n }\n\n \/**\n * Formats a found open port with its name, description, and associated visualization\n *\n * @param entry Structure holding information about the found open port with its description\n * @param scannedPort The port number\n * @param portName Friendly name for the port\n * @param item Contains the transformed output for the open port\n * @return If all associated data is found a port along with its description, underlying service, and visualization is constructed\n *\/\n private String formatOpenPort(SparseArray entry, int scannedPort, String portName, String item) {\n item = item + \" - \" + portName;\n if (entry.get(scannedPort) != null) {\n item += \" (\" + entry.get(scannedPort) + \")\";\n }\n\n \/\/If the port is in any way related to HTTP then present a nice globe icon next to it via unicode\n if (scannedPort == 80 || scannedPort == 443 || scannedPort == 8080) {\n item += \" \\uD83C\\uDF0E\";\n }\n\n return item;\n }\n\n \/**\n * Adds an open port that was found on a host to the list\n *\n * @param port Port number and description\n *\/\n private void addOpenPort(final String port) {\n setAnimations();\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n synchronized (ports) {\n ports.add(port);\n\n Collections.sort(ports, new Comparator() {\n\n @Override\n public int compare(String lhs, String rhs) {\n int left = Integer.parseInt(lhs.substring(0, lhs.indexOf('-') - 1));\n int right = Integer.parseInt(rhs.substring(0, rhs.indexOf('-') - 1));\n\n return left - right;\n }\n });\n\n adapter.notifyDataSetChanged();\n }\n }\n });\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"} +{"non_functional_requirement":"framerate","commit":"https:\/\/github.com\/erikusaj\/fdroidTvClient\/commit\/a9d817441ffde079196935cfb82c44da2d271cf9","commit_message":"'\\\\\"Bunch together notifications to prevent flickering in UI.\\\\n\\\\nThis reverts to the previous behaviour before 8faf151.\\\\nThen","source_code":"package org.fdroid.fdroid.data;\n\nimport android.app.IntentService;\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.Signature;\nimport android.net.Uri;\nimport android.os.Process;\nimport android.support.annotation.Nullable;\nimport android.util.Log;\n\nimport org.acra.ACRA;\nimport org.fdroid.fdroid.Hasher;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Schema.InstalledAppTable;\n\nimport java.io.File;\nimport java.io.FilenameFilter;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.List;\nimport java.util.Map;\n\nimport rx.functions.Action1;\nimport rx.schedulers.Schedulers;\nimport rx.subjects.PublishSubject;\n\n\/**\n * Handles all updates to {@link InstalledAppProvider}, whether checking the contents\n * versus what Android says is installed, or processing {@link Intent}s that come\n * from {@link android.content.BroadcastReceiver}s for {@link Intent#ACTION_PACKAGE_ADDED}\n * and {@link Intent#ACTION_PACKAGE_REMOVED}\n * \n * Since {@link android.content.ContentProvider#insert(Uri, ContentValues)} does not check\n * for duplicate records, it is entirely the job of this service to ensure that it is not\n * inserting duplicate versions of the same installed APK. On that note,\n * {@link #insertAppIntoDb(Context, PackageInfo, String, String)} and\n * {@link #deleteAppFromDb(Context, String)} are both static methods to enable easy testing\n * of this stuff.\n *\/\npublic class InstalledAppProviderService extends IntentService {\n private static final String TAG = \"InstalledAppProviderSer\";\n\n private static final String ACTION_INSERT = \"org.fdroid.fdroid.data.action.INSERT\";\n private static final String ACTION_DELETE = \"org.fdroid.fdroid.data.action.DELETE\";\n\n private static final String EXTRA_PACKAGE_INFO = \"org.fdroid.fdroid.data.extra.PACKAGE_INFO\";\n\n \/**\n * This is for notifing the users of this {@link android.content.ContentProvider}\n * that the contents has changed. Since {@link Intent}s can come in slow\n * or fast, and this can trigger a lot of UI updates, the actual\n * notifications are rate limited to one per second.\n *\/\n private PublishSubject notifyEvents;\n\n public InstalledAppProviderService() {\n super(\"InstalledAppProviderService\");\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n notifyEvents = PublishSubject.create();\n notifyEvents\n .subscribeOn(Schedulers.newThread())\n .subscribe(new Action1() {\n @Override\n public void call(Void voidArg) {\n Utils.debugLog(TAG, \"Notifying content providers (so they can update the relevant views).\");\n getContentResolver().notifyChange(AppProvider.getContentUri(), null);\n getContentResolver().notifyChange(ApkProvider.getContentUri(), null);\n }\n });\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, PackageInfo packageInfo) {\n insert(context, Utils.getPackageUri(packageInfo.packageName), packageInfo);\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, Uri uri) {\n insert(context, uri, null);\n }\n\n private static void insert(Context context, Uri uri, PackageInfo packageInfo) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_INSERT);\n intent.setData(uri);\n intent.putExtra(EXTRA_PACKAGE_INFO, packageInfo);\n context.startService(intent);\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, String packageName) {\n delete(context, Utils.getPackageUri(packageName));\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, Uri uri) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_DELETE);\n intent.setData(uri);\n context.startService(intent);\n }\n\n \/**\n * Make sure that {@link InstalledAppProvider}, our database of installed apps,\n * is in sync with what the {@link PackageManager} tells us is installed. Once\n * completed, the relevant {@link android.content.ContentProvider}s will be\n * notified of any changes to installed statuses.\n *

\n * The installed app cache could get out of sync, e.g. if F-Droid crashed\/ or\n * ran out of battery half way through responding to {@link Intent#ACTION_PACKAGE_ADDED}.\n * This method returns immediately, and will continue to work in an\n * {@link IntentService}. It doesn't really matter where we put this in the\n * bootstrap process, because it runs in its own thread, at the lowest priority:\n * {@link Process#THREAD_PRIORITY_LOWEST}.\n *

\n * APKs installed in {@code \/system} will often have zeroed out timestamps, like\n * 2008-01-01 (ziptime) or 2009-01-01. So instead anything older than 2010 every\n * time since we have no way to know whether an APK wasn't changed as part of an\n * OTA update. An OTA update could change the APK without changing the\n * {@link PackageInfo#versionCode} or {@link PackageInfo#lastUpdateTime}.\n *\n * @see issue #819<\/a>\n *\/\n public static void compareToPackageManager(Context context) {\n Map cachedInfo = InstalledAppProvider.Helper.all(context);\n\n List packageInfoList = context.getPackageManager()\n .getInstalledPackages(PackageManager.GET_SIGNATURES);\n for (PackageInfo packageInfo : packageInfoList) {\n if (cachedInfo.containsKey(packageInfo.packageName)) {\n if (packageInfo.lastUpdateTime < 1262300400000L \/\/ 2010-01-01 00:00\n || packageInfo.lastUpdateTime > cachedInfo.get(packageInfo.packageName)) {\n insert(context, packageInfo);\n }\n cachedInfo.remove(packageInfo.packageName);\n } else {\n insert(context, packageInfo);\n }\n }\n\n for (String packageName : cachedInfo.keySet()) {\n delete(context, packageName);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n if (intent == null) {\n return;\n }\n\n String packageName = intent.getData().getSchemeSpecificPart();\n final String action = intent.getAction();\n if (ACTION_INSERT.equals(action)) {\n PackageInfo packageInfo = getPackageInfo(intent, packageName);\n if (packageInfo != null) {\n Log.i(TAG, \"Marking \" + packageName + \" as installed\");\n File apk = new File(packageInfo.applicationInfo.publicSourceDir);\n if (apk.isDirectory()) {\n FilenameFilter filter = new FilenameFilter() {\n @Override\n public boolean accept(File dir, String name) {\n return name.endsWith(\".apk\");\n }\n };\n File[] files = apk.listFiles(filter);\n if (files == null) {\n String msg = packageName + \" sourceDir has no APKs: \"\n + apk.getAbsolutePath();\n Utils.debugLog(TAG, msg);\n ACRA.getErrorReporter().handleException(new IllegalArgumentException(msg), false);\n return;\n }\n apk = files[0];\n }\n if (apk.exists() && apk.canRead()) {\n try {\n String hashType = \"sha256\";\n String hash = Utils.getBinaryHash(apk, hashType);\n insertAppIntoDb(this, packageInfo, hashType, hash);\n } catch (IllegalArgumentException e) {\n Utils.debugLog(TAG, e.getMessage());\n ACRA.getErrorReporter().handleException(e, false);\n return;\n }\n }\n }\n } else if (ACTION_DELETE.equals(action)) {\n Log.i(TAG, \"Marking \" + packageName + \" as no longer installed\");\n deleteAppFromDb(this, packageName);\n }\n notifyEvents.onNext(null);\n }\n\n \/**\n * This class will either have received an intent from the {@link InstalledAppProviderService}\n * itself, while iterating over installed apps, or from a {@link Intent#ACTION_PACKAGE_ADDED}\n * broadcast. In the first case, it will already have a {@link PackageInfo} for us. However if\n * it is from the later case, we'll need to query the {@link PackageManager} ourselves to get\n * this info.\n *

\n * Can still return null, as there is potentially race conditions to do with uninstalling apps\n * such that querying the {@link PackageManager} for a given package may throw an exception.\n *\/\n @Nullable\n private PackageInfo getPackageInfo(Intent intent, String packageName) {\n PackageInfo packageInfo = intent.getParcelableExtra(EXTRA_PACKAGE_INFO);\n if (packageInfo != null) {\n return packageInfo;\n }\n\n try {\n return getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n \/**\n * @param hash Although the has could be calculated within this function, it is helpful to inject\n * the hash so as to be able to use this method during testing. Otherwise, the\n * hashing method will try to hash a non-existent .apk file and try to insert NULL\n * into the database when under test.\n *\/\n static void insertAppIntoDb(Context context, PackageInfo packageInfo, String hashType, String hash) {\n Uri uri = InstalledAppProvider.getContentUri();\n ContentValues contentValues = new ContentValues();\n contentValues.put(InstalledAppTable.Cols.PACKAGE_NAME, packageInfo.packageName);\n contentValues.put(InstalledAppTable.Cols.VERSION_CODE, packageInfo.versionCode);\n contentValues.put(InstalledAppTable.Cols.VERSION_NAME, packageInfo.versionName);\n contentValues.put(InstalledAppTable.Cols.APPLICATION_LABEL,\n InstalledAppProvider.getApplicationLabel(context, packageInfo.packageName));\n contentValues.put(InstalledAppTable.Cols.SIGNATURE, getPackageSig(packageInfo));\n contentValues.put(InstalledAppTable.Cols.LAST_UPDATE_TIME, packageInfo.lastUpdateTime);\n\n contentValues.put(InstalledAppTable.Cols.HASH_TYPE, hashType);\n contentValues.put(InstalledAppTable.Cols.HASH, hash);\n\n context.getContentResolver().insert(uri, contentValues);\n }\n\n static void deleteAppFromDb(Context context, String packageName) {\n Uri uri = InstalledAppProvider.getAppUri(packageName);\n context.getContentResolver().delete(uri, null, null);\n }\n\n private static String getPackageSig(PackageInfo info) {\n if (info == null || info.signatures == null || info.signatures.length < 1) {\n return \"\";\n }\n Signature sig = info.signatures[0];\n String sigHash = \"\";\n try {\n Hasher hash = new Hasher(\"MD5\", sig.toCharsString().getBytes());\n sigHash = hash.getHash();\n } catch (NoSuchAlgorithmException e) {\n \/\/ ignore\n }\n return sigHash;\n }\n\n}","target_code":"package org.fdroid.fdroid.data;\n\nimport android.app.IntentService;\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.Signature;\nimport android.net.Uri;\nimport android.os.Process;\nimport android.support.annotation.Nullable;\nimport android.util.Log;\n\nimport org.acra.ACRA;\nimport org.fdroid.fdroid.Hasher;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Schema.InstalledAppTable;\n\nimport java.io.File;\nimport java.io.FilenameFilter;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\n\nimport rx.functions.Action1;\nimport rx.schedulers.Schedulers;\nimport rx.subjects.PublishSubject;\n\n\/**\n * Handles all updates to {@link InstalledAppProvider}, whether checking the contents\n * versus what Android says is installed, or processing {@link Intent}s that come\n * from {@link android.content.BroadcastReceiver}s for {@link Intent#ACTION_PACKAGE_ADDED}\n * and {@link Intent#ACTION_PACKAGE_REMOVED}\n * \n * Since {@link android.content.ContentProvider#insert(Uri, ContentValues)} does not check\n * for duplicate records, it is entirely the job of this service to ensure that it is not\n * inserting duplicate versions of the same installed APK. On that note,\n * {@link #insertAppIntoDb(Context, PackageInfo, String, String)} and\n * {@link #deleteAppFromDb(Context, String)} are both static methods to enable easy testing\n * of this stuff.\n *\/\npublic class InstalledAppProviderService extends IntentService {\n private static final String TAG = \"InstalledAppProviderSer\";\n\n private static final String ACTION_INSERT = \"org.fdroid.fdroid.data.action.INSERT\";\n private static final String ACTION_DELETE = \"org.fdroid.fdroid.data.action.DELETE\";\n\n private static final String EXTRA_PACKAGE_INFO = \"org.fdroid.fdroid.data.extra.PACKAGE_INFO\";\n\n \/**\n * This is for notifing the users of this {@link android.content.ContentProvider}\n * that the contents has changed. Since {@link Intent}s can come in slow\n * or fast, and this can trigger a lot of UI updates, the actual\n * notifications are rate limited to one per second.\n *\/\n private PublishSubject packageChangeNotifier;\n\n public InstalledAppProviderService() {\n super(\"InstalledAppProviderService\");\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n packageChangeNotifier = PublishSubject.create();\n\n \/\/ This \"debounced\" event will queue up any number of invocations within one second, and\n \/\/ only emit an event to the subscriber after it has not received any new events for one second.\n \/\/ This ensures that we don't constantly ask our lists of apps to update as we iterate over\n \/\/ the list of installed apps and insert them to the database...\n packageChangeNotifier\n .subscribeOn(Schedulers.newThread())\n .debounce(1, TimeUnit.SECONDS)\n .subscribe(new Action1() {\n @Override\n public void call(String packageName) {\n Utils.debugLog(TAG, \"Notifying content providers (so they can update the relevant views).\");\n getContentResolver().notifyChange(AppProvider.getContentUri(), null);\n getContentResolver().notifyChange(ApkProvider.getContentUri(), null);\n }\n });\n\n \/\/ ...alternatively, this non-debounced version will instantly emit an event about the\n \/\/ particular package being updated. This is required so that our AppDetails view can update\n \/\/ itself immediately in response to an app being installed\/upgraded\/removed.\n \/\/ It does this _without_ triggering the main lists to update themselves, because they listen\n \/\/ only for changes to specific URIs in the AppProvider. These are triggered when a more\n \/\/ general notification (e.g. to AppProvider.getContentUri()) is fired, but not when a\n \/\/ sibling such as AppProvider.getHighestPriorityMetadataUri() is fired.\n packageChangeNotifier.subscribeOn(Schedulers.newThread())\n .subscribe(new Action1() {\n @Override\n public void call(String packageName) {\n getContentResolver().notifyChange(AppProvider.getHighestPriorityMetadataUri(packageName), null);\n }\n });\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, PackageInfo packageInfo) {\n insert(context, Utils.getPackageUri(packageInfo.packageName), packageInfo);\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, Uri uri) {\n insert(context, uri, null);\n }\n\n private static void insert(Context context, Uri uri, PackageInfo packageInfo) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_INSERT);\n intent.setData(uri);\n intent.putExtra(EXTRA_PACKAGE_INFO, packageInfo);\n context.startService(intent);\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, String packageName) {\n delete(context, Utils.getPackageUri(packageName));\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, Uri uri) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_DELETE);\n intent.setData(uri);\n context.startService(intent);\n }\n\n \/**\n * Make sure that {@link InstalledAppProvider}, our database of installed apps,\n * is in sync with what the {@link PackageManager} tells us is installed. Once\n * completed, the relevant {@link android.content.ContentProvider}s will be\n * notified of any changes to installed statuses.\n *

\n * The installed app cache could get out of sync, e.g. if F-Droid crashed\/ or\n * ran out of battery half way through responding to {@link Intent#ACTION_PACKAGE_ADDED}.\n * This method returns immediately, and will continue to work in an\n * {@link IntentService}. It doesn't really matter where we put this in the\n * bootstrap process, because it runs in its own thread, at the lowest priority:\n * {@link Process#THREAD_PRIORITY_LOWEST}.\n *

\n * APKs installed in {@code \/system} will often have zeroed out timestamps, like\n * 2008-01-01 (ziptime) or 2009-01-01. So instead anything older than 2010 every\n * time since we have no way to know whether an APK wasn't changed as part of an\n * OTA update. An OTA update could change the APK without changing the\n * {@link PackageInfo#versionCode} or {@link PackageInfo#lastUpdateTime}.\n *\n * @see issue #819<\/a>\n *\/\n public static void compareToPackageManager(Context context) {\n Map cachedInfo = InstalledAppProvider.Helper.all(context);\n\n List packageInfoList = context.getPackageManager()\n .getInstalledPackages(PackageManager.GET_SIGNATURES);\n for (PackageInfo packageInfo : packageInfoList) {\n if (cachedInfo.containsKey(packageInfo.packageName)) {\n if (packageInfo.lastUpdateTime < 1262300400000L \/\/ 2010-01-01 00:00\n || packageInfo.lastUpdateTime > cachedInfo.get(packageInfo.packageName)) {\n insert(context, packageInfo);\n }\n cachedInfo.remove(packageInfo.packageName);\n } else {\n insert(context, packageInfo);\n }\n }\n\n for (String packageName : cachedInfo.keySet()) {\n delete(context, packageName);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n if (intent == null) {\n return;\n }\n\n String packageName = intent.getData().getSchemeSpecificPart();\n final String action = intent.getAction();\n if (ACTION_INSERT.equals(action)) {\n PackageInfo packageInfo = getPackageInfo(intent, packageName);\n if (packageInfo != null) {\n Log.i(TAG, \"Marking \" + packageName + \" as installed\");\n File apk = new File(packageInfo.applicationInfo.publicSourceDir);\n if (apk.isDirectory()) {\n FilenameFilter filter = new FilenameFilter() {\n @Override\n public boolean accept(File dir, String name) {\n return name.endsWith(\".apk\");\n }\n };\n File[] files = apk.listFiles(filter);\n if (files == null) {\n String msg = packageName + \" sourceDir has no APKs: \"\n + apk.getAbsolutePath();\n Utils.debugLog(TAG, msg);\n ACRA.getErrorReporter().handleException(new IllegalArgumentException(msg), false);\n return;\n }\n apk = files[0];\n }\n if (apk.exists() && apk.canRead()) {\n try {\n String hashType = \"sha256\";\n String hash = Utils.getBinaryHash(apk, hashType);\n insertAppIntoDb(this, packageInfo, hashType, hash);\n } catch (IllegalArgumentException e) {\n Utils.debugLog(TAG, e.getMessage());\n ACRA.getErrorReporter().handleException(e, false);\n return;\n }\n }\n }\n } else if (ACTION_DELETE.equals(action)) {\n Log.i(TAG, \"Marking \" + packageName + \" as no longer installed\");\n deleteAppFromDb(this, packageName);\n }\n packageChangeNotifier.onNext(packageName);\n }\n\n \/**\n * This class will either have received an intent from the {@link InstalledAppProviderService}\n * itself, while iterating over installed apps, or from a {@link Intent#ACTION_PACKAGE_ADDED}\n * broadcast. In the first case, it will already have a {@link PackageInfo} for us. However if\n * it is from the later case, we'll need to query the {@link PackageManager} ourselves to get\n * this info.\n *

\n * Can still return null, as there is potentially race conditions to do with uninstalling apps\n * such that querying the {@link PackageManager} for a given package may throw an exception.\n *\/\n @Nullable\n private PackageInfo getPackageInfo(Intent intent, String packageName) {\n PackageInfo packageInfo = intent.getParcelableExtra(EXTRA_PACKAGE_INFO);\n if (packageInfo != null) {\n return packageInfo;\n }\n\n try {\n return getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n \/**\n * @param hash Although the has could be calculated within this function, it is helpful to inject\n * the hash so as to be able to use this method during testing. Otherwise, the\n * hashing method will try to hash a non-existent .apk file and try to insert NULL\n * into the database when under test.\n *\/\n static void insertAppIntoDb(Context context, PackageInfo packageInfo, String hashType, String hash) {\n Uri uri = InstalledAppProvider.getContentUri();\n ContentValues contentValues = new ContentValues();\n contentValues.put(InstalledAppTable.Cols.PACKAGE_NAME, packageInfo.packageName);\n contentValues.put(InstalledAppTable.Cols.VERSION_CODE, packageInfo.versionCode);\n contentValues.put(InstalledAppTable.Cols.VERSION_NAME, packageInfo.versionName);\n contentValues.put(InstalledAppTable.Cols.APPLICATION_LABEL,\n InstalledAppProvider.getApplicationLabel(context, packageInfo.packageName));\n contentValues.put(InstalledAppTable.Cols.SIGNATURE, getPackageSig(packageInfo));\n contentValues.put(InstalledAppTable.Cols.LAST_UPDATE_TIME, packageInfo.lastUpdateTime);\n\n contentValues.put(InstalledAppTable.Cols.HASH_TYPE, hashType);\n contentValues.put(InstalledAppTable.Cols.HASH, hash);\n\n context.getContentResolver().insert(uri, contentValues);\n }\n\n static void deleteAppFromDb(Context context, String packageName) {\n Uri uri = InstalledAppProvider.getAppUri(packageName);\n context.getContentResolver().delete(uri, null, null);\n }\n\n private static String getPackageSig(PackageInfo info) {\n if (info == null || info.signatures == null || info.signatures.length < 1) {\n return \"\";\n }\n Signature sig = info.signatures[0];\n String sigHash = \"\";\n try {\n Hasher hash = new Hasher(\"MD5\", sig.toCharsString().getBytes());\n sigHash = hash.getHash();\n } catch (NoSuchAlgorithmException e) {\n \/\/ ignore\n }\n return sigHash;\n }\n\n}","pl":"Java","chain_of_thought":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the frame rate. Write the entire code and no other text.\n```java\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n SearchEngineManager.getInstance().init(this);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n```\n\n### Thought:\nThe onCreate() function performs necessary initializations such as loading certain preferences, and sets up SearchEngineManager instance. However, loading preferences depends on the Search Engine manager, because the default search engine preference uses the search engine manager; we therefore need to ensure that preferences aren't loaded until search engines are loaded, to avoid potential hangup of the application for a fresh install. The following optimized code first initializes the search engine manager and then loads preferences.\n\n### Response:\n ```java\n \/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n SearchEngineManager.getInstance().init(this);\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the frame rate. Write the entire code and no other text:\npackage org.fdroid.fdroid.data;\n\nimport android.app.IntentService;\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.Signature;\nimport android.net.Uri;\nimport android.os.Process;\nimport android.support.annotation.Nullable;\nimport android.util.Log;\n\nimport org.acra.ACRA;\nimport org.fdroid.fdroid.Hasher;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Schema.InstalledAppTable;\n\nimport java.io.File;\nimport java.io.FilenameFilter;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.List;\nimport java.util.Map;\n\nimport rx.functions.Action1;\nimport rx.schedulers.Schedulers;\nimport rx.subjects.PublishSubject;\n\n\/**\n * Handles all updates to {@link InstalledAppProvider}, whether checking the contents\n * versus what Android says is installed, or processing {@link Intent}s that come\n * from {@link android.content.BroadcastReceiver}s for {@link Intent#ACTION_PACKAGE_ADDED}\n * and {@link Intent#ACTION_PACKAGE_REMOVED}\n * \n * Since {@link android.content.ContentProvider#insert(Uri, ContentValues)} does not check\n * for duplicate records, it is entirely the job of this service to ensure that it is not\n * inserting duplicate versions of the same installed APK. On that note,\n * {@link #insertAppIntoDb(Context, PackageInfo, String, String)} and\n * {@link #deleteAppFromDb(Context, String)} are both static methods to enable easy testing\n * of this stuff.\n *\/\npublic class InstalledAppProviderService extends IntentService {\n private static final String TAG = \"InstalledAppProviderSer\";\n\n private static final String ACTION_INSERT = \"org.fdroid.fdroid.data.action.INSERT\";\n private static final String ACTION_DELETE = \"org.fdroid.fdroid.data.action.DELETE\";\n\n private static final String EXTRA_PACKAGE_INFO = \"org.fdroid.fdroid.data.extra.PACKAGE_INFO\";\n\n \/**\n * This is for notifing the users of this {@link android.content.ContentProvider}\n * that the contents has changed. Since {@link Intent}s can come in slow\n * or fast, and this can trigger a lot of UI updates, the actual\n * notifications are rate limited to one per second.\n *\/\n private PublishSubject notifyEvents;\n\n public InstalledAppProviderService() {\n super(\"InstalledAppProviderService\");\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n notifyEvents = PublishSubject.create();\n notifyEvents\n .subscribeOn(Schedulers.newThread())\n .subscribe(new Action1() {\n @Override\n public void call(Void voidArg) {\n Utils.debugLog(TAG, \"Notifying content providers (so they can update the relevant views).\");\n getContentResolver().notifyChange(AppProvider.getContentUri(), null);\n getContentResolver().notifyChange(ApkProvider.getContentUri(), null);\n }\n });\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, PackageInfo packageInfo) {\n insert(context, Utils.getPackageUri(packageInfo.packageName), packageInfo);\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, Uri uri) {\n insert(context, uri, null);\n }\n\n private static void insert(Context context, Uri uri, PackageInfo packageInfo) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_INSERT);\n intent.setData(uri);\n intent.putExtra(EXTRA_PACKAGE_INFO, packageInfo);\n context.startService(intent);\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, String packageName) {\n delete(context, Utils.getPackageUri(packageName));\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, Uri uri) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_DELETE);\n intent.setData(uri);\n context.startService(intent);\n }\n\n \/**\n * Make sure that {@link InstalledAppProvider}, our database of installed apps,\n * is in sync with what the {@link PackageManager} tells us is installed. Once\n * completed, the relevant {@link android.content.ContentProvider}s will be\n * notified of any changes to installed statuses.\n *

\n * The installed app cache could get out of sync, e.g. if F-Droid crashed\/ or\n * ran out of battery half way through responding to {@link Intent#ACTION_PACKAGE_ADDED}.\n * This method returns immediately, and will continue to work in an\n * {@link IntentService}. It doesn't really matter where we put this in the\n * bootstrap process, because it runs in its own thread, at the lowest priority:\n * {@link Process#THREAD_PRIORITY_LOWEST}.\n *

\n * APKs installed in {@code \/system} will often have zeroed out timestamps, like\n * 2008-01-01 (ziptime) or 2009-01-01. So instead anything older than 2010 every\n * time since we have no way to know whether an APK wasn't changed as part of an\n * OTA update. An OTA update could change the APK without changing the\n * {@link PackageInfo#versionCode} or {@link PackageInfo#lastUpdateTime}.\n *\n * @see issue #819<\/a>\n *\/\n public static void compareToPackageManager(Context context) {\n Map cachedInfo = InstalledAppProvider.Helper.all(context);\n\n List packageInfoList = context.getPackageManager()\n .getInstalledPackages(PackageManager.GET_SIGNATURES);\n for (PackageInfo packageInfo : packageInfoList) {\n if (cachedInfo.containsKey(packageInfo.packageName)) {\n if (packageInfo.lastUpdateTime < 1262300400000L \/\/ 2010-01-01 00:00\n || packageInfo.lastUpdateTime > cachedInfo.get(packageInfo.packageName)) {\n insert(context, packageInfo);\n }\n cachedInfo.remove(packageInfo.packageName);\n } else {\n insert(context, packageInfo);\n }\n }\n\n for (String packageName : cachedInfo.keySet()) {\n delete(context, packageName);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n if (intent == null) {\n return;\n }\n\n String packageName = intent.getData().getSchemeSpecificPart();\n final String action = intent.getAction();\n if (ACTION_INSERT.equals(action)) {\n PackageInfo packageInfo = getPackageInfo(intent, packageName);\n if (packageInfo != null) {\n Log.i(TAG, \"Marking \" + packageName + \" as installed\");\n File apk = new File(packageInfo.applicationInfo.publicSourceDir);\n if (apk.isDirectory()) {\n FilenameFilter filter = new FilenameFilter() {\n @Override\n public boolean accept(File dir, String name) {\n return name.endsWith(\".apk\");\n }\n };\n File[] files = apk.listFiles(filter);\n if (files == null) {\n String msg = packageName + \" sourceDir has no APKs: \"\n + apk.getAbsolutePath();\n Utils.debugLog(TAG, msg);\n ACRA.getErrorReporter().handleException(new IllegalArgumentException(msg), false);\n return;\n }\n apk = files[0];\n }\n if (apk.exists() && apk.canRead()) {\n try {\n String hashType = \"sha256\";\n String hash = Utils.getBinaryHash(apk, hashType);\n insertAppIntoDb(this, packageInfo, hashType, hash);\n } catch (IllegalArgumentException e) {\n Utils.debugLog(TAG, e.getMessage());\n ACRA.getErrorReporter().handleException(e, false);\n return;\n }\n }\n }\n } else if (ACTION_DELETE.equals(action)) {\n Log.i(TAG, \"Marking \" + packageName + \" as no longer installed\");\n deleteAppFromDb(this, packageName);\n }\n notifyEvents.onNext(null);\n }\n\n \/**\n * This class will either have received an intent from the {@link InstalledAppProviderService}\n * itself, while iterating over installed apps, or from a {@link Intent#ACTION_PACKAGE_ADDED}\n * broadcast. In the first case, it will already have a {@link PackageInfo} for us. However if\n * it is from the later case, we'll need to query the {@link PackageManager} ourselves to get\n * this info.\n *

\n * Can still return null, as there is potentially race conditions to do with uninstalling apps\n * such that querying the {@link PackageManager} for a given package may throw an exception.\n *\/\n @Nullable\n private PackageInfo getPackageInfo(Intent intent, String packageName) {\n PackageInfo packageInfo = intent.getParcelableExtra(EXTRA_PACKAGE_INFO);\n if (packageInfo != null) {\n return packageInfo;\n }\n\n try {\n return getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n \/**\n * @param hash Although the has could be calculated within this function, it is helpful to inject\n * the hash so as to be able to use this method during testing. Otherwise, the\n * hashing method will try to hash a non-existent .apk file and try to insert NULL\n * into the database when under test.\n *\/\n static void insertAppIntoDb(Context context, PackageInfo packageInfo, String hashType, String hash) {\n Uri uri = InstalledAppProvider.getContentUri();\n ContentValues contentValues = new ContentValues();\n contentValues.put(InstalledAppTable.Cols.PACKAGE_NAME, packageInfo.packageName);\n contentValues.put(InstalledAppTable.Cols.VERSION_CODE, packageInfo.versionCode);\n contentValues.put(InstalledAppTable.Cols.VERSION_NAME, packageInfo.versionName);\n contentValues.put(InstalledAppTable.Cols.APPLICATION_LABEL,\n InstalledAppProvider.getApplicationLabel(context, packageInfo.packageName));\n contentValues.put(InstalledAppTable.Cols.SIGNATURE, getPackageSig(packageInfo));\n contentValues.put(InstalledAppTable.Cols.LAST_UPDATE_TIME, packageInfo.lastUpdateTime);\n\n contentValues.put(InstalledAppTable.Cols.HASH_TYPE, hashType);\n contentValues.put(InstalledAppTable.Cols.HASH, hash);\n\n context.getContentResolver().insert(uri, contentValues);\n }\n\n static void deleteAppFromDb(Context context, String packageName) {\n Uri uri = InstalledAppProvider.getAppUri(packageName);\n context.getContentResolver().delete(uri, null, null);\n }\n\n private static String getPackageSig(PackageInfo info) {\n if (info == null || info.signatures == null || info.signatures.length < 1) {\n return \"\";\n }\n Signature sig = info.signatures[0];\n String sigHash = \"\";\n try {\n Hasher hash = new Hasher(\"MD5\", sig.toCharsString().getBytes());\n sigHash = hash.getHash();\n } catch (NoSuchAlgorithmException e) {\n \/\/ ignore\n }\n return sigHash;\n }\n\n}\n\n### Thought:","one_shot":"Below is an instruction that describes a task along with an example. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given Java program to optimize and improve the frame rate. Write the entire code and no other text.\n```java\n\/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n SearchEngineManager.getInstance().init(this);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n```\n### Response:\n ```java\n \/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage org.mozilla.focus;\n\nimport android.app.Application;\nimport android.preference.PreferenceManager;\n\nimport org.mozilla.focus.search.SearchEngineManager;\nimport org.mozilla.focus.telemetry.TelemetryWrapper;\nimport org.mozilla.focus.utils.AdjustHelper;\n\npublic class FocusApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n\n SearchEngineManager.getInstance().init(this);\n\n PreferenceManager.setDefaultValues(this, R.xml.settings, false);\n\n TelemetryWrapper.init(this);\n AdjustHelper.setupAdjustIfNeeded(this);\n }\n}\n```\n\n### Instruction:\nRewrite the given java program to optimize and improve the frame rate. Write the entire code and no other text:\npackage org.fdroid.fdroid.data;\n\nimport android.app.IntentService;\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.Signature;\nimport android.net.Uri;\nimport android.os.Process;\nimport android.support.annotation.Nullable;\nimport android.util.Log;\n\nimport org.acra.ACRA;\nimport org.fdroid.fdroid.Hasher;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Schema.InstalledAppTable;\n\nimport java.io.File;\nimport java.io.FilenameFilter;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.List;\nimport java.util.Map;\n\nimport rx.functions.Action1;\nimport rx.schedulers.Schedulers;\nimport rx.subjects.PublishSubject;\n\n\/**\n * Handles all updates to {@link InstalledAppProvider}, whether checking the contents\n * versus what Android says is installed, or processing {@link Intent}s that come\n * from {@link android.content.BroadcastReceiver}s for {@link Intent#ACTION_PACKAGE_ADDED}\n * and {@link Intent#ACTION_PACKAGE_REMOVED}\n * \n * Since {@link android.content.ContentProvider#insert(Uri, ContentValues)} does not check\n * for duplicate records, it is entirely the job of this service to ensure that it is not\n * inserting duplicate versions of the same installed APK. On that note,\n * {@link #insertAppIntoDb(Context, PackageInfo, String, String)} and\n * {@link #deleteAppFromDb(Context, String)} are both static methods to enable easy testing\n * of this stuff.\n *\/\npublic class InstalledAppProviderService extends IntentService {\n private static final String TAG = \"InstalledAppProviderSer\";\n\n private static final String ACTION_INSERT = \"org.fdroid.fdroid.data.action.INSERT\";\n private static final String ACTION_DELETE = \"org.fdroid.fdroid.data.action.DELETE\";\n\n private static final String EXTRA_PACKAGE_INFO = \"org.fdroid.fdroid.data.extra.PACKAGE_INFO\";\n\n \/**\n * This is for notifing the users of this {@link android.content.ContentProvider}\n * that the contents has changed. Since {@link Intent}s can come in slow\n * or fast, and this can trigger a lot of UI updates, the actual\n * notifications are rate limited to one per second.\n *\/\n private PublishSubject notifyEvents;\n\n public InstalledAppProviderService() {\n super(\"InstalledAppProviderService\");\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n notifyEvents = PublishSubject.create();\n notifyEvents\n .subscribeOn(Schedulers.newThread())\n .subscribe(new Action1() {\n @Override\n public void call(Void voidArg) {\n Utils.debugLog(TAG, \"Notifying content providers (so they can update the relevant views).\");\n getContentResolver().notifyChange(AppProvider.getContentUri(), null);\n getContentResolver().notifyChange(ApkProvider.getContentUri(), null);\n }\n });\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, PackageInfo packageInfo) {\n insert(context, Utils.getPackageUri(packageInfo.packageName), packageInfo);\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, Uri uri) {\n insert(context, uri, null);\n }\n\n private static void insert(Context context, Uri uri, PackageInfo packageInfo) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_INSERT);\n intent.setData(uri);\n intent.putExtra(EXTRA_PACKAGE_INFO, packageInfo);\n context.startService(intent);\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, String packageName) {\n delete(context, Utils.getPackageUri(packageName));\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, Uri uri) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_DELETE);\n intent.setData(uri);\n context.startService(intent);\n }\n\n \/**\n * Make sure that {@link InstalledAppProvider}, our database of installed apps,\n * is in sync with what the {@link PackageManager} tells us is installed. Once\n * completed, the relevant {@link android.content.ContentProvider}s will be\n * notified of any changes to installed statuses.\n *

\n * The installed app cache could get out of sync, e.g. if F-Droid crashed\/ or\n * ran out of battery half way through responding to {@link Intent#ACTION_PACKAGE_ADDED}.\n * This method returns immediately, and will continue to work in an\n * {@link IntentService}. It doesn't really matter where we put this in the\n * bootstrap process, because it runs in its own thread, at the lowest priority:\n * {@link Process#THREAD_PRIORITY_LOWEST}.\n *

\n * APKs installed in {@code \/system} will often have zeroed out timestamps, like\n * 2008-01-01 (ziptime) or 2009-01-01. So instead anything older than 2010 every\n * time since we have no way to know whether an APK wasn't changed as part of an\n * OTA update. An OTA update could change the APK without changing the\n * {@link PackageInfo#versionCode} or {@link PackageInfo#lastUpdateTime}.\n *\n * @see issue #819<\/a>\n *\/\n public static void compareToPackageManager(Context context) {\n Map cachedInfo = InstalledAppProvider.Helper.all(context);\n\n List packageInfoList = context.getPackageManager()\n .getInstalledPackages(PackageManager.GET_SIGNATURES);\n for (PackageInfo packageInfo : packageInfoList) {\n if (cachedInfo.containsKey(packageInfo.packageName)) {\n if (packageInfo.lastUpdateTime < 1262300400000L \/\/ 2010-01-01 00:00\n || packageInfo.lastUpdateTime > cachedInfo.get(packageInfo.packageName)) {\n insert(context, packageInfo);\n }\n cachedInfo.remove(packageInfo.packageName);\n } else {\n insert(context, packageInfo);\n }\n }\n\n for (String packageName : cachedInfo.keySet()) {\n delete(context, packageName);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n if (intent == null) {\n return;\n }\n\n String packageName = intent.getData().getSchemeSpecificPart();\n final String action = intent.getAction();\n if (ACTION_INSERT.equals(action)) {\n PackageInfo packageInfo = getPackageInfo(intent, packageName);\n if (packageInfo != null) {\n Log.i(TAG, \"Marking \" + packageName + \" as installed\");\n File apk = new File(packageInfo.applicationInfo.publicSourceDir);\n if (apk.isDirectory()) {\n FilenameFilter filter = new FilenameFilter() {\n @Override\n public boolean accept(File dir, String name) {\n return name.endsWith(\".apk\");\n }\n };\n File[] files = apk.listFiles(filter);\n if (files == null) {\n String msg = packageName + \" sourceDir has no APKs: \"\n + apk.getAbsolutePath();\n Utils.debugLog(TAG, msg);\n ACRA.getErrorReporter().handleException(new IllegalArgumentException(msg), false);\n return;\n }\n apk = files[0];\n }\n if (apk.exists() && apk.canRead()) {\n try {\n String hashType = \"sha256\";\n String hash = Utils.getBinaryHash(apk, hashType);\n insertAppIntoDb(this, packageInfo, hashType, hash);\n } catch (IllegalArgumentException e) {\n Utils.debugLog(TAG, e.getMessage());\n ACRA.getErrorReporter().handleException(e, false);\n return;\n }\n }\n }\n } else if (ACTION_DELETE.equals(action)) {\n Log.i(TAG, \"Marking \" + packageName + \" as no longer installed\");\n deleteAppFromDb(this, packageName);\n }\n notifyEvents.onNext(null);\n }\n\n \/**\n * This class will either have received an intent from the {@link InstalledAppProviderService}\n * itself, while iterating over installed apps, or from a {@link Intent#ACTION_PACKAGE_ADDED}\n * broadcast. In the first case, it will already have a {@link PackageInfo} for us. However if\n * it is from the later case, we'll need to query the {@link PackageManager} ourselves to get\n * this info.\n *

\n * Can still return null, as there is potentially race conditions to do with uninstalling apps\n * such that querying the {@link PackageManager} for a given package may throw an exception.\n *\/\n @Nullable\n private PackageInfo getPackageInfo(Intent intent, String packageName) {\n PackageInfo packageInfo = intent.getParcelableExtra(EXTRA_PACKAGE_INFO);\n if (packageInfo != null) {\n return packageInfo;\n }\n\n try {\n return getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n \/**\n * @param hash Although the has could be calculated within this function, it is helpful to inject\n * the hash so as to be able to use this method during testing. Otherwise, the\n * hashing method will try to hash a non-existent .apk file and try to insert NULL\n * into the database when under test.\n *\/\n static void insertAppIntoDb(Context context, PackageInfo packageInfo, String hashType, String hash) {\n Uri uri = InstalledAppProvider.getContentUri();\n ContentValues contentValues = new ContentValues();\n contentValues.put(InstalledAppTable.Cols.PACKAGE_NAME, packageInfo.packageName);\n contentValues.put(InstalledAppTable.Cols.VERSION_CODE, packageInfo.versionCode);\n contentValues.put(InstalledAppTable.Cols.VERSION_NAME, packageInfo.versionName);\n contentValues.put(InstalledAppTable.Cols.APPLICATION_LABEL,\n InstalledAppProvider.getApplicationLabel(context, packageInfo.packageName));\n contentValues.put(InstalledAppTable.Cols.SIGNATURE, getPackageSig(packageInfo));\n contentValues.put(InstalledAppTable.Cols.LAST_UPDATE_TIME, packageInfo.lastUpdateTime);\n\n contentValues.put(InstalledAppTable.Cols.HASH_TYPE, hashType);\n contentValues.put(InstalledAppTable.Cols.HASH, hash);\n\n context.getContentResolver().insert(uri, contentValues);\n }\n\n static void deleteAppFromDb(Context context, String packageName) {\n Uri uri = InstalledAppProvider.getAppUri(packageName);\n context.getContentResolver().delete(uri, null, null);\n }\n\n private static String getPackageSig(PackageInfo info) {\n if (info == null || info.signatures == null || info.signatures.length < 1) {\n return \"\";\n }\n Signature sig = info.signatures[0];\n String sigHash = \"\";\n try {\n Hasher hash = new Hasher(\"MD5\", sig.toCharsString().getBytes());\n sigHash = hash.getHash();\n } catch (NoSuchAlgorithmException e) {\n \/\/ ignore\n }\n return sigHash;\n }\n\n}\n\n### Response:\n```java","base_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nRewrite the given java program to optimize and improve the frame rate. Write the entire code and no other text:\npackage org.fdroid.fdroid.data;\n\nimport android.app.IntentService;\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.Signature;\nimport android.net.Uri;\nimport android.os.Process;\nimport android.support.annotation.Nullable;\nimport android.util.Log;\n\nimport org.acra.ACRA;\nimport org.fdroid.fdroid.Hasher;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Schema.InstalledAppTable;\n\nimport java.io.File;\nimport java.io.FilenameFilter;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.List;\nimport java.util.Map;\n\nimport rx.functions.Action1;\nimport rx.schedulers.Schedulers;\nimport rx.subjects.PublishSubject;\n\n\/**\n * Handles all updates to {@link InstalledAppProvider}, whether checking the contents\n * versus what Android says is installed, or processing {@link Intent}s that come\n * from {@link android.content.BroadcastReceiver}s for {@link Intent#ACTION_PACKAGE_ADDED}\n * and {@link Intent#ACTION_PACKAGE_REMOVED}\n * \n * Since {@link android.content.ContentProvider#insert(Uri, ContentValues)} does not check\n * for duplicate records, it is entirely the job of this service to ensure that it is not\n * inserting duplicate versions of the same installed APK. On that note,\n * {@link #insertAppIntoDb(Context, PackageInfo, String, String)} and\n * {@link #deleteAppFromDb(Context, String)} are both static methods to enable easy testing\n * of this stuff.\n *\/\npublic class InstalledAppProviderService extends IntentService {\n private static final String TAG = \"InstalledAppProviderSer\";\n\n private static final String ACTION_INSERT = \"org.fdroid.fdroid.data.action.INSERT\";\n private static final String ACTION_DELETE = \"org.fdroid.fdroid.data.action.DELETE\";\n\n private static final String EXTRA_PACKAGE_INFO = \"org.fdroid.fdroid.data.extra.PACKAGE_INFO\";\n\n \/**\n * This is for notifing the users of this {@link android.content.ContentProvider}\n * that the contents has changed. Since {@link Intent}s can come in slow\n * or fast, and this can trigger a lot of UI updates, the actual\n * notifications are rate limited to one per second.\n *\/\n private PublishSubject notifyEvents;\n\n public InstalledAppProviderService() {\n super(\"InstalledAppProviderService\");\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n notifyEvents = PublishSubject.create();\n notifyEvents\n .subscribeOn(Schedulers.newThread())\n .subscribe(new Action1() {\n @Override\n public void call(Void voidArg) {\n Utils.debugLog(TAG, \"Notifying content providers (so they can update the relevant views).\");\n getContentResolver().notifyChange(AppProvider.getContentUri(), null);\n getContentResolver().notifyChange(ApkProvider.getContentUri(), null);\n }\n });\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, PackageInfo packageInfo) {\n insert(context, Utils.getPackageUri(packageInfo.packageName), packageInfo);\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, Uri uri) {\n insert(context, uri, null);\n }\n\n private static void insert(Context context, Uri uri, PackageInfo packageInfo) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_INSERT);\n intent.setData(uri);\n intent.putExtra(EXTRA_PACKAGE_INFO, packageInfo);\n context.startService(intent);\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, String packageName) {\n delete(context, Utils.getPackageUri(packageName));\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, Uri uri) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_DELETE);\n intent.setData(uri);\n context.startService(intent);\n }\n\n \/**\n * Make sure that {@link InstalledAppProvider}, our database of installed apps,\n * is in sync with what the {@link PackageManager} tells us is installed. Once\n * completed, the relevant {@link android.content.ContentProvider}s will be\n * notified of any changes to installed statuses.\n *

\n * The installed app cache could get out of sync, e.g. if F-Droid crashed\/ or\n * ran out of battery half way through responding to {@link Intent#ACTION_PACKAGE_ADDED}.\n * This method returns immediately, and will continue to work in an\n * {@link IntentService}. It doesn't really matter where we put this in the\n * bootstrap process, because it runs in its own thread, at the lowest priority:\n * {@link Process#THREAD_PRIORITY_LOWEST}.\n *

\n * APKs installed in {@code \/system} will often have zeroed out timestamps, like\n * 2008-01-01 (ziptime) or 2009-01-01. So instead anything older than 2010 every\n * time since we have no way to know whether an APK wasn't changed as part of an\n * OTA update. An OTA update could change the APK without changing the\n * {@link PackageInfo#versionCode} or {@link PackageInfo#lastUpdateTime}.\n *\n * @see issue #819<\/a>\n *\/\n public static void compareToPackageManager(Context context) {\n Map cachedInfo = InstalledAppProvider.Helper.all(context);\n\n List packageInfoList = context.getPackageManager()\n .getInstalledPackages(PackageManager.GET_SIGNATURES);\n for (PackageInfo packageInfo : packageInfoList) {\n if (cachedInfo.containsKey(packageInfo.packageName)) {\n if (packageInfo.lastUpdateTime < 1262300400000L \/\/ 2010-01-01 00:00\n || packageInfo.lastUpdateTime > cachedInfo.get(packageInfo.packageName)) {\n insert(context, packageInfo);\n }\n cachedInfo.remove(packageInfo.packageName);\n } else {\n insert(context, packageInfo);\n }\n }\n\n for (String packageName : cachedInfo.keySet()) {\n delete(context, packageName);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n if (intent == null) {\n return;\n }\n\n String packageName = intent.getData().getSchemeSpecificPart();\n final String action = intent.getAction();\n if (ACTION_INSERT.equals(action)) {\n PackageInfo packageInfo = getPackageInfo(intent, packageName);\n if (packageInfo != null) {\n Log.i(TAG, \"Marking \" + packageName + \" as installed\");\n File apk = new File(packageInfo.applicationInfo.publicSourceDir);\n if (apk.isDirectory()) {\n FilenameFilter filter = new FilenameFilter() {\n @Override\n public boolean accept(File dir, String name) {\n return name.endsWith(\".apk\");\n }\n };\n File[] files = apk.listFiles(filter);\n if (files == null) {\n String msg = packageName + \" sourceDir has no APKs: \"\n + apk.getAbsolutePath();\n Utils.debugLog(TAG, msg);\n ACRA.getErrorReporter().handleException(new IllegalArgumentException(msg), false);\n return;\n }\n apk = files[0];\n }\n if (apk.exists() && apk.canRead()) {\n try {\n String hashType = \"sha256\";\n String hash = Utils.getBinaryHash(apk, hashType);\n insertAppIntoDb(this, packageInfo, hashType, hash);\n } catch (IllegalArgumentException e) {\n Utils.debugLog(TAG, e.getMessage());\n ACRA.getErrorReporter().handleException(e, false);\n return;\n }\n }\n }\n } else if (ACTION_DELETE.equals(action)) {\n Log.i(TAG, \"Marking \" + packageName + \" as no longer installed\");\n deleteAppFromDb(this, packageName);\n }\n notifyEvents.onNext(null);\n }\n\n \/**\n * This class will either have received an intent from the {@link InstalledAppProviderService}\n * itself, while iterating over installed apps, or from a {@link Intent#ACTION_PACKAGE_ADDED}\n * broadcast. In the first case, it will already have a {@link PackageInfo} for us. However if\n * it is from the later case, we'll need to query the {@link PackageManager} ourselves to get\n * this info.\n *

\n * Can still return null, as there is potentially race conditions to do with uninstalling apps\n * such that querying the {@link PackageManager} for a given package may throw an exception.\n *\/\n @Nullable\n private PackageInfo getPackageInfo(Intent intent, String packageName) {\n PackageInfo packageInfo = intent.getParcelableExtra(EXTRA_PACKAGE_INFO);\n if (packageInfo != null) {\n return packageInfo;\n }\n\n try {\n return getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n \/**\n * @param hash Although the has could be calculated within this function, it is helpful to inject\n * the hash so as to be able to use this method during testing. Otherwise, the\n * hashing method will try to hash a non-existent .apk file and try to insert NULL\n * into the database when under test.\n *\/\n static void insertAppIntoDb(Context context, PackageInfo packageInfo, String hashType, String hash) {\n Uri uri = InstalledAppProvider.getContentUri();\n ContentValues contentValues = new ContentValues();\n contentValues.put(InstalledAppTable.Cols.PACKAGE_NAME, packageInfo.packageName);\n contentValues.put(InstalledAppTable.Cols.VERSION_CODE, packageInfo.versionCode);\n contentValues.put(InstalledAppTable.Cols.VERSION_NAME, packageInfo.versionName);\n contentValues.put(InstalledAppTable.Cols.APPLICATION_LABEL,\n InstalledAppProvider.getApplicationLabel(context, packageInfo.packageName));\n contentValues.put(InstalledAppTable.Cols.SIGNATURE, getPackageSig(packageInfo));\n contentValues.put(InstalledAppTable.Cols.LAST_UPDATE_TIME, packageInfo.lastUpdateTime);\n\n contentValues.put(InstalledAppTable.Cols.HASH_TYPE, hashType);\n contentValues.put(InstalledAppTable.Cols.HASH, hash);\n\n context.getContentResolver().insert(uri, contentValues);\n }\n\n static void deleteAppFromDb(Context context, String packageName) {\n Uri uri = InstalledAppProvider.getAppUri(packageName);\n context.getContentResolver().delete(uri, null, null);\n }\n\n private static String getPackageSig(PackageInfo info) {\n if (info == null || info.signatures == null || info.signatures.length < 1) {\n return \"\";\n }\n Signature sig = info.signatures[0];\n String sigHash = \"\";\n try {\n Hasher hash = new Hasher(\"MD5\", sig.toCharsString().getBytes());\n sigHash = hash.getHash();\n } catch (NoSuchAlgorithmException e) {\n \/\/ ignore\n }\n return sigHash;\n }\n\n}\n\n### Response:\n```java","coding_concepts":"Below is an instruction that describes a task. The instruction contains concepts formatted as a list of keyword and value pairs separated by newline. The list of concept keywords and their descriptions are:\n\n### Keywords:\n\n[in] What specific function or class to focus on to implement the required change(s).\n\n[+] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to USE or ADD to implement the required change(s)\n\n[-] What specific library, programming or data structure or design concept, or programmer-defined construct in the code to NOT USE or REMOVE to implement the required change(s)\n\n[implement] What specific function to implement in the class of interest\n\n[override] What specific function of the parent class to override and implement in the class of interest\n\n[hint] Full or partial textual description of the idea to implement\n\nWrite a response that appropriately completes the request.\n\n### Instruction:\nBunch together notifications in the code to prevent flickering in the UI and improve bandwidth usage of the android application. Write the entire code and no other text in the response.\n\n### Concepts:\n[+] java.util.concurrent.TimeUnit\n[+] PublishSubject packageChangeNotifier\n[-] PublishSubject notifyEvents\n[in] onCreate function\n[in] onHandleIntent function\n[hint] general events (e.g., 'some misc apps in the database were changed') should be 'debounced' for 1 second. However, also emit a more 'specific package org.blah.com was changed' instantly. \n\n### Given program:\n```java\npackage org.fdroid.fdroid.data;\n\nimport android.app.IntentService;\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.content.pm.PackageInfo;\nimport android.content.pm.PackageManager;\nimport android.content.pm.Signature;\nimport android.net.Uri;\nimport android.os.Process;\nimport android.support.annotation.Nullable;\nimport android.util.Log;\n\nimport org.acra.ACRA;\nimport org.fdroid.fdroid.Hasher;\nimport org.fdroid.fdroid.Utils;\nimport org.fdroid.fdroid.data.Schema.InstalledAppTable;\n\nimport java.io.File;\nimport java.io.FilenameFilter;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.List;\nimport java.util.Map;\n\nimport rx.functions.Action1;\nimport rx.schedulers.Schedulers;\nimport rx.subjects.PublishSubject;\n\n\/**\n * Handles all updates to {@link InstalledAppProvider}, whether checking the contents\n * versus what Android says is installed, or processing {@link Intent}s that come\n * from {@link android.content.BroadcastReceiver}s for {@link Intent#ACTION_PACKAGE_ADDED}\n * and {@link Intent#ACTION_PACKAGE_REMOVED}\n * \n * Since {@link android.content.ContentProvider#insert(Uri, ContentValues)} does not check\n * for duplicate records, it is entirely the job of this service to ensure that it is not\n * inserting duplicate versions of the same installed APK. On that note,\n * {@link #insertAppIntoDb(Context, PackageInfo, String, String)} and\n * {@link #deleteAppFromDb(Context, String)} are both static methods to enable easy testing\n * of this stuff.\n *\/\npublic class InstalledAppProviderService extends IntentService {\n private static final String TAG = \"InstalledAppProviderSer\";\n\n private static final String ACTION_INSERT = \"org.fdroid.fdroid.data.action.INSERT\";\n private static final String ACTION_DELETE = \"org.fdroid.fdroid.data.action.DELETE\";\n\n private static final String EXTRA_PACKAGE_INFO = \"org.fdroid.fdroid.data.extra.PACKAGE_INFO\";\n\n \/**\n * This is for notifing the users of this {@link android.content.ContentProvider}\n * that the contents has changed. Since {@link Intent}s can come in slow\n * or fast, and this can trigger a lot of UI updates, the actual\n * notifications are rate limited to one per second.\n *\/\n private PublishSubject notifyEvents;\n\n public InstalledAppProviderService() {\n super(\"InstalledAppProviderService\");\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n notifyEvents = PublishSubject.create();\n notifyEvents\n .subscribeOn(Schedulers.newThread())\n .subscribe(new Action1() {\n @Override\n public void call(Void voidArg) {\n Utils.debugLog(TAG, \"Notifying content providers (so they can update the relevant views).\");\n getContentResolver().notifyChange(AppProvider.getContentUri(), null);\n getContentResolver().notifyChange(ApkProvider.getContentUri(), null);\n }\n });\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, PackageInfo packageInfo) {\n insert(context, Utils.getPackageUri(packageInfo.packageName), packageInfo);\n }\n\n \/**\n * Inserts an app into {@link InstalledAppProvider} based on a {@code package:} {@link Uri}.\n * This has no checks for whether it is inserting an exact duplicate, whatever is provided\n * will be inserted.\n *\/\n public static void insert(Context context, Uri uri) {\n insert(context, uri, null);\n }\n\n private static void insert(Context context, Uri uri, PackageInfo packageInfo) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_INSERT);\n intent.setData(uri);\n intent.putExtra(EXTRA_PACKAGE_INFO, packageInfo);\n context.startService(intent);\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, String packageName) {\n delete(context, Utils.getPackageUri(packageName));\n }\n\n \/**\n * Deletes an app from {@link InstalledAppProvider} based on a {@code package:} {@link Uri}\n *\/\n public static void delete(Context context, Uri uri) {\n Intent intent = new Intent(context, InstalledAppProviderService.class);\n intent.setAction(ACTION_DELETE);\n intent.setData(uri);\n context.startService(intent);\n }\n\n \/**\n * Make sure that {@link InstalledAppProvider}, our database of installed apps,\n * is in sync with what the {@link PackageManager} tells us is installed. Once\n * completed, the relevant {@link android.content.ContentProvider}s will be\n * notified of any changes to installed statuses.\n *

\n * The installed app cache could get out of sync, e.g. if F-Droid crashed\/ or\n * ran out of battery half way through responding to {@link Intent#ACTION_PACKAGE_ADDED}.\n * This method returns immediately, and will continue to work in an\n * {@link IntentService}. It doesn't really matter where we put this in the\n * bootstrap process, because it runs in its own thread, at the lowest priority:\n * {@link Process#THREAD_PRIORITY_LOWEST}.\n *

\n * APKs installed in {@code \/system} will often have zeroed out timestamps, like\n * 2008-01-01 (ziptime) or 2009-01-01. So instead anything older than 2010 every\n * time since we have no way to know whether an APK wasn't changed as part of an\n * OTA update. An OTA update could change the APK without changing the\n * {@link PackageInfo#versionCode} or {@link PackageInfo#lastUpdateTime}.\n *\n * @see issue #819<\/a>\n *\/\n public static void compareToPackageManager(Context context) {\n Map cachedInfo = InstalledAppProvider.Helper.all(context);\n\n List packageInfoList = context.getPackageManager()\n .getInstalledPackages(PackageManager.GET_SIGNATURES);\n for (PackageInfo packageInfo : packageInfoList) {\n if (cachedInfo.containsKey(packageInfo.packageName)) {\n if (packageInfo.lastUpdateTime < 1262300400000L \/\/ 2010-01-01 00:00\n || packageInfo.lastUpdateTime > cachedInfo.get(packageInfo.packageName)) {\n insert(context, packageInfo);\n }\n cachedInfo.remove(packageInfo.packageName);\n } else {\n insert(context, packageInfo);\n }\n }\n\n for (String packageName : cachedInfo.keySet()) {\n delete(context, packageName);\n }\n }\n\n @Override\n protected void onHandleIntent(Intent intent) {\n Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);\n if (intent == null) {\n return;\n }\n\n String packageName = intent.getData().getSchemeSpecificPart();\n final String action = intent.getAction();\n if (ACTION_INSERT.equals(action)) {\n PackageInfo packageInfo = getPackageInfo(intent, packageName);\n if (packageInfo != null) {\n Log.i(TAG, \"Marking \" + packageName + \" as installed\");\n File apk = new File(packageInfo.applicationInfo.publicSourceDir);\n if (apk.isDirectory()) {\n FilenameFilter filter = new FilenameFilter() {\n @Override\n public boolean accept(File dir, String name) {\n return name.endsWith(\".apk\");\n }\n };\n File[] files = apk.listFiles(filter);\n if (files == null) {\n String msg = packageName + \" sourceDir has no APKs: \"\n + apk.getAbsolutePath();\n Utils.debugLog(TAG, msg);\n ACRA.getErrorReporter().handleException(new IllegalArgumentException(msg), false);\n return;\n }\n apk = files[0];\n }\n if (apk.exists() && apk.canRead()) {\n try {\n String hashType = \"sha256\";\n String hash = Utils.getBinaryHash(apk, hashType);\n insertAppIntoDb(this, packageInfo, hashType, hash);\n } catch (IllegalArgumentException e) {\n Utils.debugLog(TAG, e.getMessage());\n ACRA.getErrorReporter().handleException(e, false);\n return;\n }\n }\n }\n } else if (ACTION_DELETE.equals(action)) {\n Log.i(TAG, \"Marking \" + packageName + \" as no longer installed\");\n deleteAppFromDb(this, packageName);\n }\n notifyEvents.onNext(null);\n }\n\n \/**\n * This class will either have received an intent from the {@link InstalledAppProviderService}\n * itself, while iterating over installed apps, or from a {@link Intent#ACTION_PACKAGE_ADDED}\n * broadcast. In the first case, it will already have a {@link PackageInfo} for us. However if\n * it is from the later case, we'll need to query the {@link PackageManager} ourselves to get\n * this info.\n *

\n * Can still return null, as there is potentially race conditions to do with uninstalling apps\n * such that querying the {@link PackageManager} for a given package may throw an exception.\n *\/\n @Nullable\n private PackageInfo getPackageInfo(Intent intent, String packageName) {\n PackageInfo packageInfo = intent.getParcelableExtra(EXTRA_PACKAGE_INFO);\n if (packageInfo != null) {\n return packageInfo;\n }\n\n try {\n return getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);\n } catch (PackageManager.NameNotFoundException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n \/**\n * @param hash Although the has could be calculated within this function, it is helpful to inject\n * the hash so as to be able to use this method during testing. Otherwise, the\n * hashing method will try to hash a non-existent .apk file and try to insert NULL\n * into the database when under test.\n *\/\n static void insertAppIntoDb(Context context, PackageInfo packageInfo, String hashType, String hash) {\n Uri uri = InstalledAppProvider.getContentUri();\n ContentValues contentValues = new ContentValues();\n contentValues.put(InstalledAppTable.Cols.PACKAGE_NAME, packageInfo.packageName);\n contentValues.put(InstalledAppTable.Cols.VERSION_CODE, packageInfo.versionCode);\n contentValues.put(InstalledAppTable.Cols.VERSION_NAME, packageInfo.versionName);\n contentValues.put(InstalledAppTable.Cols.APPLICATION_LABEL,\n InstalledAppProvider.getApplicationLabel(context, packageInfo.packageName));\n contentValues.put(InstalledAppTable.Cols.SIGNATURE, getPackageSig(packageInfo));\n contentValues.put(InstalledAppTable.Cols.LAST_UPDATE_TIME, packageInfo.lastUpdateTime);\n\n contentValues.put(InstalledAppTable.Cols.HASH_TYPE, hashType);\n contentValues.put(InstalledAppTable.Cols.HASH, hash);\n\n context.getContentResolver().insert(uri, contentValues);\n }\n\n static void deleteAppFromDb(Context context, String packageName) {\n Uri uri = InstalledAppProvider.getAppUri(packageName);\n context.getContentResolver().delete(uri, null, null);\n }\n\n private static String getPackageSig(PackageInfo info) {\n if (info == null || info.signatures == null || info.signatures.length < 1) {\n return \"\";\n }\n Signature sig = info.signatures[0];\n String sigHash = \"\";\n try {\n Hasher hash = new Hasher(\"MD5\", sig.toCharsString().getBytes());\n sigHash = hash.getHash();\n } catch (NoSuchAlgorithmException e) {\n \/\/ ignore\n }\n return sigHash;\n }\n\n}\n```\n\n### Response:\n```java","classification_left_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Map;\n\n\npublic class HostActivity extends Activity implements HostAsyncResponse {\n\n private static final String TAG = \"HostActivity\";\n\n private Wireless wifi;\n private Host host = new Host();\n private TextView hostNameLabel;\n private String hostName;\n private String hostIp;\n private String hostMac;\n private ArrayAdapter adapter;\n private ArrayList ports = new ArrayList<>();\n private ProgressDialog scanProgressDialog;\n private Dialog portRangeDialog;\n private int scanProgress;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_host);\n\n TextView hostIpLabel = (TextView) findViewById(R.id.hostIpLabel);\n this.hostNameLabel = (TextView) findViewById(R.id.hostName);\n TextView hostMacVendor = (TextView) findViewById(R.id.hostMacVendor);\n Button scanWellKnownPortsButton = (Button) findViewById(R.id.scanWellKnownPorts);\n Button scanPortRangeButton = (Button) findViewById(R.id.scanPortRange);\n ListView portList = (ListView) findViewById(R.id.portList);\n TextView hostMacLabel = (TextView) findViewById(R.id.hostMac);\n\n if(savedInstanceState != null) {\n this.hostIp = savedInstanceState.getString(\"hostIp\");\n this.hostMac = savedInstanceState.getString(\"hostMac\");\n this.hostName = savedInstanceState.getString(\"hostName\");\n this.ports = savedInstanceState.getStringArrayList(\"ports\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n else if(savedInstanceState == null) {\n Bundle extras = getIntent().getExtras();\n this.hostIp = extras.getString(\"HOST\");\n this.hostMac = extras.getString(\"MAC\");\n\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(adapter);\n }\n\n this.wifi = new Wireless(this);\n\n this.host.getHostname(this.hostIp, this);\n\n String mac = this.hostMac.replace(\":\", \"\");\n mac = mac.substring(0, 6);\n\n hostMacVendor.setText(this.host.getMacVendor(mac, this));\n\n hostIpLabel.setText(this.hostIp);\n hostMacLabel.setText(this.hostMac);\n\n scanWellKnownPortsButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning well known ports\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Well Known Ports\");\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(1024);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, 1, 1024, HostActivity.this);\n }\n });\n\n scanPortRangeButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning a port range\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.portRangeDialog = new Dialog(HostActivity.this);\n portRangeDialog.setTitle(\"Select Port Range\");\n portRangeDialog.setContentView(R.layout.port_range);\n portRangeDialog.show();\n\n final NumberPicker portRangePickerStart = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStart);\n final NumberPicker portRangePickerStop = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStop);\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n\n portRangePickerStart.setMinValue(1);\n portRangePickerStart.setMaxValue(65535);\n portRangePickerStart.setWrapSelectorWheel(false);\n portRangePickerStop.setMinValue(1);\n portRangePickerStop.setMaxValue(65535);\n portRangePickerStop.setWrapSelectorWheel(false);\n\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n int startPort = portRangePickerStart.getValue();\n int stopPort = portRangePickerStop.getValue();\n\n if((startPort - stopPort >= 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, startPort, stopPort, HostActivity.this);\n }\n });\n }\n });\n\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putString(\"hostIp\", this.hostIp);\n savedState.putString(\"hostName\", this.hostName);\n savedState.putString(\"hostMac\", this.hostMac);\n savedState.putStringArrayList(\"ports\", this.ports);\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if(this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n this.scanProgress += output;\n if(scanProgressDialog != null && scanProgressDialog.isShowing() && this.scanProgress % 50 == 0) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n scanProgressDialog.setProgress(scanProgress);\n }\n });\n }\n }\n\n \/**\n * Delegate to determine if the progress dialog should be dismissed or not\n *\n * @param output True if the dialog should be dismissed\n *\/\n @Override\n public void processFinish(boolean output) {\n if(output && this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n this.scanProgress = 0;\n }\n if(output && this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(Map output) {\n try {\n int scannedPort = output.keySet().iterator().next();\n BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open(\"ports.csv\")));\n String line;\n String item = String.valueOf(scannedPort);\n\n while((line = reader.readLine()) != null) {\n String[] portInfo = line.split(\",\");\n String name;\n String port;\n\n if(portInfo.length > 2) {\n name = portInfo[0];\n port = portInfo[1];\n }\n else {\n name = \"unknown\";\n port = null;\n }\n\n if(scannedPort == Integer.parseInt(port)) {\n item = item + \" - \" + name;\n if(output.get(scannedPort) != null) {\n item += \" (\" + output.get(scannedPort) + \")\";\n }\n\n final String finalItem = item;\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ports.add(finalItem);\n Collections.sort(ports);\n adapter.notifyDataSetChanged();\n }\n });\n\n reader.close();\n break;\n }\n }\n }\n catch(IOException | NumberFormatException ignored) {\n }\n }\n\n \/**\n * Delegate to handle setting the hostname in the UI\n *\n * @param output Hostname\n *\/\n @Override\n public void processFinish(String output) {\n if(output != null) {\n this.hostNameLabel.setText(output);\n }\n else {\n this.hostNameLabel.setText(\"Couldn't get hostname\");\n }\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Map;\n\n\npublic class HostActivity extends Activity implements HostAsyncResponse {\n\n private static final String TAG = \"HostActivity\";\n\n private Wireless wifi;\n private Host host = new Host();\n private TextView hostNameLabel;\n private String hostName;\n private String hostIp;\n private String hostMac;\n private ArrayAdapter adapter;\n private ArrayList ports = new ArrayList<>();\n private ProgressDialog scanProgressDialog;\n private Dialog portRangeDialog;\n private int scanProgress;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_host);\n\n TextView hostIpLabel = (TextView) findViewById(R.id.hostIpLabel);\n this.hostNameLabel = (TextView) findViewById(R.id.hostName);\n TextView hostMacVendor = (TextView) findViewById(R.id.hostMacVendor);\n Button scanWellKnownPortsButton = (Button) findViewById(R.id.scanWellKnownPorts);\n Button scanPortRangeButton = (Button) findViewById(R.id.scanPortRange);\n ListView portList = (ListView) findViewById(R.id.portList);\n TextView hostMacLabel = (TextView) findViewById(R.id.hostMac);\n\n if(savedInstanceState != null) {\n this.hostIp = savedInstanceState.getString(\"hostIp\");\n this.hostMac = savedInstanceState.getString(\"hostMac\");\n this.hostName = savedInstanceState.getString(\"hostName\");\n this.ports = savedInstanceState.getStringArrayList(\"ports\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n else if(savedInstanceState == null) {\n Bundle extras = getIntent().getExtras();\n this.hostIp = extras.getString(\"HOST\");\n this.hostMac = extras.getString(\"MAC\");\n\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(adapter);\n }\n\n this.wifi = new Wireless(this);\n\n this.host.getHostname(this.hostIp, this);\n\n String mac = this.hostMac.replace(\":\", \"\");\n mac = mac.substring(0, 6);\n\n hostMacVendor.setText(this.host.getMacVendor(mac, this));\n\n hostIpLabel.setText(this.hostIp);\n hostMacLabel.setText(this.hostMac);\n\n scanWellKnownPortsButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning well known ports\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Well Known Ports\");\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(1024);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, 1, 1024, HostActivity.this);\n }\n });\n\n scanPortRangeButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning a port range\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.portRangeDialog = new Dialog(HostActivity.this);\n portRangeDialog.setTitle(\"Select Port Range\");\n portRangeDialog.setContentView(R.layout.port_range);\n portRangeDialog.show();\n\n final NumberPicker portRangePickerStart = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStart);\n final NumberPicker portRangePickerStop = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStop);\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n\n portRangePickerStart.setMinValue(1);\n portRangePickerStart.setMaxValue(65535);\n portRangePickerStart.setWrapSelectorWheel(false);\n portRangePickerStop.setMinValue(1);\n portRangePickerStop.setMaxValue(65535);\n portRangePickerStop.setWrapSelectorWheel(false);\n\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n int startPort = portRangePickerStart.getValue();\n int stopPort = portRangePickerStop.getValue();\n\n if((startPort - stopPort >= 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, startPort, stopPort, HostActivity.this);\n }\n });\n }\n });\n\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putString(\"hostIp\", this.hostIp);\n savedState.putString(\"hostName\", this.hostName);\n savedState.putString(\"hostMac\", this.hostMac);\n savedState.putStringArrayList(\"ports\", this.ports);\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if(this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n this.scanProgress += output;\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if(scanProgressDialog != null && scanProgressDialog.isShowing()) {\n if(scanProgress % 50 == 0) {\n scanProgressDialog.setProgress(scanProgress);\n }\n }\n }\n });\n }\n\n \/**\n * Delegate to determine if the progress dialog should be dismissed or not\n *\n * @param output True if the dialog should be dismissed\n *\/\n @Override\n public void processFinish(boolean output) {\n if(output && this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n this.scanProgress = 0;\n }\n if(output && this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(Map output) {\n try {\n int scannedPort = output.keySet().iterator().next();\n BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open(\"ports.csv\")));\n String line;\n String item = String.valueOf(scannedPort);\n\n while((line = reader.readLine()) != null) {\n String[] portInfo = line.split(\",\");\n String name;\n String port;\n\n if(portInfo.length > 2) {\n name = portInfo[0];\n port = portInfo[1];\n }\n else {\n name = \"unknown\";\n port = null;\n }\n\n if(scannedPort == Integer.parseInt(port)) {\n item = item + \" - \" + name;\n if(output.get(scannedPort) != null) {\n item += \" (\" + output.get(scannedPort) + \")\";\n }\n\n final String finalItem = item;\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ports.add(finalItem);\n Collections.sort(ports);\n adapter.notifyDataSetChanged();\n }\n });\n\n reader.close();\n break;\n }\n }\n }\n catch(IOException | NumberFormatException ignored) {\n }\n }\n\n \/**\n * Delegate to handle setting the hostname in the UI\n *\n * @param output Hostname\n *\/\n @Override\n public void processFinish(String output) {\n if(output != null) {\n this.hostNameLabel.setText(output);\n }\n else {\n this.hostNameLabel.setText(\"Couldn't get hostname\");\n }\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_left_label":"A","classification_right_prompt":"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n### Instruction:\n\nOnly one of the two code snippets has a lower execution time.\n\nCode-A:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Map;\n\n\npublic class HostActivity extends Activity implements HostAsyncResponse {\n\n private static final String TAG = \"HostActivity\";\n\n private Wireless wifi;\n private Host host = new Host();\n private TextView hostNameLabel;\n private String hostName;\n private String hostIp;\n private String hostMac;\n private ArrayAdapter adapter;\n private ArrayList ports = new ArrayList<>();\n private ProgressDialog scanProgressDialog;\n private Dialog portRangeDialog;\n private int scanProgress;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_host);\n\n TextView hostIpLabel = (TextView) findViewById(R.id.hostIpLabel);\n this.hostNameLabel = (TextView) findViewById(R.id.hostName);\n TextView hostMacVendor = (TextView) findViewById(R.id.hostMacVendor);\n Button scanWellKnownPortsButton = (Button) findViewById(R.id.scanWellKnownPorts);\n Button scanPortRangeButton = (Button) findViewById(R.id.scanPortRange);\n ListView portList = (ListView) findViewById(R.id.portList);\n TextView hostMacLabel = (TextView) findViewById(R.id.hostMac);\n\n if(savedInstanceState != null) {\n this.hostIp = savedInstanceState.getString(\"hostIp\");\n this.hostMac = savedInstanceState.getString(\"hostMac\");\n this.hostName = savedInstanceState.getString(\"hostName\");\n this.ports = savedInstanceState.getStringArrayList(\"ports\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n else if(savedInstanceState == null) {\n Bundle extras = getIntent().getExtras();\n this.hostIp = extras.getString(\"HOST\");\n this.hostMac = extras.getString(\"MAC\");\n\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(adapter);\n }\n\n this.wifi = new Wireless(this);\n\n this.host.getHostname(this.hostIp, this);\n\n String mac = this.hostMac.replace(\":\", \"\");\n mac = mac.substring(0, 6);\n\n hostMacVendor.setText(this.host.getMacVendor(mac, this));\n\n hostIpLabel.setText(this.hostIp);\n hostMacLabel.setText(this.hostMac);\n\n scanWellKnownPortsButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning well known ports\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Well Known Ports\");\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(1024);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, 1, 1024, HostActivity.this);\n }\n });\n\n scanPortRangeButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning a port range\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.portRangeDialog = new Dialog(HostActivity.this);\n portRangeDialog.setTitle(\"Select Port Range\");\n portRangeDialog.setContentView(R.layout.port_range);\n portRangeDialog.show();\n\n final NumberPicker portRangePickerStart = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStart);\n final NumberPicker portRangePickerStop = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStop);\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n\n portRangePickerStart.setMinValue(1);\n portRangePickerStart.setMaxValue(65535);\n portRangePickerStart.setWrapSelectorWheel(false);\n portRangePickerStop.setMinValue(1);\n portRangePickerStop.setMaxValue(65535);\n portRangePickerStop.setWrapSelectorWheel(false);\n\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n int startPort = portRangePickerStart.getValue();\n int stopPort = portRangePickerStop.getValue();\n\n if((startPort - stopPort >= 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, startPort, stopPort, HostActivity.this);\n }\n });\n }\n });\n\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putString(\"hostIp\", this.hostIp);\n savedState.putString(\"hostName\", this.hostName);\n savedState.putString(\"hostMac\", this.hostMac);\n savedState.putStringArrayList(\"ports\", this.ports);\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if(this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n this.scanProgress += output;\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n if(scanProgressDialog != null && scanProgressDialog.isShowing()) {\n if(scanProgress % 50 == 0) {\n scanProgressDialog.setProgress(scanProgress);\n }\n }\n }\n });\n }\n\n \/**\n * Delegate to determine if the progress dialog should be dismissed or not\n *\n * @param output True if the dialog should be dismissed\n *\/\n @Override\n public void processFinish(boolean output) {\n if(output && this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n this.scanProgress = 0;\n }\n if(output && this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(Map output) {\n try {\n int scannedPort = output.keySet().iterator().next();\n BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open(\"ports.csv\")));\n String line;\n String item = String.valueOf(scannedPort);\n\n while((line = reader.readLine()) != null) {\n String[] portInfo = line.split(\",\");\n String name;\n String port;\n\n if(portInfo.length > 2) {\n name = portInfo[0];\n port = portInfo[1];\n }\n else {\n name = \"unknown\";\n port = null;\n }\n\n if(scannedPort == Integer.parseInt(port)) {\n item = item + \" - \" + name;\n if(output.get(scannedPort) != null) {\n item += \" (\" + output.get(scannedPort) + \")\";\n }\n\n final String finalItem = item;\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ports.add(finalItem);\n Collections.sort(ports);\n adapter.notifyDataSetChanged();\n }\n });\n\n reader.close();\n break;\n }\n }\n }\n catch(IOException | NumberFormatException ignored) {\n }\n }\n\n \/**\n * Delegate to handle setting the hostname in the UI\n *\n * @param output Hostname\n *\/\n @Override\n public void processFinish(String output) {\n if(output != null) {\n this.hostNameLabel.setText(output);\n }\n else {\n this.hostNameLabel.setText(\"Couldn't get hostname\");\n }\n }\n}\n\n\nCode-B:\npackage com.aaronjwood.portauthority.activity;\n\nimport android.app.Activity;\nimport android.app.Dialog;\nimport android.app.ProgressDialog;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.ListView;\nimport android.widget.NumberPicker;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\nimport com.aaronjwood.portauthority.R;\nimport com.aaronjwood.portauthority.network.Host;\nimport com.aaronjwood.portauthority.network.Wireless;\nimport com.aaronjwood.portauthority.response.HostAsyncResponse;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Map;\n\n\npublic class HostActivity extends Activity implements HostAsyncResponse {\n\n private static final String TAG = \"HostActivity\";\n\n private Wireless wifi;\n private Host host = new Host();\n private TextView hostNameLabel;\n private String hostName;\n private String hostIp;\n private String hostMac;\n private ArrayAdapter adapter;\n private ArrayList ports = new ArrayList<>();\n private ProgressDialog scanProgressDialog;\n private Dialog portRangeDialog;\n private int scanProgress;\n\n \/**\n * Activity created\n *\n * @param savedInstanceState Data from a saved state\n *\/\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_host);\n\n TextView hostIpLabel = (TextView) findViewById(R.id.hostIpLabel);\n this.hostNameLabel = (TextView) findViewById(R.id.hostName);\n TextView hostMacVendor = (TextView) findViewById(R.id.hostMacVendor);\n Button scanWellKnownPortsButton = (Button) findViewById(R.id.scanWellKnownPorts);\n Button scanPortRangeButton = (Button) findViewById(R.id.scanPortRange);\n ListView portList = (ListView) findViewById(R.id.portList);\n TextView hostMacLabel = (TextView) findViewById(R.id.hostMac);\n\n if(savedInstanceState != null) {\n this.hostIp = savedInstanceState.getString(\"hostIp\");\n this.hostMac = savedInstanceState.getString(\"hostMac\");\n this.hostName = savedInstanceState.getString(\"hostName\");\n this.ports = savedInstanceState.getStringArrayList(\"ports\");\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(this.adapter);\n this.adapter.notifyDataSetChanged();\n }\n else if(savedInstanceState == null) {\n Bundle extras = getIntent().getExtras();\n this.hostIp = extras.getString(\"HOST\");\n this.hostMac = extras.getString(\"MAC\");\n\n this.adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, this.ports);\n portList.setAdapter(adapter);\n }\n\n this.wifi = new Wireless(this);\n\n this.host.getHostname(this.hostIp, this);\n\n String mac = this.hostMac.replace(\":\", \"\");\n mac = mac.substring(0, 6);\n\n hostMacVendor.setText(this.host.getMacVendor(mac, this));\n\n hostIpLabel.setText(this.hostIp);\n hostMacLabel.setText(this.hostMac);\n\n scanWellKnownPortsButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning well known ports\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Well Known Ports\");\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(1024);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, 1, 1024, HostActivity.this);\n }\n });\n\n scanPortRangeButton.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for scanning a port range\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n if(!wifi.isConnected()) {\n Toast.makeText(getApplicationContext(), \"You're not connected to a network!\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.portRangeDialog = new Dialog(HostActivity.this);\n portRangeDialog.setTitle(\"Select Port Range\");\n portRangeDialog.setContentView(R.layout.port_range);\n portRangeDialog.show();\n\n final NumberPicker portRangePickerStart = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStart);\n final NumberPicker portRangePickerStop = (NumberPicker) portRangeDialog.findViewById(R.id.portRangePickerStop);\n Button startPortRangeScan = (Button) portRangeDialog.findViewById(R.id.startPortRangeScan);\n\n portRangePickerStart.setMinValue(1);\n portRangePickerStart.setMaxValue(65535);\n portRangePickerStart.setWrapSelectorWheel(false);\n portRangePickerStop.setMinValue(1);\n portRangePickerStop.setMaxValue(65535);\n portRangePickerStop.setWrapSelectorWheel(false);\n\n startPortRangeScan.setOnClickListener(new View.OnClickListener() {\n\n \/**\n * Click handler for starting a port range scan\n * @param v\n *\/\n @Override\n public void onClick(View v) {\n int startPort = portRangePickerStart.getValue();\n int stopPort = portRangePickerStop.getValue();\n\n if((startPort - stopPort >= 0)) {\n Toast.makeText(getApplicationContext(), \"Please pick a valid port range\", Toast.LENGTH_SHORT).show();\n return;\n }\n\n HostActivity.this.ports.clear();\n\n scanProgressDialog = new ProgressDialog(HostActivity.this);\n scanProgressDialog.setCancelable(false);\n scanProgressDialog.setTitle(\"Scanning Port \" + startPort + \" to \" + stopPort);\n scanProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n scanProgressDialog.setProgress(0);\n scanProgressDialog.setMax(stopPort - startPort + 1);\n scanProgressDialog.show();\n\n host.scanPorts(hostIp, startPort, stopPort, HostActivity.this);\n }\n });\n }\n });\n\n }\n\n \/**\n * Save the state of the activity\n *\n * @param savedState Data to save\n *\/\n @Override\n public void onSaveInstanceState(Bundle savedState) {\n super.onSaveInstanceState(savedState);\n\n savedState.putString(\"hostIp\", this.hostIp);\n savedState.putString(\"hostName\", this.hostName);\n savedState.putString(\"hostMac\", this.hostMac);\n savedState.putStringArrayList(\"ports\", this.ports);\n }\n\n \/**\n * Activity paused\n *\/\n @Override\n public void onPause() {\n super.onPause();\n\n if(this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n }\n if(this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n this.scanProgressDialog = null;\n this.portRangeDialog = null;\n }\n\n \/**\n * Delegate to handle incrementing the scan progress dialog\n *\n * @param output The amount of progress to increment\n *\/\n @Override\n public void processFinish(final int output) {\n this.scanProgress += output;\n if(scanProgressDialog != null && scanProgressDialog.isShowing() && this.scanProgress % 50 == 0) {\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n scanProgressDialog.setProgress(scanProgress);\n }\n });\n }\n }\n\n \/**\n * Delegate to determine if the progress dialog should be dismissed or not\n *\n * @param output True if the dialog should be dismissed\n *\/\n @Override\n public void processFinish(boolean output) {\n if(output && this.scanProgressDialog != null && this.scanProgressDialog.isShowing()) {\n this.scanProgressDialog.dismiss();\n this.scanProgress = 0;\n }\n if(output && this.portRangeDialog != null && this.portRangeDialog.isShowing()) {\n this.portRangeDialog.dismiss();\n }\n }\n\n \/**\n * Delegate to handle open ports\n *\n * @param output Contains the port number and associated banner (if any)\n *\/\n @Override\n public void processFinish(Map output) {\n try {\n int scannedPort = output.keySet().iterator().next();\n BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open(\"ports.csv\")));\n String line;\n String item = String.valueOf(scannedPort);\n\n while((line = reader.readLine()) != null) {\n String[] portInfo = line.split(\",\");\n String name;\n String port;\n\n if(portInfo.length > 2) {\n name = portInfo[0];\n port = portInfo[1];\n }\n else {\n name = \"unknown\";\n port = null;\n }\n\n if(scannedPort == Integer.parseInt(port)) {\n item = item + \" - \" + name;\n if(output.get(scannedPort) != null) {\n item += \" (\" + output.get(scannedPort) + \")\";\n }\n\n final String finalItem = item;\n runOnUiThread(new Runnable() {\n\n @Override\n public void run() {\n ports.add(finalItem);\n Collections.sort(ports);\n adapter.notifyDataSetChanged();\n }\n });\n\n reader.close();\n break;\n }\n }\n }\n catch(IOException | NumberFormatException ignored) {\n }\n }\n\n \/**\n * Delegate to handle setting the hostname in the UI\n *\n * @param output Hostname\n *\/\n @Override\n public void processFinish(String output) {\n if(output != null) {\n this.hostNameLabel.setText(output);\n }\n else {\n this.hostNameLabel.setText(\"Couldn't get hostname\");\n }\n }\n}\n\n\nPlease select the code snippet from Code-A or Code-B with a lower execution time utilization.\n\n### Response: Code-","classification_right_label":"B"}