id stringlengths 36 36 | text stringlengths 1 1.25M |
|---|---|
676740c9-bf5a-4ae1-8adb-e19921107713 | public void test1(){
String url="http://finance.sina.com.cn/realstock/company/sh600664/nc.shtml";
Document doc=null;
try {
doc = Jsoup.connect(url).get();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Elements td=doc.select("td");
System.out.println(doc);
} |
b3ea2723-46e9-472f-a31d-c7e4379c032b | public void test(){
String url = "http://money.finance.sina.com.cn/corp/go.php/vMS_MarketHistory/stockid/600664.phtml?year=2014&jidu=4";
System.out.println(url);
Document document=null;
try {
document = Jsoup.connect(url).get();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Elements stockdatas = document.select("table#FundHoldSharesTable").select("tr");
for(Element e : stockdatas){
String time;
double openPrice;
double highPrice;
double endPrice;
double lowPrice;
int dealCount;
int dealAmount;
Element tmp = e.select("td").select("a").first();
if(tmp != null){
List<String> infoList = new ArrayList<String>();
Elements infos = e.select("td");
for(Element info : infos){
String tmpMsg = info.text();
infoList.add(tmpMsg);
}
HisStockData hisData = new HisStockData();
time = infoList.get(0);
openPrice = Double.parseDouble(infoList.get(1));
highPrice = Double.parseDouble(infoList.get(2));
endPrice= Double.parseDouble(infoList.get(3));
lowPrice= Double.parseDouble(infoList.get(4));
dealCount= Integer.parseInt(infoList.get(5));
dealAmount = Integer.parseInt(infoList.get(6));
hisData.setTime(time);
hisData.setOpenPrice(openPrice);
hisData.setHighPrice(highPrice);
hisData.setEndPrice(endPrice);
hisData.setLowPrice(lowPrice);
hisData.setDealAmount(dealAmount);
hisData.setDealCount(dealCount);
System.out.println(hisData.toString());
}
}
} |
f94b2c2f-f2d1-4998-9952-ed60f02e740d | public static HttpsClientTestServer getSingleInstance() {
if (instance == null) {
instance = new HttpsClientTestServer();
}
return instance;
} |
ea7b7824-e265-4149-800d-7b2dd128786e | @Override
public boolean startServer() {
int times =
Integer.parseInt(VarManageServer.getSingleInstance().getVarStringValue("chongqing_times"));
long sleepTime = 0;
for (int i = 0; i < times; i++) {
long start = System.currentTimeMillis();
testConnection();
long cost=System.currentTimeMillis() - start;
logger.info("=========================消耗时间:" + cost);
sleepTime = 100000+Math.round(Math.random() * 60000);
logger.info("=========================sleepTime:" + sleepTime);
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// TODO Auto-generated method stub
this.isRunning = true;
return true;
} |
a68cb69e-bed3-4307-b357-02472fea0911 | public static void testConnection() {
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "debug");
// TODO Auto-generated method stub
String url = "https://wexpress-mobipay.ymcft.com:4431/MobilePay/MobilePayService.aspx";
String chongqingUrl = VarManageServer.getSingleInstance().getVarStringValue("chongqing_url");
if (StrFilter.hasValue(chongqingUrl)) {
url = chongqingUrl;
}
String charset = "utf-8";
HttpClient client = getHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
String xmlInfo =
"323A003E7CDCBA0177D5CC213B192DAE55<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<SERVICE>"
+ "<SYS_HEAD><TRAN_CODE>AM0003</TRAN_CODE><MER_CODE>30103005</MER_CODE>"
+ "<POS_CODE>10000001</POS_CODE><TRAN_DATE>20140418</TRAN_DATE>"
+ "<TRAN_TIME>102310</TRAN_TIME><TRAN_SEQ>00002001</TRAN_SEQ></SYS_HEAD>"
+ "<BODY>" + "<MER_ORDER>301030052</MER_ORDER>" + "<TRAN_AMT>123.09</TRAN_AMT>"
+ "<ACCT_NO>OD31234519</ACCT_NO>" + "<PAY_STAT>1</PAY_STAT>" + "</BODY>"
+ "</SERVICE>";
byte[] reqBytes = (byte[]) xmlInfo.getBytes(charset);
httpPost.setEntity(new InputStreamEntity(new ByteArrayInputStream(reqBytes), ContentType.create(
"application/xml", charset)));
httpPost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,
false);
HttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
byte[] result = EntityUtils.toByteArray(entity);
String receiveMsg = new String(result, charset);
logger.info("recieve:" + new String(receiveMsg.getBytes(charset), charset));
} catch (Exception ex) {
ex.printStackTrace();
}finally{
if(httpPost!=null){
httpPost.releaseConnection();
}
}
} |
1dc742d1-4588-4cbf-a57c-9cb1a08f74bc | private static HttpClient getHttpClient() {
try {
if (httpClient != null) {
return httpClient;
}
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string) {
}
public void checkServerTrusted(X509Certificate[] xcs, String string) {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory socketFactory =
new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
// 不校验域名
socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Scheme sch = new Scheme("https", 443, socketFactory);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(sch);
HttpParams params = new BasicHttpParams();
params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 600000);
params.setParameter(CoreConnectionPNames.SO_KEEPALIVE, 10000);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
// cm.setMaxTotal(100);
// cm.setDefaultMaxPerRoute(50);
httpClient = new DefaultHttpClient(cm, params);
} catch (Exception ex) {
ex.printStackTrace();
}
return httpClient;
} |
4143a944-5173-4d47-a551-3807d394ebdb | public void checkClientTrusted(X509Certificate[] xcs, String string) {
} |
5b2ba5c1-dc48-4286-b069-20f85bec2c79 | public void checkServerTrusted(X509Certificate[] xcs, String string) {
} |
323c44c3-2f35-4532-905e-8ab7669f02c4 | public X509Certificate[] getAcceptedIssuers() {
return null;
} |
e3aae259-cbf6-4fdd-aa4e-a203393d9472 | public static void main(String[] args) {
System.out.println(Math.round(Math.random() * 120000));
} |
ababd306-a262-4639-8f8b-1930cba64816 | public static HIBADbServer getSingleInstance()
{
if (instance == null)
{
instance = new HIBADbServer();
}
return instance;
} |
4c0af179-f7bc-4441-8cc1-90cbeda0efb2 | public boolean startServer()
{
return super.startServer();
} |
f05d5313-b4e6-4e02-8ec3-7c0b4e7a8a3e | public void stopServer()
{
super.stopServer();
} |
f284fa4f-5795-47be-90ed-34dddc8aa425 | public X509Certificate[] getAcceptedIssuers() {
return null;
} |
4315e355-e288-4c77-854f-f8f7b522e519 | public void checkClientTrusted(
X509Certificate[] certs, String authType) {
} |
7f3aa27d-4943-4ed8-aff5-358c74d12243 | public void checkServerTrusted(
X509Certificate[] certs, String authType) {
} |
1ac21c0c-3ed6-4bef-b899-95364f3c28f2 | @SuppressWarnings("deprecation")
public static String invokeGet(String url, Map<String, String> params, String encode, int connectTimeout,
int soTimeout) {
String responseString = null;
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(connectTimeout)
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectTimeout).build();
StringBuilder sb = new StringBuilder();
sb.append(url);
int i = 0;
for (Entry<String, String> entry : params.entrySet()) {
if (i == 0 && !url.contains("?")) {
sb.append("?");
} else {
sb.append("&");
}
sb.append(entry.getKey());
sb.append("=");
String value = entry.getValue();
try {
sb.append(URLEncoder.encode(value, "UTF-8"));
} catch (UnsupportedEncodingException e) {
logger.info("encode http get params error, value is "+value+ e.getMessage());
sb.append(URLEncoder.encode(value));
}
i++;
}
logger.info("[HttpUtils Get] begin invoke:" + sb.toString());
HttpGet get = new HttpGet(sb.toString());
get.setConfig(requestConfig);
try {
CloseableHttpResponse response = httpclient.execute(get);
try {
HttpEntity entity = response.getEntity();
try {
if(entity != null){
responseString = EntityUtils.toString(entity, encode);
}
} finally {
if(entity != null){
entity.getContent().close();
}
}
} catch (Exception e) {
logger.info(String.format("[HttpUtils Get]get response error, url:%s", sb.toString())+ e.getMessage());
return responseString;
} finally {
if(response != null){
response.close();
}
}
logger.info(String.format("[HttpUtils Get]Debug url:%s , response string %s:", sb.toString(), responseString));
} catch (SocketTimeoutException e) {
logger.info(String.format("[HttpUtils Get]invoke get timout error, url:%s", sb.toString())+ e.getMessage());
return responseString;
} catch (Exception e) {
logger.info(String.format("[HttpUtils Get]invoke get error, url:%s", sb.toString())+ e.getMessage());
} finally {
get.releaseConnection();
}
return responseString;
} |
97806e28-b7d8-4da7-a202-262d0676857a | public static String connectPostHttps(String reqURL, Map<String, String> params) {
String responseContent = null;
HttpPost httpPost = new HttpPost(reqURL);
try {
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(connectTimeout)
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectTimeout).build();
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
httpPost.setEntity(new UrlEncodedFormEntity(formParams, Consts.UTF_8));
httpPost.setConfig(requestConfig);
// 绑定到请求 Entry
for (Map.Entry<String, String> entry : params.entrySet()) {
formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
// 执行POST请求
HttpEntity entity = response.getEntity(); // 获取响应实体
try {
if (null != entity) {
responseContent = EntityUtils.toString(entity, Consts.UTF_8);
}
} finally {
if(entity != null){
entity.getContent().close();
}
}
} finally {
if(response != null){
response.close();
}
}
logger.info("requestURI : "+httpPost.getURI()+", responseContent: " + responseContent);
} catch (ClientProtocolException e) {
logger.info("ClientProtocolException"+ e.getMessage());
} catch (IOException e) {
logger.info("IOException"+ e.getMessage());
} finally {
httpPost.releaseConnection();
}
return responseContent;
} |
aaa920bb-eeeb-4f96-becb-c4b31bc69918 | public static void main(String[] args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uin", "1633931117@qq.com"));
params.add(new BasicNameValuePair("appid", "522005705"));
params.add(new BasicNameValuePair("ptlang", "2052"));
params.add(new BasicNameValuePair("js_type", "2"));
params.add(new BasicNameValuePair("js_ver", "10009"));
String r = String.valueOf(Math.random());
params.add(new BasicNameValuePair("r", r));
String url = "https://ssl.ptlogin2.qq.com/check";
String body = post(url, params);
System.out.println(body);
} |
92674087-41dd-4ae7-9fa5-46d7c0245f2a | @SuppressWarnings("deprecation")
public static String get(String url, List<NameValuePair> params) {
String body = null;
try {
// Get请求
HttpGet httpget = new HttpGet(url);
// 设置参数
String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
httpget.setURI(new URI(httpget.getURI().toString() + "?" + str));
// 发送请求
HttpResponse httpresponse = httpclient.execute(httpget);
// 获取返回数据
HttpEntity entity = httpresponse.getEntity();
body = EntityUtils.toString(entity);
if (entity != null) {
entity.consumeContent();
}
} catch (ParseException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return body;
} |
5ea7c245-8d2e-4d5a-91c8-c7cb78c949e2 | @SuppressWarnings("deprecation")
public static String post(String url, List<NameValuePair> params) {
String body = null;
try {
// Post请求
HttpPost httppost = new HttpPost(url);
// 设置参数
httppost.setEntity(new UrlEncodedFormEntity(params));
// 发送请求
HttpResponse httpresponse = httpclient.execute(httppost);
// 获取返回数据
HttpEntity entity = httpresponse.getEntity();
body = EntityUtils.toString(entity);
if (entity != null) {
entity.consumeContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return body;
} |
5f175606-0ece-4d5f-a683-7c8940f64b8f | public SearchHreg(String href) {
this.href = href;
} |
d2df637d-3055-4ed0-9dab-71ac14e0c0ee | public SearchHreg(List<String> hrefs, List<String> visited, List<String> images) {
this.hrefs = hrefs;
this.visited = visited;
this.images = images;
} |
73ac2d95-5b11-402b-939c-ab28ffcb97d3 | @Override
public void run() {
String content = null;
//未解析队列非空时,继续解析
while(!hrefs.isEmpty()) {
try {
//把当前要解析的url字符串从hrefs移到visited
visited.add(hrefs.remove(0));
//访问visited最后一个元素
url = new URL(visited.get(visited.size()-1));
System.out.println("已解析第 " + ++analyze + " 个连接。。。");
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setConnectTimeout(1500);
httpURLConnection.setReadTimeout(3000);
//打开字符输入流
reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
//每行字符串
content = null;
pageContent = new StringBuffer();
//开始读取页面内容
while((content = reader.readLine()) != null) {
pageContent.append(content);
}
//关闭字符输入流
reader.close();
//arr1为该页面所有href,arr2为该页面的所有<img>的src
String[] arr1 = getlinks(pageContent.toString(), HREF_REGEX);
String[] arr2 = getlinks(pageContent.toString(), IMAGE_REGEX);
for(String str : arr1) {
//获取http协议与https协议的url,则存放不存在的url
if((str.startsWith("http") || str.startsWith("https")) && (visited.indexOf(str) == -1) && (hrefs.indexOf(str) == -1)) {
hrefs.add(str);
System.out.println(++count + " >>> " + str);
}
}
for(String str : arr2) {
if(images.indexOf(str) == -1) {
images.add(str);
//System.out.println(count + " IMAGE >>> " + str);
}
}
new Thread(new DownloadImage(images)).start();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
} finally {
next();
}
}
} |
e3585533-136c-4e32-88e5-d8e813a7daea | public void next() {
try {
pageContent = null;
url = null;
httpURLConnection = null;
if(reader != null) {
reader.close();
}
reader = null;
System.gc();
} catch (IOException e) {
e.printStackTrace();
}
} |
43f14d5f-5f2a-44eb-8242-9059502acecd | public String[] getlinks(String pageContent, String regex) {
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
Matcher matcher = pattern.matcher(pageContent);
List<String> strs = new ArrayList<String>();
while(matcher.find()) {
strs.add(matcher.group(1));
}
String[] strings = new String[strs.size()];
return strs.toArray(strings);
} |
dc5e513a-5735-4698-9285-7ee809142b0e | public DownloadImage(List<String> image) {
this.images = image;
} |
08796a9e-dbc7-47f5-b2db-24e79d5aadca | @Override
public void run() {
// TODO Auto-generated method stub
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HHmmssSSS");
try {
while(!images.isEmpty()) {
imageUrl = new URL(images.remove(0));
imageUrl.openConnection().setConnectTimeout(1500);
imageUrl.openConnection().setReadTimeout(10000);
inputStream = new BufferedInputStream(imageUrl.openStream());
image = new File(IMAGE_PATH + "\\" + dateFormat.format(new Date()) + "." + imageUrl.toString().substring(imageUrl.toString().lastIndexOf(".") + 1));
outputStream = new BufferedOutputStream(new FileOutputStream(image));
byte[] buf = new byte[2048];
int length = inputStream.read(buf);
while (length != -1) {
outputStream.write(buf, 0, length);
length = inputStream.read(buf);
}
next();
}
//wait();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
next();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
524ce120-8664-4c5d-81d7-3ab813b06111 | public void next() throws IOException {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
image = null;
//images = null;
imageUrl = null;
inputStream = null;
outputStream = null;
System.gc();
System.out.println("DownloadImage >>> " + ++imageCount);
} |
8357a2c3-26f8-4480-b808-63d895972232 | public MyRobot(String href) {
hrefs.add(href);
} |
dee91bee-989a-45ee-adb5-27b4a5fb36c3 | public void run() throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.execute(new SearchHreg(hrefs, visited, images));
Thread.sleep(5000);
pool.execute(new SearchHreg(hrefs, visited, images));
//pool.execute(new DownloadImage(images));
pool.shutdown();
} |
dfb3277d-1d44-4eea-a6a3-ef0620fab72d | public static void main(String[] args) throws InterruptedException {
// MyRobot robot = new MyRobot("http://sexy.faceks.com/post/2c9c66_145b18c");
MyRobot robot = new MyRobot("http://www.taobao.com");
robot.run();
} |
a70b4cb0-a761-4b0f-8331-15847cf57f5c | public ItemId(String s) {
content = s;
} |
455f8f2f-6892-4702-a4b0-0d6cd953ea3c | public int hashCode() { return content.hashCode();} |
3eb0f063-c953-4de2-b1fd-bacde9bfec5d | public String toString() { return content; } |
3a7df117-12ba-40c2-b8a3-dbef2e84be23 | protected AbstractRecommenderEvaluator() {
random = RandomUtils.getRandom();
maxPreference = Float.NaN;
minPreference = Float.NaN;
} |
682b9e00-cd57-464c-bcad-45081d7a9a77 | @Override
public final float getMaxPreference() {
return maxPreference;
} |
d0073b64-a680-4f51-a9e4-02e2d090e34d | @Override
public final void setMaxPreference(float maxPreference) {
this.maxPreference = maxPreference;
} |
e9ea90db-879f-44ba-afb9-1f52a28abf4b | @Override
public final float getMinPreference() {
return minPreference;
} |
6cfb0349-d511-41dc-8cf5-3df29da413d1 | @Override
public final void setMinPreference(float minPreference) {
this.minPreference = minPreference;
} |
09f57ae3-225d-4f7c-851d-9361e67d02f7 | @Override
public double evaluate(RecommenderBuilder recommenderBuilder,
DataModelBuilder dataModelBuilder,
DataModel dataModel,
double trainingPercentage,
double evaluationPercentage) throws TasteException {
Preconditions.checkArgument(recommenderBuilder != null, "recommenderBuilder is null");
Preconditions.checkArgument(dataModel != null, "dataModel is null");
Preconditions.checkArgument(trainingPercentage >= 0.0 && trainingPercentage <= 1.0,
"Invalid trainingPercentage: " + trainingPercentage);
Preconditions.checkArgument(evaluationPercentage >= 0.0 && evaluationPercentage <= 1.0,
"Invalid evaluationPercentage: " + evaluationPercentage);
log.info("Beginning evaluation using {} of {}", trainingPercentage, dataModel);
int numUsers = dataModel.getNumUsers();
FastByIDMap<PreferenceArray> trainingUsers = new FastByIDMap<PreferenceArray>(
1 + (int) (evaluationPercentage * numUsers));
FastByIDMap<PreferenceArray> testUserPrefs = new FastByIDMap<PreferenceArray>(
1 + (int) (evaluationPercentage * numUsers));
LongPrimitiveIterator it = dataModel.getUserIDs();
while (it.hasNext()) {
long userID = it.nextLong();
if (random.nextDouble() < evaluationPercentage) {
processOneUser(trainingPercentage, trainingUsers, testUserPrefs, userID, dataModel);
}
else { //this user will not be used for evaluation so use all its preferences in training
PreferenceArray trainingPrefs = dataModel.getPreferencesFromUser(userID);
trainingUsers.put(userID, trainingPrefs);
}
}
DataModel trainingModel = dataModelBuilder == null ? new GenericDataModel(trainingUsers)
: dataModelBuilder.buildDataModel(trainingUsers);
Recommender recommender = recommenderBuilder.buildRecommender(trainingModel);
double result = getEvaluation(testUserPrefs, recommender);
log.info("Evaluation result: {}", result);
return result;
} |
a081e9f2-fde2-4b6b-840f-ea61b455bf26 | private void processOneUser(double trainingPercentage,
FastByIDMap<PreferenceArray> trainingUsers,
FastByIDMap<PreferenceArray> testUserPrefs,
long userID,
DataModel dataModel) throws TasteException {
List<Preference> trainingPrefs = null;
List<Preference> testPrefs = null;
PreferenceArray prefs = dataModel.getPreferencesFromUser(userID);
int size = prefs.length();
for (int i = 0; i < size; i++) {
Preference newPref = new GenericPreference(userID, prefs.getItemID(i), prefs.getValue(i));
if (random.nextDouble() < trainingPercentage) {
if (trainingPrefs == null) {
trainingPrefs = new ArrayList<Preference>(3);
}
trainingPrefs.add(newPref);
} else {
if (testPrefs == null) {
testPrefs = new ArrayList<Preference>(3);
}
testPrefs.add(newPref);
}
}
if (trainingPrefs != null) {
trainingUsers.put(userID, new GenericUserPreferenceArray(trainingPrefs));
if (testPrefs != null) {
testUserPrefs.put(userID, new GenericUserPreferenceArray(testPrefs));
}
}
} |
6c9264dc-9e56-4765-89db-8c5570cbb322 | protected float capEstimatedPreference(float estimate) {
if (estimate > maxPreference) {
return maxPreference;
}
if (estimate < minPreference) {
return minPreference;
}
return estimate;
} |
c4595e9b-6588-4d1a-b0db-3ca3e57c2979 | private double getEvaluation(FastByIDMap<PreferenceArray> testUserPrefs, Recommender recommender)
throws TasteException {
reset();
Collection<Callable<Void>> estimateCallables = new ArrayList<Callable<Void>>();
AtomicInteger noEstimateCounter = new AtomicInteger();
for (Map.Entry<Long,PreferenceArray> entry : testUserPrefs.entrySet()) {
estimateCallables.add(
new PreferenceEstimateCallable(recommender, entry.getKey(), entry.getValue(), noEstimateCounter));
}
log.info("Beginning evaluation of {} users", estimateCallables.size());
execute(estimateCallables, noEstimateCounter);
//scale evaluation result so it's a percentage of rating-spread
double rawResult = computeFinalEvaluation();
if(Double.isNaN(getMaxPreference()) || Double.isNaN(getMinPreference())){
return rawResult;
} else {
double scaling = getMaxPreference() - getMinPreference();
double result = rawResult/scaling;
return result;
}
} |
8143581a-eed5-413d-b60d-b499b6834260 | protected static void execute(Collection<Callable<Void>> callables, AtomicInteger noEstimateCounter)
throws TasteException {
callables = wrapWithStatsCallables(callables, noEstimateCounter);
int numProcessors = Runtime.getRuntime().availableProcessors();
ExecutorService executor = Executors.newFixedThreadPool(numProcessors);
log.info("Starting timing of {} tasks in {} threads", callables.size(), numProcessors);
try {
List<Future<Void>> futures = executor.invokeAll(callables);
// Go look for exceptions here, really
for (Future<Void> future : futures) {
future.get();
}
} catch (InterruptedException ie) {
throw new TasteException(ie);
} catch (ExecutionException ee) {
throw new TasteException(ee.getCause());
}
executor.shutdown();
} |
23249112-0f84-428d-9f78-36b5b094aadf | private static Collection<Callable<Void>> wrapWithStatsCallables(Collection<Callable<Void>> callables,
AtomicInteger noEstimateCounter) {
int size = callables.size();
Collection<Callable<Void>> wrapped = new ArrayList<Callable<Void>>(size);
int count = 0;
RunningAverageAndStdDev timing = new FullRunningAverageAndStdDev();
for (Callable<Void> callable : callables) {
boolean logStats = count++ % 200 == 0; // log every 200 or so iterations
wrapped.add(new StatsCallable(callable, logStats, timing, noEstimateCounter));
}
return wrapped;
} |
b79b845d-f6a7-451e-a798-cf20ee3cc00a | protected abstract void reset(); |
4cdf28aa-737c-49d6-bd80-cda69050eeaf | protected abstract void evaluateOneUser(Recommender recommender,
long testUserID,
PreferenceArray prefs,
AtomicInteger noEstimateCounter) throws TasteException; |
ed77e4b9-a727-429e-8070-a6a287188f08 | protected abstract double computeFinalEvaluation(); |
e97f0090-bdec-4ca7-9fec-7d12a4711334 | public PreferenceEstimateCallable(Recommender recommender,
long testUserID,
PreferenceArray prefs,
AtomicInteger noEstimateCounter) {
this.recommender = recommender;
this.testUserID = testUserID;
this.prefs = prefs;
this.noEstimateCounter = noEstimateCounter;
} |
667abd7a-c2f3-4178-b977-fe55a454a2e6 | @Override
public Void call() throws TasteException {
evaluateOneUser(recommender,testUserID,prefs,noEstimateCounter);
return null;
} |
ee5b0d51-a6ae-4567-b44a-5773398198ab | private StatsCallable(Callable<Void> delegate,
boolean logStats,
RunningAverageAndStdDev timing,
AtomicInteger noEstimateCounter) {
this.delegate = delegate;
this.logStats = logStats;
this.timing = timing;
this.noEstimateCounter = noEstimateCounter;
} |
122eeb9b-6cd2-4c0b-aa84-392b348b329b | @Override
public Void call() throws Exception {
long start = System.currentTimeMillis();
delegate.call();
long end = System.currentTimeMillis();
timing.addDatum(end - start);
if (logStats) {
Runtime runtime = Runtime.getRuntime();
int average = (int) timing.getAverage();
log.info("Average time per recommendation: {}ms", average);
long totalMemory = runtime.totalMemory();
long memory = totalMemory - runtime.freeMemory();
log.info("Approximate memory used: {}MB / {}MB", memory / 1000000L, totalMemory / 1000000L);
log.info("Unable to recommend in {} cases", noEstimateCounter.get());
}
return null;
} |
10689b9f-d9e0-4197-8310-4863376dc04c | protected abstract void processOneEstimate(float estimatedPreference, Preference realPref); |
025bd91a-ea1c-4fb6-a167-2cf2a17c01e9 | protected void evaluateOneUser(Recommender recommender,
long testUserID,
PreferenceArray prefs,
AtomicInteger noEstimateCounter) throws TasteException{
for (Preference realPref : prefs) {
float estimatedPreference = Float.NaN;
try {
estimatedPreference = recommender.estimatePreference(testUserID, realPref.getItemID());
} catch (NoSuchUserException nsue) {
// It's possible that an item exists in the test data but not training data in which case
// NSEE will be thrown. Just ignore it and move on.
log.info("User exists in test data but not training data: {}", testUserID);
} catch (NoSuchItemException nsie) {
log.info("Item exists in test data but not training data: {}", realPref.getItemID());
}
if (Float.isNaN(estimatedPreference)) {
noEstimateCounter.incrementAndGet();
} else {
estimatedPreference = capEstimatedPreference(estimatedPreference);
processOneEstimate(estimatedPreference, realPref);
}
}
} |
a7296473-c917-434e-b92f-7602e5b99e9e | void processPrefPair(Double u1Pref, Double u2Pref); |
f82e8bbb-a586-4972-9cbd-297c259d5ed4 | Double computeResult(); |
7b6bb07f-04e9-47eb-8dc6-f7a44fd8252e | public RailroadMap() {
connections = new HashMap<Town, List<Route>>();
distances = new HashMap<Town, Map<Town, Integer>>();
} |
4d44ca21-d68a-4605-bd79-76b5d8d5182f | public void addRoute(String from, String to, int distance) {
Town fromTown = new Town(from);
Town toTown = new Town(to);
List<Route> fromConnections = connections.get(fromTown);
if (fromConnections == null) {
fromConnections = new LinkedList<Route>();
connections.put(fromTown, fromConnections);
}
if (!connections.containsKey(toTown)) {
connections.put(toTown, null);
}
fromConnections.add(new Route(toTown, distance));
Map<Town, Integer> fromDistances = distances.get(fromTown);
if (fromDistances == null) {
fromDistances = new HashMap<Town, Integer>();
distances.put(fromTown, fromDistances);
}
fromDistances.put(toTown, distance);
} |
472f273b-00e3-4987-b3af-5853d9593075 | public List<Route> getRoutesFromTown(Town town) {
return this.connections.get(town);
} |
3d5f0b99-a170-43da-9d21-9038d372ef94 | public Integer getDistance(Town first, Town second) {
Map<Town, Integer> submap = this.distances.get(first);
if (submap == null) {
return null;
}
return submap.get(second);
} |
949c0cb1-01a7-47a8-982f-8e2e623bf3e0 | public Set<Town> getTownList() {
return this.connections.keySet();
} |
fddc6547-2426-4ca0-8793-4f78c6dd659a | public boolean existsTown(Town t) {
return this.connections.containsKey(t);
} |
b078ef5a-44b9-4dca-9ca5-57a87f0ec513 | public Town(String name) {
this.name = name;
} |
aca829a3-823a-493c-95cb-0927f846ef07 | public String getName() {
return name;
} |
c178f94c-579a-4dbb-a736-d52e357e4c42 | @Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}
Town otherTown = (Town) obj;
return this.name.equals(otherTown.name);
} |
d6dfb27b-35c2-490e-ac85-67784118c4cd | @Override
public int hashCode() {
return name.hashCode();
} |
adf5cef6-c7e1-437e-9cf8-c2fe5d42e150 | @Override
public String toString() {
return "Town{" +
"name='" + name + '\'' +
'}';
} |
6aae62e2-7a95-4189-a556-f24375514b09 | public Route(Town to, int distance) {
this.to = to;
this.distance = distance;
} |
1082eb48-2ea3-467e-a067-10d0aaf2ade5 | public Town getTo() {
return to;
} |
f9d0498c-8fbf-457a-a0c3-c31431094a68 | public int getDistance() {
return distance;
} |
a9e2cc70-07ea-48a0-bdf2-c05026a413f0 | @Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}
Route otherRoute = (Route) obj;
return this.to.equals(otherRoute.to) &&
this.distance == otherRoute.distance;
} |
f5841a1f-40ee-43ee-8a1a-f8894507eb9b | @Override
public int hashCode() {
int result = to != null ? to.hashCode() : 0;
result = 31 * result + distance;
return result;
} |
6feb7c59-94b8-4dd7-81cd-064fe37ff8e4 | public synchronized void setMap(RailroadMap map) {
this.map = map;
} |
e546abd5-6cf1-419a-8028-bcbc9cd6c647 | public synchronized RailroadMap getMap() {
return map;
} |
27fac7a8-8318-4e65-b888-f24085a5551f | public TrainsServerHandlers(TrainsServerState serverState) {
this.serverState = serverState;
handlers = new HttpHandler[] {updateMap, followPath, shortestPath, countRoutes};
mappings = new String[] {UPDATE_MAP_PATH, FOLLOW_PATH_PATH, SHORTEST_PATH_PATH, COUNT_ROUTES_PATH};
algorithms = new RailroadAlgorithms();
} |
dd366734-0c28-4dc9-bef5-5be5163ad330 | @Override
public void handle(HttpExchange httpExchange) throws IOException {
//Parameter extraction
String[] uriParts = initialCheck(httpExchange, 3);
//Parameter conversion
String param = uriParts[2];
String[] routes = param.split(",");
RailroadMap map = new RailroadMap();
for (String r : routes) {
map.addRoute(String.valueOf(r.charAt(0)), String.valueOf(r.charAt(1)),
Integer.parseInt(String.valueOf(r.charAt(2))));
}
serverState.setMap(map);
httpExchange.sendResponseHeaders(200, 0);
OutputStream os = httpExchange.getResponseBody();
os.close();
} |
334adcc3-b071-470e-8ac7-caa0b4e91e64 | @Override
public void handle(HttpExchange httpExchange) throws IOException {
//Parameter extraction
String[] uriParts = initialCheck(httpExchange, 3);
//Parameter conversion
String param = uriParts[2];
List<Town> towns = new LinkedList<Town>();
for (char x : param.toCharArray()) {
towns.add(new Town(String.valueOf(x)));
}
int result = algorithms.followPath(serverState.getMap(), towns);
String response = "NO SUCH ROUTE";
if (result >= 0) {
response = String.valueOf(result);
}
httpExchange.sendResponseHeaders(200, response.length());
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
} |
8abfe4ab-1c88-41ab-b63b-133d2ac4d767 | @Override
public void handle(HttpExchange httpExchange) throws IOException {
//Parameter extraction
String[] uriParts = initialCheck(httpExchange, 4);
//Parameter conversion
String from = uriParts[2];
String to = uriParts[3];
int result = algorithms.shortestPathLength(serverState.getMap(), new Town(from), new Town(to));
String response = String.valueOf(result);
httpExchange.sendResponseHeaders(200, response.length());
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
} |
3ec9f6c8-f75f-464b-a613-4221010b55a6 | @Override
public void handle(HttpExchange httpExchange) throws IOException {
//Parameter extraction
String[] uriParts = initialCheck(httpExchange, 4);
//Parameter conversion
Town from = new Town(uriParts[2]);
Town to = new Town(uriParts[3]);
String maxStops = extractQueryString(httpExchange, "maxStops");
String totalStops = extractQueryString(httpExchange, "totalStops");
String maxDistance = extractQueryString(httpExchange, "maxDistance");
String totalDistance = extractQueryString(httpExchange, "totalDistance");
List<RunningFilter<RouteStatus>> runningFilters = new LinkedList<RunningFilter<RouteStatus>>();
List<EndFilter<RouteStatus>> endFilters = new LinkedList<EndFilter<RouteStatus>>();
if (maxStops != null) {
runningFilters.add(new MaxStopsFilter(Integer.valueOf(maxStops)));
}
if (totalStops != null) {
Integer totalStopsInt = Integer.valueOf(totalStops);
runningFilters.add(new MaxStopsFilter(totalStopsInt));
endFilters.add(new ExactStopsFilter(totalStopsInt));
}
if (maxDistance != null) {
runningFilters.add(new MaxDistanceFilter(Integer.valueOf(maxDistance)));
}
if (totalDistance != null) {
Integer totalDistanceInt = Integer.valueOf(totalDistance);
runningFilters.add(new MaxDistanceFilter(totalDistanceInt));
endFilters.add(new ExactDistanceFilter(totalDistanceInt));
}
int result = algorithms.numberOfRoutes(serverState.getMap(), from, to, runningFilters, endFilters);
String response = String.valueOf(result);
httpExchange.sendResponseHeaders(200, response.length());
OutputStream os = httpExchange.getResponseBody();
os.write(response.getBytes());
os.close();
} |
b9c362bf-c027-4408-8ef8-e4f2667d2d8f | private String[] initialCheck(HttpExchange httpExchange, int paramNumber) throws IOException, IllegalArgumentException {
//Parameter extraction
String uri = httpExchange.getRequestURI().getPath();
String method = httpExchange.getRequestMethod();
String[] uriParts = uri.split("/");
if (uriParts.length < paramNumber) {
returnError(httpExchange, "ERROR: Not enough parameters");
} else if (!method.equals("GET")) {
returnError(httpExchange, "ERROR: Support is only provided for GET method.");
}
return uriParts;
} |
78fa7a5e-bdcb-4c85-b56e-34a5b88cfc49 | private void returnError(HttpExchange httpExchange, String errorMsg) throws IOException, IllegalArgumentException {
httpExchange.sendResponseHeaders(400, errorMsg.length());
OutputStream os = httpExchange.getResponseBody();
os.write(errorMsg.getBytes());
os.close();
throw new IllegalArgumentException();
} |
8bf64dfd-e442-48a1-b0b3-ec667140ff2e | private String extractQueryString(HttpExchange httpExchange, String queryKey) {
String query = httpExchange.getRequestURI().getQuery();
Pattern p = Pattern.compile(queryKey + "=" + "(.*)&?");
Matcher m = p.matcher(query);
if (m.find()) {
return m.group(1);
}
return null;
} |
890f03d4-2579-4d07-97eb-6cf8f63ae50f | public static void main(String[] args) throws IOException {
new TrainsServerMain();
} |
93402ebb-700d-4d01-807c-9c794d939700 | public TrainsServerMain() {
try {
HttpServer httpServer = HttpServer.create(new InetSocketAddress(SERVER_PORT), 0);
for (int i = 0; i < this.serverHandlers.mappings.length; i++) {
httpServer.createContext(this.serverHandlers.mappings[i],
this.serverHandlers.handlers[i]);
}
httpServer.setExecutor(null); // creates a default executor
httpServer.start();
} catch (IOException ex) {
ex.printStackTrace();
}
} |
b3833ad2-1dcc-4b73-b503-b3285c8758fa | public int followPath(RailroadMap map, List<Town> towns) {
Iterator<Town> it = towns.iterator();
int acum = 0;
if (it.hasNext()) {
Town startTown = it.next();
if (!map.existsTown(startTown)) {
return -1;
}
while (it.hasNext()) {
Town nextTown = it.next();
Integer distance = map.getDistance(startTown, nextTown);
if (distance != null) {
acum += distance;
} else {
return -1;
}
startTown = nextTown;
}
}
return acum;
} |
5693e8de-5615-46b2-a748-7a65bd9ed94f | public int numberOfRoutesWithStopsFilter(RailroadMap map, Town from, Town to, int maximumStops, boolean isExact) {
List<RunningFilter<RouteStatus>> runningFilters = new LinkedList<RunningFilter<RouteStatus>>();
runningFilters.add(new MaxStopsFilter(maximumStops));
List<EndFilter<RouteStatus>> endFilters = null;
if (isExact) {
endFilters = new LinkedList<EndFilter<RouteStatus>>();
endFilters.add(new ExactStopsFilter(maximumStops));
}
return numberOfRoutes(map, from, to, runningFilters, endFilters);
} |
479a1981-0332-4757-9fb8-180d65e64c82 | public int numberOfRoutesWithDistanceFilter(RailroadMap map, Town from, Town to, int maximumDistance, boolean isExact) {
List<RunningFilter<RouteStatus>> runningFilters = new LinkedList<RunningFilter<RouteStatus>>();
List<EndFilter<RouteStatus>> endFilters = null;
if (isExact) {
endFilters = new LinkedList<EndFilter<RouteStatus>>();
endFilters.add(new ExactDistanceFilter(maximumDistance));
runningFilters.add(new MaxDistanceFilter(maximumDistance+1));
} else {
runningFilters.add(new MaxDistanceFilter(maximumDistance));
}
return numberOfRoutes(map, from, to, runningFilters, endFilters);
} |
30f4891d-29ab-43e8-bc88-5f67d7b10d67 | public int numberOfRoutes(RailroadMap map, Town from, Town to,
List<RunningFilter<RouteStatus>> runningFilters, List<EndFilter<RouteStatus>> endFilters) {
Queue<RouteStatus> current = new LinkedList<RouteStatus>();
Collection<RouteStatus> results = new HashSet<RouteStatus>();
int result = 0;
//Startup
if (!map.existsTown(from) || !map.existsTown(to)) {
return result;
}
for (Route r : map.getRoutesFromTown(from)) {
current.add(new RouteStatus(r.getTo(), r.getDistance()));
}
//Main cicle
while (!current.isEmpty()) {
//Removing filtered results
if (runningFilters != null) {
for (RunningFilter<RouteStatus> filter : runningFilters) {
Queue<RouteStatus> passing = new LinkedList<RouteStatus>();
while (!current.isEmpty()) {
RouteStatus rs = current.remove();
if (filter.isOk(rs)) {
passing.add(rs);
}
}
current = passing;
}
}
//Checking possible results
for (RouteStatus st : current) {
if (st.current.equals(to)) {
results.add(st);
}
}
//Creating new status
Queue<RouteStatus> newStatus = new LinkedList<RouteStatus>();
while (!current.isEmpty()) {
RouteStatus st = current.remove();
List<Route> outRoutes = map.getRoutesFromTown(st.current);
if (outRoutes != null) {
for (Route r : outRoutes) {
newStatus.add(new RouteStatus(st, r.getTo(), r.getDistance()));
}
}
}
current = newStatus;
}
//Clearing
if (endFilters != null) {
for (EndFilter<RouteStatus> filter : endFilters) {
filter.filter(results);
}
}
//Result
return results.size();
} |
63e99b90-344c-4e35-a7dc-fe2ee933b9eb | public int shortestPathLength(RailroadMap map, Town from, Town to) {
//Setup
Map<Town, Integer> distances = new HashMap<Town, Integer>();
Set<Town> unvisited = new HashSet<Town>();
for (Town t : map.getTownList()) {
distances.put(t, Integer.MAX_VALUE);
unvisited.add(t);
}
//First update
Town current = from;
updateUnvisited(map, current, distances, 0, unvisited);
current = getNextCurrent(distances, unvisited);
//Normal update
while (!current.equals(to) && !distances.get(current).equals(Integer.MAX_VALUE)) {
updateUnvisited(map, current, distances, distances.get(current), unvisited);
current = getNextCurrent(distances, unvisited);
unvisited.remove(current);
}
if (distances.get(current).equals(Integer.MAX_VALUE)) {
return -1;
}
return distances.get(current);
} |
eb41fee3-b80d-4931-9e93-f9821d6ab0c9 | private void updateUnvisited(RailroadMap map, Town current, Map<Town, Integer> distances, Integer baseDistance, Set<Town> unvisited) {
for (Route r : map.getRoutesFromTown(current)) {
Town toUpdate = r.getTo();
if (unvisited.contains(toUpdate)) {
Integer distance = distances.get(toUpdate);
Integer alt = baseDistance + r.getDistance();
if (alt < distance) {
distances.put(toUpdate, alt);
}
}
}
} |
e69e8917-197e-494e-a7aa-34dd000c5660 | private Town getNextCurrent(Map<Town, Integer> distances, Set<Town> unvisited) {
Town next = unvisited.iterator().next();
for (Town t : unvisited) {
if (distances.get(t) < distances.get(next)) {
next = t;
}
}
return next;
} |
796fdd51-5abe-4e31-9a15-79af639cdc33 | public RouteStatus(Town current, int distance) {
this.current = current;
this.stops = 1;
this.distance = distance;
} |
e550471b-a77a-418b-b7a8-404d10191bfd | public RouteStatus(RouteStatus st, Town current, int distance) {
this.current = current;
this.stops = st.stops + 1;
this.distance = st.distance + distance;
} |
d732539a-23ff-42b3-8f43-5a49af46d976 | @Override
public String toString() {
return "RouteStatus{" +
"current=" + current +
", stops=" + stops +
", distance=" + distance +
'}';
} |
513e3e0c-1463-4d30-8510-5b851047b2a3 | void filter(Collection<T> t); |
04f4bf4d-dd19-4075-a2b4-7ec17e2a47b1 | boolean isOk(T t); |
faea0e2d-69ce-410c-a37b-e995f960de71 | public ExactDistanceFilter(int maximumDistance) {
this.distance = maximumDistance;
} |
2fbaf21f-6279-4a2a-8046-1f210cdd706d | @Override
boolean isOk(RouteStatus routeStatus) {
return routeStatus.distance == this.distance;
} |
77d58178-a3c2-486b-aeeb-80399b1d09d1 | public ExactStopsFilter(int stops) {
this.stops = stops;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.