将map对象转换为list时报错'list' object is not callable?

代码如下:

def fun(x):
    return x ** 2
your_list = [1,2,3,4,5,6,7,8,9,10]

list(map(fun,your_list))

报错为:'list' object is not callable

BoJackuu
ljquu17 太神奇了,我今天又跑了一遍可以了。。。
4 个月之前 回复

2个回答

没有问题啊 你这是全部代码了吗 运行不会有问题啊

python3 运行没有任何问题。楼主环境是什么?建议下次提问带上环境这些。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
思科防火墙5505 端口映射问题
单位内有台电脑想要端口映射到外网访问,查询了相关资料一直没弄好,请求大神帮忙。 贴上防火墙代码: ciscoasa(config)# sh run : Saved : ASA Version 8.2(5) ! hostname ciscoasa names ! interface Ethernet0/0 switchport access vlan 2 ! interface Ethernet0/1 switchport access vlan 1000 ! interface Ethernet0/2 ! interface Ethernet0/3 ! interface Ethernet0/4 ! interface Ethernet0/5 ! interface Ethernet0/6 ! interface Ethernet0/7 ! interface Vlan1 no nameif security-level 100 ip address 192.168.1.1 255.255.255.0 ! interface Vlan2 nameif outside security-level 10 ip address 公网IP 255.255.255.248 ! interface Vlan1000 nameif inside security-level 100 ip address 1.1.1.2 255.255.255.252 ! ftp mode passive dns domain-lookup outside dns server-group DefaultDNS name-server 233.5.5.5 name-server 114.114.114.114 object-group network OBJ_INSIDE_Subnet network-object 10.88.0.0 255.255.0.0 access-list 101 extended permit icmp any any access-list 101 extended permit ip any any access-list 101 extended permit tcp any eq www interface outside eq 28780 access-list 101 extended permit tcp any eq 8866 interface outside eq 30001 access-list 101 extended permit tcp any eq 8080 interface outside eq 38080 pager lines 24 logging asdm informational mtu outside 1500 mtu inside 1500 no failover icmp unreachable rate-limit 1 burst-size 1 no asdm history enable arp timeout 14400 nat-control global (outside) 1 interface nat (inside) 1 0.0.0.0 0.0.0.0 static (inside,outside) tcp interface 28780 10.88.98.87 www netmask 255.255.255.255 static (inside,outside) tcp interface 30001 10.88.38.215 8866 netmask 255.255.255.255 static (inside,outside) tcp interface 38080 10.88.38.215 8080 netmask 255.255.255.255 access-group 101 in interface outside access-group 101 in interface inside route outside 0.0.0.0 0.0.0.0 公网网关 1 route inside 10.88.0.0 255.255.0.0 1.1.1.1 1 timeout xlate 3:00:00 timeout conn 1:00:00 half-closed 0:10:00 udp 0:02:00 icmp 0:00:02 timeout sunrpc 0:10:00 h323 0:05:00 h225 1:00:00 mgcp 0:05:00 mgcp-pat 0:05:00 timeout sip 0:30:00 sip_media 0:02:00 sip-invite 0:03:00 sip-disconnect 0:02:00 timeout sip-provisional-media 0:02:00 uauth 0:05:00 absolute timeout tcp-proxy-reassembly 0:01:00 timeout floating-conn 0:00:00 dynamic-access-policy-record DfltAccessPolicy aaa authentication telnet console LOCAL http server enable http 0.0.0.0 0.0.0.0 inside no snmp-server location no snmp-server contact snmp-server enable traps snmp authentication linkup linkdown coldstart crypto ipsec security-association lifetime seconds 28800 crypto ipsec security-association lifetime kilobytes 4608000 telnet 0.0.0.0 0.0.0.0 inside telnet timeout 5 ssh 0.0.0.0 0.0.0.0 inside ssh timeout 5 console timeout 0 dhcpd auto_config outside ! threat-detection basic-threat threat-detection statistics access-list no threat-detection statistics tcp-intercept ntp server 210.72.145.44 webvpn ! class-map inspection_default match default-inspection-traffic ! ! policy-map type inspect dns preset_dns_map parameters message-length maximum client auto message-length maximum 512 policy-map global_policy class inspection_default inspect dns preset_dns_map inspect ftp inspect h323 h225 inspect h323 ras inspect rsh inspect rtsp inspect esmtp inspect sqlnet inspect skinny inspect sunrpc inspect xdmcp inspect sip inspect netbios inspect tftp inspect ip-options ! service-policy global_policy global prompt hostname context no call-home reporting anonymous : end 现在外网访问不了服务器页面,然后用站长工具里面的端口扫描显示28780与30001端口是打开的。 sh nat: ciscoasa(config)# sh nat NAT policies on Interface inside: match tcp inside host 10.88.98.87 eq 80 outside any static translation to 公网IP/28780 translate_hits = 0, untranslate_hits = 11 match tcp inside host 10.88.38.215 eq 8866 outside any static translation to 公网IP/30001 translate_hits = 0, untranslate_hits = 105 match tcp inside host 10.88.38.215 eq 8080 outside any static translation to 公网IP/38080 translate_hits = 0, untranslate_hits = 2 match ip inside any outside any dynamic translation to pool 1 (公网IP [Interface PAT]) translate_hits = 5885251, untranslate_hits = 531611 match ip inside any inside any dynamic translation to pool 1 (No matching global) translate_hits = 0, untranslate_hits = 0 match ip inside any _internal_loopback any dynamic translation to pool 1 (No matching global) translate_hits = 0, untranslate_hits = 0 match ip inside any outside any no translation group, implicit deny policy_hits = 0 ciscoasa(config)# 为什么这里untranslate_hits = 11 我只要用站长工具的端口扫描一次,这里就增加一。 请问我怎么才能成功把10.88.98.87的80端口映射到公网IP的28780端口呢? 谢啦。
android 调用 webservice 返回字符串想在listview中显示。出现问题……
下文是 主查询模块 Query_xiaofeijilu.java, ``` package com.gongneng.chaxun; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleAdapter; import org.json.JSONException; import org.ksoap2.SoapEnvelope; import org.ksoap2.SoapFault; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import org.xmlpull.v1.XmlPullParserException; import com.constant.Constant; import com.example.kehuduan.R; public class Query_xiaofeijilu extends Activity { private Button okButton; private ListView listview; private Handler handler = null; private SimpleAdapter adapter; private List<Map<String,Object>> muldata; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.query_xiaofeijilu); okButton = (Button) this.findViewById(R.id.xiaofeijiluchaxun); listview = (ListView) this.findViewById(R.id.listxiaofeijilu); handler = new Handler(); okButton.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { new Thread() { @Override public void run() { try { try { getWebservice(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.start(); } }); } public void getWebservice() throws InterruptedException, IOException, XmlPullParserException, JSONException { // 创建属于主线程的handler HttpTransportSE ht = new HttpTransportSE(Constant.SERVICE_URL); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); SoapObject request = new SoapObject(Constant.SERVICE_NS,Constant.QueryAction_chaxunxiaofeijilu); request.addProperty("aac999", "2200000"); envelope.bodyOut = request;// 往出走的数据Out,也就是服务器的传入值 try { ht.call(null, envelope); Object object = (Object) envelope.getResponse();// 就用Object来取 muldata = new ArrayList<Map<String,Object>>(); if (envelope.getResponse() != null) { String a = object.toString(); String b = a.replace("[","");//变[为空 String c = b.replace("]",""); String d = c.replace("{",""); String e = d.replace("}",""); String f = e; // String[] arr = c.split(",");//将字符串转为数组,以,为分割 Map<String, Object> aa = transStringToMap(f); Iterator<?> iter = aa.entrySet().iterator(); while (iter.hasNext()) { Map<String,Object> map=new HashMap<String, Object>(); Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey(); Object val = entry.getValue(); map.put(key.toString(),val.toString()); // map.put("text", "测试文本:"); muldata.add(map); } adapter = buildListAdapter(this, muldata); new Thread() { public void run() { handler.post(runnableUi); } }.start(); return; } else { System.out.println("没有返回值"); return; } } catch (SoapFault e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 构建adapter. public SimpleAdapter buildListAdapter(Context context,List<Map<String, Object>> data) { SimpleAdapter adapter = new SimpleAdapter(context, data, R.layout.chaxunxiaofeijilulist, new String[] { "AKB021","AKE038","KS","JS","ROWNUM" }, new int[] { R.id.akb021, R.id.ake038,R.id.ks,R.id.js ,R.id.rownum}); return adapter; } // 构建Runnable对象,在runnable中更新界面 // 更新页面list 需要单独写个线程 Runnable runnableUi = new Runnable() { @Override public void run() { // 更新界面 listview.setAdapter(adapter); Looper.loop(); } }; //=================================== //字符串转MAP public static Map<String, Object> transStringToMap(String mapString){ Map<String, Object> map = new HashMap<String, Object>(); java.util.StringTokenizer items; for(StringTokenizer entrys = new StringTokenizer(mapString, ","); entrys.hasMoreTokens(); map.put(items.nextToken(), items.hasMoreTokens() ? ((Object) (items.nextToken())).toString() : null)) items = new StringTokenizer(entrys.nextToken(), ":"); return map; } } ``` 下文是list页面 ``` <?xml version="1.0" encoding="UTF-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/child" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" > <!-- 若想隐藏id加入此属性: android:visibility="gone",这样做有点类似于Html中hidden域 android:background="#E3D25E" --> <TextView android:id="@+id/akb021" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#6633FF" android:text=" akb021 " /> <TextView android:id="@+id/ake038" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" ake038 "/> <TextView android:id="@+id/ks" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" ks "/> <TextView android:id="@+id/js" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" js "/> <TextView android:id="@+id/rownum" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" rownum "/> </LinearLayout> ``` 主显示页面 ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <EditText android:id="@+id/editTextShenfenzheng" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/listxiaofeijilu" android:layout_alignParentTop="true" android:layout_alignRight="@+id/listxiaofeijilu" android:ems="10" android:hint="@string/shenfenzheng" > </EditText> <Button android:id="@+id/chongzhi" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:text="@string/chongzhi" /> <ListView android:id="@+id/listxiaofeijilu" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_above="@+id/xiaofeijiluchaxun" android:layout_alignRight="@+id/chongzhi" android:layout_below="@+id/editTextShenfenzheng" > </ListView> <Button android:id="@+id/xiaofeijiluchaxun" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/chongzhi" android:layout_alignBottom="@+id/chongzhi" android:layout_toLeftOf="@+id/chongzhi" android:text="@string/xiaofeijilu" /> </RelativeLayout> ``` 但是现在只把行数显示出来了,里边没有值,附图: ![图片说明](https://img-ask.csdn.net/upload/201504/18/1429357099_489390.png) 这个问题,困扰了我好几天了,烦请各位好友,帮忙出出招,在此写过了!!!
Mybatis如何使用注解方式设置resultMap的type属性。
``` @Mapper public interface TableSearchMapper { @Select("call sp_XTBCX(#{tableName,mode=IN,jdbcType=VARCHAR},'','',#{result,mode=OUT,jdbcType=CURSOR,javaType=ResultSet,resultMap=result})") @Results(id = "result") @Options(statementType= StatementType.CALLABLE ) public List<Map<String,Object>> tableSearch(@Param("tableName")String tableName,@Param("result")List<Map<String,Object>> result); } ``` 存储过程是输入表名后输出经过处理的全集,所以列名是不确定的,想写一个动态的方法,通过网上搜索XML形式在配置中将<resultMap>的type属性设置成HashMap可以实现,但是由于现在工程中所有Mapper都是基于注解形式的,但是@Results没有type属性 还有一点疑惑是:TableSearchMapper这个方法,返回值是否可以是void,是将Map参数传进来之后return Map参数还是return 这个方法的返回值?
hibernate 调用存储过程的通用方法
我想作一个在hibernate中调用存储过程的通用方法 public class callbackfunc implements HibernateCallback { private String funname; Map<String,Object> param ; public callbackfunc(String func,Map<String,Object> param ){ this.funname=func; this.param=param; } public Object doInHibernate(Session session) { Object o=new Object(); try { String sql = "{call "+this.getFunname()+ "}"; SQLQuery query=session.createSQLQuery(sql); Set<Entry<String,Object>> s = param.entrySet(); for(Entry<String,Object> e :s){ query.setParameter(e.getKey(), e.getValue()); } List<Map<String,Object>> list = new ArrayList<Map<String,Object>>(); list = query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list return list; } catch (Exception e) { e.printStackTrace(); return false; } } public Map<String, Object> getParam() { return param; } public void setParam(Map<String, Object> param) { this.param = param; } public String getFunname() { return funname; } public void setFunname(String funname) { this.funname = funname; } } 以上是回调函数 public List<Map<String,Object>> excuteFun(String funname,Map<String,Object> param) { return getHibernateTemplate().execute(new callbackfunc(funname,param)); } 以上是hibernate调用存储过程的方法 main{ Map m=new HashMap(); m.put("dnpno", "dfv"); cs.excuteFun("WF_DENPNO_SAIBAN_UPDATE('5030',1,=>:dnpno)", m ); } 以上是调用WF_DENPNO_SAIBAN_UPDATE存储过程的测试main方法 WF_DENPNO_SAIBAN_UPDATE 存储过程定义如下 WF_DENPNO_SAIBAN_UPDATE( dnpkbn in varchar2, cnt in number,dnpno out varchar2 ) 输入两个参数 dnpkbn cnt 返回字符串型dnpno 为什么总是返回 不能执行查询错误?
基于AXIS调用webservice报错:Connection refused: connect
我的调用方法: public static void main(String[] args) throws Exception { String client_id = "HeYiApp"; String orderNum = "2"; List numberList = new ArrayList(); numberList.add("120719"); numberList.add("120746"); numberList.add("113095"); String webUrl = "https://10.218.132.26/api/openapi/employee/getBatchEmpInfoList.json";// 服务端url地址 String webMethod = "getBatchEmpInfoList";// 调用方法名称 Service service = new Service(); // 建服务 Call call; try { call = (Call) service.createCall(); try { call.setTargetEndpointAddress(new URL(webUrl)); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); }// 设置访问地址 call.setOperationName(webMethod);// 设置访问方法 call.addParameter("arg0", XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN);// 定义参数 call.addParameter("arg1", XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN);// 定义参数 call.addParameter("arg2", XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN);// 定义参数 call.setReturnType(XMLType.XSD_STRING);// 定义返回值格式 //List<Map<String, Object>> workersInfo= (List<Map<String, Object>>) call.invoke(new Object[] { client_id, numberList, orderNum }); //for(Map m:workersInfo){ // System.out.println(m.get("name")); //} JSONArray jsonObject = (JSONArray) call.invoke(new Object[] { client_id, numberList, orderNum }); System.out.println(jsonObject.toString()); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 建对话 } 报错: Exception in thread "main" AxisFault faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException faultSubcode: faultString: java.net.ConnectException: Connection refused: connect faultActor: faultNode: faultDetail: {http://xml.apache.org/axis/}stackTrace:java.net.ConnectException: Connection refused: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:668) at sun.security.ssl.SSLSocketImpl.&lt;init&gt;(SSLSocketImpl.java:427) at sun.security.ssl.SSLSocketFactoryImpl.createSocket(SSLSocketFactoryImpl.java:88) at org.apache.axis.components.net.JSSESocketFactory.create(JSSESocketFactory.java:92) at org.apache.axis.transport.http.HTTPSender.getSocket(HTTPSender.java:191) at org.apache.axis.transport.http.HTTPSender.writeToSocket(HTTPSender.java:404) at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:138) at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32) at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118) at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83) at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165) at org.apache.axis.client.Call.invokeEngine(Call.java:2784) at org.apache.axis.client.Call.invoke(Call.java:2767) at org.apache.axis.client.Call.invoke(Call.java:2443) at org.apache.axis.client.Call.invoke(Call.java:2366) at org.apache.axis.client.Call.invoke(Call.java:1812) at webservice.Test.main(Test.java:52) {http://xml.apache.org/axis/}hostname:zhangxl java.net.ConnectException: Connection refused: connect at org.apache.axis.AxisFault.makeFault(AxisFault.java:101) at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:154) at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32) at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118) at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83) at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165) at org.apache.axis.client.Call.invokeEngine(Call.java:2784) at org.apache.axis.client.Call.invoke(Call.java:2767) at org.apache.axis.client.Call.invoke(Call.java:2443) at org.apache.axis.client.Call.invoke(Call.java:2366) at org.apache.axis.client.Call.invoke(Call.java:1812) at webservice.Test.main(Test.java:52) Caused by: java.net.ConnectException: Connection refused: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:668) at sun.security.ssl.SSLSocketImpl.<init>(SSLSocketImpl.java:427) at sun.security.ssl.SSLSocketFactoryImpl.createSocket(SSLSocketFactoryImpl.java:88) at org.apache.axis.components.net.JSSESocketFactory.create(JSSESocketFactory.java:92) at org.apache.axis.transport.http.HTTPSender.getSocket(HTTPSender.java:191) at org.apache.axis.transport.http.HTTPSender.writeToSocket(HTTPSender.java:404) at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:138) ... 10 more
hibernate调用存储过程
public List<Map<String,Object>> excuteFun(String funname,Map<String,Object> param) { return getHibernateTemplate().execute(new callbackfunc(funname,param)); } 有一个存储过程 SPECIAL_CONFIRM ( DENPNO IN VARCHAR2,USERID IN VARCHAR2) java调用代码为: Map m=new HashMap(); m.put("DENPNO","ASDF"); m.put("USERID", "EDP"); cs.excuteFun("special_confirm(:DENPNO,:USERID)", m); 执行时报错: Hibernate: {call special_confirm(?,?)} org.hibernate.HibernateException: Could not extract result set metadata 为什么?
Android如何获取listview里面的选取的数据
需要在lv1.setOnItemLongClickListener方法中加入一个长按获取电话号码,联系人的代码,我写的代码总感觉有错误,但是不知道错在哪,我尝试用system输出我获取的数值,数值是对的,但是传不到打电话和发短信的地方 ![图片说明](https://img-ask.csdn.net/upload/201512/27/1451222337_132249.png) 这是效果图 package com.example.lianxi; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.Inflater; import android.R.string; import android.app.Activity; import android.app.ActionBar; import android.app.Fragment; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ContextMenu.ContextMenuInfo; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import android.os.Build; public class M1 extends Activity { private ListView lv1; private int[] pic = new int[] { R.drawable.img01, R.drawable.img02, R.drawable.img03, R.drawable.img04, }; private String[] xm = new String[] { "张三", "李四", "王五", "赵六" }; private String[] dh = new String[] { "626746", "624882", "620874", "130533", }; String s = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.m1); lv1 = (ListView) findViewById(R.id.lv1); final List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); for (int i = 0; i < pic.length; i++) { Map<String, Object> m1 = new HashMap<String, Object>(); m1.put("pic", pic[i]); m1.put("xm", xm[i]); m1.put("dh", dh[i]); list.add(m1); } SimpleAdapter sa = new SimpleAdapter(M1.this, list, R.layout.moban, new String[] { "pic", "xm", "dh" }, new int[] { R.id.iv1, R.id.tv1, R.id.tv2 }); lv1.setAdapter(sa); lv1.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { HashMap<String, Object> map = (HashMap<String, Object>) lv1 .getItemAtPosition(arg2); String xm = String.valueOf(map.get("xm").toString()); String dh = String.valueOf(map.get("dh").toString()); System.out.println(xm); System.out.println(dh); return false; } }); registerForContextMenu(lv1); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { // TODO Auto-generated method stub MenuInflater m1 = new MenuInflater(M1.this); m1.inflate(R.menu.m1, menu); menu.setHeaderIcon(R.drawable.i); menu.setHeaderTitle("请选择"); super.onCreateContextMenu(menu, v, menuInfo); } @Override public boolean onContextItemSelected(MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { case R.id.dh: Intent intent = new Intent(); intent.setAction(intent.ACTION_CALL); intent.setData(Uri.parse("tel:" + dh)); startActivity(intent); break; case R.id.dx: Intent intent1 = new Intent(); intent1.setAction(intent1.ACTION_SENDTO); intent1.setData(Uri.parse("smsto:" + dh)); intent1.putExtra("sms_body", ""); startActivity(intent1); break; } return super.onContextItemSelected(item); } }
如何把scrapy爬出来的数据导入csv文件
import csv import pymysql from scrapy.exceptions import DropItem class UeinfoPipeline(object): def process_item(self, item, spider): list=[] pinpai = item["pinpai"][0] xinghao=item["xinghao"][0] yuefen=item["yuefen"][0] nianfen=item["nianfen"][0] list.append(pinpai) list.append(xinghao) list.append(yuefen) list.append(nianfen) with open("test.csv", "w") as csvfile: fieldnames = ['first_name', 'last_name','username'] writer=csv.DictWriter(csvfile,fieldnames=fieldnames) writer.writeheader() writer.writerows(list) return item def close_spider(self,spider): self.conn.close() 错误代码如下: Traceback (most recent call last): File "d:\programdata\anaconda3\lib\site-packages\twisted\internet\defer.py", line 653, in _runCallbacks current.result = callback(current.result, *args, **kw) File "D:\ueinfo\ueinfo\pipelines.py", line 36, in process_item writer.writerows(list) File "d:\programdata\anaconda3\lib\csv.py", line 158, in writerows return self.writer.writerows(map(self._dict_to_list, rowdicts)) File "d:\programdata\anaconda3\lib\csv.py", line 148, in _dict_to_list wrong_fields = rowdict.keys() - self.fieldnames AttributeError: 'str' object has no attribute 'keys' 2017-06-13 14:56:40 [scrapy.core.engine] INFO: Closing spider (finished) 2017-06-13 14:56:40 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
python算法编码问题咨询
以下是apriori关联算法的实例代码实现,是用python实现的,IDE是myeclipse,没有报错: #coding:utf-8 samples = [ ["I1","I2","I5"], ["I2","I4"], ["I2","I3"], ["I1","I2","I4"], ["I1","I3"], ["I2","I3"], ["I1","I3"], ["I1","I2","I3","I5"], ["I1","I2","I3"] ] min_support = 2 min_confidence = 0.6 fre_list = list() def get_c1(): global record_list global record_dict new_dict = dict() for row in samples: for item in row: if item not in fre_list: fre_list.append(item) new_dict[item] = 1 else: new_dict[item] = new_dict[item] + 1 fre_list.sort() print ("candidate set:") print_dict(new_dict) for key in fre_list: if new_dict[key] < min_support: del new_dict[key] print ("after pruning:") print_dict(new_dict) record_list = fre_list record_dict = record_dict def get_candidateset(): new_list = list() #自连接 for i in range(0,len(fre_list)): for j in range(0,len(fre_list)): if i == j: continue #如果两个k项集可以自连接,必须保证它们有k-1项是相同的 if has_samesubitem(fre_list[i],fre_list[j]): curitem = fre_list[i] + ',' + fre_list[j] curitem = curitem.split(",") curitem = list(set(curitem)) curitem.sort() curitem = ','.join(curitem) #如果一个k项集要成为候选集,必须保证它的所有子集都是频繁的 if has_infresubset(curitem) == False and already_constains(curitem,new_list) == False: new_list.append(curitem) new_list.sort() return new_list def has_samesubitem(str1,str2): str1s = str1.split(",") str2s = str2.split(",") if len(str1s) != len(str2s): return False nums = 0 for items in str1s: if items in str2s: nums += 1 str2s.remove(items) if nums == len(str1s) - 1: return True else: return False def judge(candidatelist): # 计算候选集的支持度 new_dict = dict() for item in candidatelist: new_dict[item] = get_support(item) print ("candidate set:") print_dict(new_dict) #剪枝 #频繁集的支持度要大于最小支持度 new_list = list() for item in candidatelist: if new_dict[item] < min_support: del new_dict[item] continue else: new_list.append(item) global fre_list fre_list = new_list print ("after pruning:") print_dict(new_dict) return new_dict def has_infresubset(item): # 由于是逐层搜索的,所以对于Ck候选集只需要判断它的k-1子集是否包含非频繁集即可 subset_list = get_subset(item.split(",")) for item_list in subset_list: if already_constains(item_list,fre_list) == False: return True return False def get_support(item,splitetag=True): if splitetag: items = item.split(",") else: items = item.split("^") support = 0 for row in samples: tag = True for curitem in items: if curitem not in row: tag = False continue if tag: support += 1 return support def get_fullpermutation(arr): if len(arr) == 1: return [arr] else: newlist = list() for i in range(0,len(arr)): sublist = get_fullpermutation(arr[0:i]+arr[i+1:len(arr)]) for item in sublist: curlist = list() curlist.append(arr[i]) curlist.extend(item) newlist.append(curlist) return newlist def get_subset(arr): newlist = list() for i in range(0,len(arr)): arr1 = arr[0:i]+arr[i+1:len(arr)] newlist1 = get_fullpermutation(arr1) for newlist_item in newlist1: newlist.append(newlist_item) newlist.sort() newlist = remove_dumplicate(newlist) return newlist def remove_dumplicate(arr): newlist = list() for i in range(0,len(arr)): if already_constains(arr[i],newlist) == False: newlist.append(arr[i]) return newlist def already_constains(item,curlist): import types items = list() if type(item) is types.StringType: items = item.split(",") else: items = item for i in range(0,len(curlist)): curitems = list() if type(curlist[i]) is types.StringType: curitems = curlist[i].split(",") else: curitems = curlist[i] if len(set(items)) == len(curitems) and len(list(set(items).difference(set(curitems)))) == 0: return True return False def print_dict(curdict): keys = curdict.keys() keys.sort() for curkey in keys: print ("%s:%s"%curkey,curdict[curkey]) # 计算关联规则的方法 def get_all_subset(arr): rtn = list() while True: subset_list = get_subset(arr) stop = False for subset_item_list in subset_list: if len(subset_item_list) == 1: stop = True rtn.append(subset_item_list) if stop: break return rtn def get_all_subses(s): from itertools import combinations return sum(map(lambda r: list(combinations(s, r)), range(1, len(s)+1)), []) def cal_associative_rule(frelist): rule_list = list() rule_dict = dict() for fre_item in frelist: fre_items = fre_item.split(",") subitem_list = get_all_subset(fre_items) for subitem in subitem_list: # 忽略为为自身的子集 if len(subitem) == len(fre_items): continue else: difference = set(fre_items).difference(subitem) rule_list.append("^".join(subitem)+"->"+"^".join(difference)) print ("The rule is:") for rule in rule_list: conf = cal_rule_confidency(rule) print (rule,conf) if conf >= min_confidence: rule_dict[rule] = conf print ("The associative rule is:") for key in rule_list: if key in rule_dict.keys(): print (key,":",rule_dict[key]) def cal_rule_confidency(rule): rules = rule.split("->") support1 = get_support("^".join(rules),False) support2 = get_support(rules[0],False) if support2 == 0: return 0 rule_confidency = float(support1)/float(support2) return rule_confidency if __name__ == '__main__': record_list = list() record_dict = dict() get_c1() # 不断进行自连接和剪枝,直到得到最终的频繁集为止;终止条件是,如果自连接得到的已经不再是频繁集 # 那么取最后一次得到的频繁集作为结果 while True: record_list = fre_list new_list = get_candidateset() judge_dict = judge(new_list) if len(judge_dict) == 0: break else: record_dict = judge_dict print ("The final frequency set is:") print (record_list) # 根据频繁集计算关联规则 cal_associative_rule(record_list) 运行后,出错,结果输出如下: Traceback (most recent call last): File "D:\Workspaces\MyEclipse 2017 CI\pythontest\src\pythontest.py", line 213, in <module> candidate set: get_c1() File "D:\Workspaces\MyEclipse 2017 CI\pythontest\src\pythontest.py", line 29, in get_c1 print_dict(new_dict) File "D:\Workspaces\MyEclipse 2017 CI\pythontest\src\pythontest.py", line 160, in print_dict keys.sort() AttributeError: 'dict_keys' object has no attribute 'sort' 找了很久,不知道出错点在哪,求指教。
mybatis调用存储过程返回cursor没有值
我自己写的测试程序,下面是配置文件和代码,jdbc里是已经取到resultset了,而且也可以遍历出来值,但是最后返回的list是空,请大神帮忙看一下是哪里错了 java代码: ``` String statement="me.gacl.mapping.userMapper.getDateTime"; Map<String, Object> param = new HashMap<String, Object>(); param.put("v_Sequences", "aaa"); param.put("v_refcur",KBTypeInfo.CURSOR); List<Curs> l = session.selectList(statement, param); System.out.println(l.size()); ``` 下面是配置文件部分内容 ``` <select id="getDateTime" statementType="CALLABLE" parameterType="map" resultMap="DateResult" resultOrdered="true"> { call getdatatime1( #{v_Sequences,jdbcType=VARCHAR,mode=IN}, #{v_refcur,jdbcType=CURSOR,mode=OUT,javaType=java.sql.ResultSet,resultMap=DateResult} ) } </select> <resultMap type ="me.domain.Curs" id="DateResult"> <result column="A" property="a"/> </resultMap> ```
org.springframework.beans.factory.UnsatisfiedDependencyException
ssm+maven入门: 头一次用ssm框架,还使用了maven,还用了mybatis-Generator生成bean、mapper等相关文件,写了一些代码后部署在tomcat上,然后tomcat异常: 异常为: ``` 四月 21, 2019 9:32:37 下午 org.apache.catalina.core.StandardContext listenerStart 严重: Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener] org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDaoImpl': Unsatisfied dependency expressed through field 'userExample'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xinkai.bean.UserExample' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:849) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:400) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:291) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4643) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5105) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1425) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1415) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:941) at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:839) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1425) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1415) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:941) at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:258) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:770) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) at org.apache.catalina.startup.Catalina.start(Catalina.java:657) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:355) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:495) Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xinkai.bean.UserExample' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1654) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1213) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ... 45 more 四月 21, 2019 9:32:37 下午 org.apache.catalina.core.StandardContext startInternal 严重: One or more listeners failed to start. Full details will be found in the appropriate container log file 四月 21, 2019 9:32:37 下午 org.apache.catalina.core.StandardContext startInternal 严重: Context [/maven-ssm] startup failed due to previous errors 四月 21, 2019 9:32:37 下午 org.apache.catalina.core.ApplicationContext log 信息: Closing Spring root WebApplicationContext 四月 21, 2019 9:32:37 下午 org.apache.coyote.AbstractProtocol start 信息: Starting ProtocolHandler ["http-nio-8080"] 四月 21, 2019 9:32:37 下午 org.apache.coyote.AbstractProtocol start 信息: Starting ProtocolHandler ["ajp-nio-8009"] 四月 21, 2019 9:32:37 下午 org.apache.catalina.startup.Catalina start 信息: Server startup in 9131 ms ``` 异常中提到的相关类为: ``` package com.xinkai.bean; import java.util.ArrayList; import java.util.List; public class UserExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public UserExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andUsernameIsNull() { addCriterion("username is null"); return (Criteria) this; } public Criteria andUsernameIsNotNull() { addCriterion("username is not null"); return (Criteria) this; } public Criteria andUsernameEqualTo(String value) { addCriterion("username =", value, "username"); return (Criteria) this; } public Criteria andUsernameNotEqualTo(String value) { addCriterion("username <>", value, "username"); return (Criteria) this; } public Criteria andUsernameGreaterThan(String value) { addCriterion("username >", value, "username"); return (Criteria) this; } public Criteria andUsernameGreaterThanOrEqualTo(String value) { addCriterion("username >=", value, "username"); return (Criteria) this; } public Criteria andUsernameLessThan(String value) { addCriterion("username <", value, "username"); return (Criteria) this; } public Criteria andUsernameLessThanOrEqualTo(String value) { addCriterion("username <=", value, "username"); return (Criteria) this; } public Criteria andUsernameLike(String value) { addCriterion("username like", value, "username"); return (Criteria) this; } public Criteria andUsernameNotLike(String value) { addCriterion("username not like", value, "username"); return (Criteria) this; } public Criteria andUsernameIn(List<String> values) { addCriterion("username in", values, "username"); return (Criteria) this; } public Criteria andUsernameNotIn(List<String> values) { addCriterion("username not in", values, "username"); return (Criteria) this; } public Criteria andUsernameBetween(String value1, String value2) { addCriterion("username between", value1, value2, "username"); return (Criteria) this; } public Criteria andUsernameNotBetween(String value1, String value2) { addCriterion("username not between", value1, value2, "username"); return (Criteria) this; } public Criteria andPasswordIsNull() { addCriterion("password is null"); return (Criteria) this; } public Criteria andPasswordIsNotNull() { addCriterion("password is not null"); return (Criteria) this; } public Criteria andPasswordEqualTo(String value) { addCriterion("password =", value, "password"); return (Criteria) this; } public Criteria andPasswordNotEqualTo(String value) { addCriterion("password <>", value, "password"); return (Criteria) this; } public Criteria andPasswordGreaterThan(String value) { addCriterion("password >", value, "password"); return (Criteria) this; } public Criteria andPasswordGreaterThanOrEqualTo(String value) { addCriterion("password >=", value, "password"); return (Criteria) this; } public Criteria andPasswordLessThan(String value) { addCriterion("password <", value, "password"); return (Criteria) this; } public Criteria andPasswordLessThanOrEqualTo(String value) { addCriterion("password <=", value, "password"); return (Criteria) this; } public Criteria andPasswordLike(String value) { addCriterion("password like", value, "password"); return (Criteria) this; } public Criteria andPasswordNotLike(String value) { addCriterion("password not like", value, "password"); return (Criteria) this; } public Criteria andPasswordIn(List<String> values) { addCriterion("password in", values, "password"); return (Criteria) this; } public Criteria andPasswordNotIn(List<String> values) { addCriterion("password not in", values, "password"); return (Criteria) this; } public Criteria andPasswordBetween(String value1, String value2) { addCriterion("password between", value1, value2, "password"); return (Criteria) this; } public Criteria andPasswordNotBetween(String value1, String value2) { addCriterion("password not between", value1, value2, "password"); return (Criteria) this; } public Criteria andTypeIsNull() { addCriterion("type is null"); return (Criteria) this; } public Criteria andTypeIsNotNull() { addCriterion("type is not null"); return (Criteria) this; } public Criteria andTypeEqualTo(Integer value) { addCriterion("type =", value, "type"); return (Criteria) this; } public Criteria andTypeNotEqualTo(Integer value) { addCriterion("type <>", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThan(Integer value) { addCriterion("type >", value, "type"); return (Criteria) this; } public Criteria andTypeGreaterThanOrEqualTo(Integer value) { addCriterion("type >=", value, "type"); return (Criteria) this; } public Criteria andTypeLessThan(Integer value) { addCriterion("type <", value, "type"); return (Criteria) this; } public Criteria andTypeLessThanOrEqualTo(Integer value) { addCriterion("type <=", value, "type"); return (Criteria) this; } public Criteria andTypeIn(List<Integer> values) { addCriterion("type in", values, "type"); return (Criteria) this; } public Criteria andTypeNotIn(List<Integer> values) { addCriterion("type not in", values, "type"); return (Criteria) this; } public Criteria andTypeBetween(Integer value1, Integer value2) { addCriterion("type between", value1, value2, "type"); return (Criteria) this; } public Criteria andTypeNotBetween(Integer value1, Integer value2) { addCriterion("type not between", value1, value2, "type"); return (Criteria) this; } public Criteria andCreatetimeIsNull() { addCriterion("createTime is null"); ``` ``` return (Criteria) this; } public Criteria andCreatetimeIsNotNull() { addCriterion("createTime is not null"); return (Criteria) this; } public Criteria andCreatetimeEqualTo(String value) { addCriterion("createTime =", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeNotEqualTo(String value) { addCriterion("createTime <>", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeGreaterThan(String value) { addCriterion("createTime >", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeGreaterThanOrEqualTo(String value) { addCriterion("createTime >=", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeLessThan(String value) { addCriterion("createTime <", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeLessThanOrEqualTo(String value) { addCriterion("createTime <=", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeLike(String value) { addCriterion("createTime like", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeNotLike(String value) { addCriterion("createTime not like", value, "createtime"); return (Criteria) this; } public Criteria andCreatetimeIn(List<String> values) { addCriterion("createTime in", values, "createtime"); return (Criteria) this; } public Criteria andCreatetimeNotIn(List<String> values) { addCriterion("createTime not in", values, "createtime"); return (Criteria) this; } public Criteria andCreatetimeBetween(String value1, String value2) { addCriterion("createTime between", value1, value2, "createtime"); return (Criteria) this; } public Criteria andCreatetimeNotBetween(String value1, String value2) { addCriterion("createTime not between", value1, value2, "createtime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } } ``` ``` package com.xinkai.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.xinkai.bean.User; import com.xinkai.bean.UserExample; import com.xinkai.bean.UserExample.Criteria; import com.xinkai.mapper.UserMapper; /** * Created by xinkai ``` ``` * Created time:2019年4月21日 上午11:27:50 * description */ @Component public class UserDaoImpl implements UserDao { @Autowired private UserMapper userMapper; @Autowired private UserExample userExample; /** * 注册防止重名 */ @Override public List<User> selectByName(User user) { // TODO Auto-generated method stub Criteria criteria= userExample.createCriteria(); criteria.andUsernameEqualTo(user.getUsername()); criteria.andTypeEqualTo(user.getType()); List<User> list=userMapper.selectByExample(userExample); return list; } /** * 用户注册 */ @Override public int insertUser(User user) { // TODO Auto-generated method stub int result = userMapper.insert(user); return result; } /** * 用户登录 */ @Override public List<User> login(User user) { // TODO Auto-generated method stub Criteria criteria = userExample.createCriteria(); criteria.andUsernameEqualTo(user.getUsername()); criteria.andPasswordEqualTo(user.getPassword()); criteria.andTypeEqualTo(user.getType()); List<User> list= userMapper.selectByExample(userExample); return list; } /** * 用户更新个人信息 */ @Override public int updateUser(User user) { // TODO Auto-generated method stub int result = userMapper.updateByPrimaryKey(user); return result; } } package com.xinkai.controller; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import com.xinkai.bean.User; import com.xinkai.service.UserDao; /** * @author xinkai E-mail:1079463993@qq.com * @version 创建时间:2019年4月20日 上午11:39:24 * 类说明 Controller */ @Controller public class UserController { // @Resource(name = "userDao") @Autowired private UserDao userDao; /** * Create by xinkai 2019年4月20日下午4:00:51 * 用户注册,不可注册同名用户 * @param map * @param user * @return */ @RequestMapping("regist.do") public String regist(){ return "login"; } @RequestMapping("doRegist.do") public String doRegist(ModelMap map,User user){ user.setType(1); List<User> list=userDao.selectByName(user); if(list.size()!=0) { map.addAttribute("tips", "该用户名已存在"); return "login"; } String date=new Date().toLocaleString().substring(0, 10).trim(); user.setCreatetime(date); int result = userDao.insertUser(user); if(result == 0) { map.addAttribute("tips", "注册出现异常,请重试"); return "login"; } return "login"; } /** * Create by xinkai 2019年4月20日下午2:20:28 * 用户登录 * @return */ @RequestMapping("userlogin.do") public String userLogin() { return "login"; } @RequestMapping("doUserLogin.do") public String doUserLogin(HttpServletRequest request,ModelMap map,User user){ List<User>list=userDao.login(user); if (list.isEmpty()){ map.addAttribute("tips", "用户名或密码错误"); return "login"; }else{ HttpSession session=request.getSession(); session.setAttribute("user", list.get(0)); return "index"; } } /** * Create by xinkai 2019年4月20日下午2:28:24 * 用户退出账号 * @param request * @return */ @RequestMapping("doLogout") public String doLogout(HttpServletRequest request) { HttpSession session = request.getSession(); session.removeAttribute("user"); return "index"; } /** * Create by xinkai 2019年4月20日下午2:38:01 * 用户查询自己的信息 * @param request * @param map * @return */ @RequestMapping("userInfo") public String userInfo(HttpServletRequest request,ModelMap map){ HttpSession session=request.getSession(); User user=(User) session.getAttribute("user"); map.addAttribute("user", user); return "userInfo"; } /** * Create by xinkai 2019年4月20日下午2:47:32 * 用户修改密码 * @param map * @param user * @return */ @RequestMapping("updateUserInfo") public String updateUserInfo(ModelMap map,User user) { int result = userDao.updateUser(user); if (result==0){ map.addAttribute("tips", "相关信息更新失败!"); return "userInfo"; } return "login"; } } ``` 我哪里的问题?
用create_pascal_tf_record.py时候出现的问题!
这是我用create_pascal_tf_record.py出现的错误 ``` D:\tensorflow\models\research\object_detection>python dataset_tools\create_pascal_tf_record.py --label_map=D:\tensorflow\pedestrain_train\data\label_map.pbtxt --data_dir=D:\pedestrain_data --year=VOC2012 --set=train --output_path=D:\pascal_train.record Traceback (most recent call last): File "dataset_tools\create_pascal_tf_record.py", line 185, in <module> tf.app.run() File "C:\anaconda\lib\site-packages\tensorflow\python\platform\app.py", line 125, in run _sys.exit(main(argv)) File "dataset_tools\create_pascal_tf_record.py", line 167, in main examples_list = dataset_util.read_examples_list(examples_path) File "D:\ssd-detection\models-master\research\object_detection\utils\dataset_util.py", line 59, in read_examples_list lines = fid.readlines() File "C:\anaconda\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 188, in readlines self._preread_check() File "C:\anaconda\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 85, in _preread_check compat.as_bytes(self.__name), 1024 * 512, status) File "C:\anaconda\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 519, in __exit__ c_api.TF_GetCode(self.status.status)) tensorflow.python.framework.errors_impl.NotFoundError: NewRandomAccessFile failed to Create/Open: D:\pedestrain_data\VOC2012\ImageSets\Main\aeroplane_train.txt : \u03f5\u0373\udcd5\u04b2\udcbb\udcb5\udcbd\u05b8\udcb6\udca8\udcb5\udcc4\udcce\u013c\udcfe\udca1\udca3 ; No such file or directory ``` 可是我的main文件夹里面是pedestrain_train.txt和pedestrain_val.txt为什么他要去找aeroplane_train.txt这个文件呢
oracle 存储过程 返回复合数据类型(index by表) ibatis如何接受
最近有个问题一直困扰着,希望各位能给予帮助。 先贴代码: 1 <parameterMap class="map" id="UserIndexParam"> 2 <parameter property="PRM_USERID" javaType="java.lang.Object" 3 jdbcType="Object" mode="IN" /> 4 <parameter property="PRM_OBJECTS" javaType="java.sql.ResultSet" 5 jdbcType="ARRAY" mode="OUT" typeHandler="com.diy.object.entity.ObjectTypeHandler" /> 6 <parameter property="PRM_TAGS" javaType="java.sql.ResultSet" 7 jdbcType="ARRAY" mode="OUT" typeHandler="com.diy.tag.entity.TagsTypeHandler" /> 8 <parameter property="PRM_APPCODE" javaType="java.lang.String" 9 jdbcType="VARCHAR" mode="OUT" /> 10 <parameter property="PRM_ERRMSG" javaType="java.lang.String" 11 jdbcType="VARCHAR" mode="OUT" /> 12 </parameterMap> 13 14 <procedure id="prc_user_index" parameterMap="UserIndexParam"> 15 {call 16 PKG_USER.PRC_USER_INDEXVIEW(?,?,?,?,?)} 17 </procedure> 这个ibatis的配置文件. 在网上查了很久,说是用typeHandler和jdbcType来解决解决oracle复合类型, 1 package com.diy.tag.entity; 2 3 import java.sql.CallableStatement; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.util.ArrayList; 8 import java.util.List; 9 10 import oracle.sql.Datum; 11 import oracle.sql.STRUCT; 12 13 import com.ibatis.sqlmap.engine.type.TypeHandler; 14 15 public class TagsTypeHandler implements TypeHandler { 16 17 /** 18 * @Description: 这个方法重点 19 * @param cs 20 * @param arg1 21 * @throws SQLException 22 */ 23 public java.lang.Object getResult(CallableStatement cs, int arg1) 24 throws SQLException { 25 List<Tag> list = new ArrayList<Tag>(); 26 ResultSet rs = cs.getArray(arg1).getResultSet(); 27 while (rs.next()) { 28 Datum[] data = ((STRUCT)rs.getObject(2)).getOracleAttributes(); 29 Tag tag = new Tag(); 30 if (data[0] != null) { 31 tag.setTagid(new Long(data[0].getBytes().toString())); 32 } 33 list.add(tag); 34 } 35 return list; 36 } 37 38 @Override 39 public boolean equals(java.lang.Object arg0, String arg1) { 40 // TODO Auto-generated method stub 41 return false; 42 } 43 44 @Override 45 public java.lang.Object getResult(ResultSet arg0, String arg1) 46 throws SQLException { 47 // TODO Auto-generated method stub 48 return null; 49 } 50 51 @Override 52 public java.lang.Object getResult(ResultSet arg0, int arg1) 53 throws SQLException { 54 // TODO Auto-generated method stub 55 return null; 56 } 57 58 59 60 @Override 61 public void setParameter(PreparedStatement arg0, int arg1, 62 java.lang.Object arg2, String arg3) throws SQLException { 63 // TODO Auto-generated method stub 64 65 } 66 67 @Override 68 public java.lang.Object valueOf(String arg0) { 69 // TODO Auto-generated method stub 70 return null; 71 } 72 73 } 这个是java代码,其中一个handler处理类 1 --定义 object表 对象 2 TYPE object_arr IS TABLE OF OBJECT%ROWTYPE INDEX BY BINARY_INTEGER; 3 4 --定义 tag index_by表 5 TYPE table_tag IS TABLE OF TAGS_INFO INDEX BY BINARY_INTEGER; 这个定义的oracle复合类型 1 PROCEDURE PRC_USER_INDEXVIEW(PRM_USERID IN VARCHAR2, 2 PRM_OBJECTS OUT PKG_COMM.OBJECT_ARR, 3 PRM_TAGS OUT PKG_COMM.table_tag, 4 PRM_APPCODE OUT VARCHAR2, 5 PRM_ERRMSG OUT VARCHAR2) IS 6 N_FLAG NUMBER; 7 VAR_FIRSTTAG VARCHAR2(100); 8 VAR_DUSERID VARCHAR2(100); 9 --用户兴趣标签 10 CURSOR CUR_USERTAG IS 11 SELECT C.TAGID, C.NAME 12 FROM USERSDETIAL A, TAGRELATION B, TAG C 13 WHERE A.DUSERSID = B.DUSERSID 14 AND B.TAGID = C.TAGID 15 AND A.DUSERSID = VAR_DUSERID; 16 --公共兴趣标签 17 CURSOR CUR_USERPUB IS 18 SELECT T.* 19 FROM (SELECT ROWNUM AS RNUM, 20 COUNT(A.DUSERSID) AS CNUM, 21 B.TAGID, 22 B.NAME 23 FROM TAGRELATION A, TAG B 24 WHERE A.TAGID = B.TAGID 25 GROUP BY A.TAGID) T 26 WHERE RNUM <= 8 27 ORDER BY T.CNUM DESC; 28 --object 29 CURSOR CUR_OBJ(VAR_TAGID VARCHAR2) IS 30 SELECT ROWNUM AS RN, A.* 31 FROM OBJECT A 32 WHERE trim(A.TAGID) = VAR_TAGID 33 AND ROWNUM < 30; 34 35 REC_USERTAG CUR_USERTAG%ROWTYPE; 36 REC_USERPUB CUR_USERPUB%ROWTYPE; 37 REC_OBJ OBJECT%ROWTYPE; 38 BEGIN 39 PRM_APPCODE := PKG_COMM.DEF_OK; 40 PRM_ERRMSG := ''; 41 42 IF PRM_USERID IS NULL THEN 43 PRM_APPCODE := PKG_COMM.DEF_ERR; 44 PRM_ERRMSG := '参数未定义'; 45 RETURN; 46 END IF; 47 --用户详细ID是否存在 48 SELECT B.DUSERSID 49 INTO VAR_DUSERID 50 FROM USERS A, USERSDETIAL B 51 WHERE A.USERID = B.USERSID 52 AND A.USERID = PRM_USERID; 53 IF VAR_DUSERID IS NULL THEN 54 PRM_APPCODE := PKG_COMM.DEF_ERR; 55 PRM_ERRMSG := '参数无效'; 56 RETURN; 57 END IF; 58 --1.判断是否为有效用户 59 SELECT NVL(A.FLAG, 1) 60 INTO N_FLAG 61 FROM USERS A, USERSDETIAL B 62 WHERE A.Userid = B.USERSID 63 AND B.DUSERSID = VAR_DUSERID; 64 65 IF N_FLAG = 1 THEN 66 PRM_APPCODE := PKG_COMM.DEF_ERR; 67 PRM_ERRMSG := '用户已被禁止登录'; 68 RETURN; 69 END IF; 70 71 --2.判断用户是否有兴趣tag 72 73 FOR REC_USERTAG IN CUR_USERTAG LOOP 74 75 IF CUR_USERTAG%ROWCOUNT = 0 THEN 76 --获取公共兴趣游标 77 FOR REC_USERPUB IN CUR_USERPUB LOOP 78 IF CUR_USERPUB%ROWCOUNT = 1 THEN 79 VAR_FIRSTTAG := REC_USERPUB.TAGID; 80 END IF; 81 PRM_TAGS(CUR_USERPUB%ROWCOUNT).TAGID := REC_USERPUB.TAGID; 82 PRM_TAGS(CUR_USERPUB%ROWCOUNT).TAGNAME := REC_USERPUB.NAME; 83 END LOOP; 84 ELSIF CUR_USERTAG%ROWCOUNT = 1 THEN 85 VAR_FIRSTTAG := REC_USERTAG.TAGID; 86 END IF; 87 PRM_TAGS(CUR_USERTAG%ROWCOUNT).TAGID := REC_USERTAG.TAGID; 88 PRM_TAGS(CUR_USERTAG%ROWCOUNT).TAGNAME := REC_USERTAG.NAME; 89 END LOOP; 90 91 IF PRM_TAGS.count <> 0 THEN 92 --3. 取出object 93 FOR REC_OBJ IN CUR_OBJ(VAR_FIRSTTAG) LOOP 94 PRM_OBJECTS(CUR_OBJ%ROWCOUNT).OWNERID := REC_OBJ.OWNERID; 95 PRM_OBJECTS(CUR_OBJ%ROWCOUNT).OBJECTID := REC_OBJ.OBJECTID; 96 PRM_OBJECTS(CUR_OBJ%ROWCOUNT).DBUSID := REC_OBJ.DBUSID; 97 PRM_OBJECTS(CUR_OBJ%ROWCOUNT).DUSERSID := REC_OBJ.DUSERSID; 98 PRM_OBJECTS(CUR_OBJ%ROWCOUNT).TAGID := REC_OBJ.TAGID; 99 PRM_OBJECTS(CUR_OBJ%ROWCOUNT).LOVENUM := REC_OBJ.LOVENUM; 100 PRM_OBJECTS(CUR_OBJ%ROWCOUNT).INRUDUCTION := REC_OBJ.INRUDUCTION; 101 PRM_OBJECTS(CUR_OBJ%ROWCOUNT).CATAGROY := REC_OBJ.CATAGROY; 102 PRM_OBJECTS(CUR_OBJ%ROWCOUNT).Imagepath := REC_OBJ.Imagepath; 103 104 END LOOP; 105 END IF; 106 107 EXCEPTION 108 WHEN OTHERS THEN 109 PRM_APPCODE := PKG_COMM.DEF_ERR; 110 PRM_ERRMSG := '获取主界面数据失败' || '错误原因:' || PRM_ERRMSG || '-' || SQLERRM || 111 '错误行数:' || DBMS_UTILITY.FORMAT_ERROR_BACKTRACE(); 112 END; 这个是存储过程的实现,过程没有问题,plsql调试正常!!! 现在我可以确定问题在 1.ibatis xml文件中jdbcType 和typeHandler的配置问题 1 <parameter property="PRM_OBJECTS" javaType="java.sql.ResultSet" 2 5 jdbcType="ARRAY" mode="OUT" typeHandler="com.diy.object.entity.ObjectTypeHandler" /> 3 6 <parameter property="PRM_TAGS" javaType="java.sql.ResultSet" 4 7 jdbcType="ARRAY" mode="OUT" typeHandler="com.diy.tag.entity.TagsTypeHandler" /> 2.java typeHandler类的返回值 还有一个附带的问题:index by 表不能在数据库中存储,而嵌套表可以存储在数据库中。是不是说index by 表 像java 方法中声明的变量,方法结束,其变量的生命周期就结束了??? 谢谢!!!
滑动窗口协议模拟用vc++/mfc做的,其中代码缺少.rc文件不能在vc++6.0上运行!!怎么补
求教!! // Sender.cpp : Defines the class behaviors for the application. #include "stdafx.h" #include "Sender.h" #include "SenderDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // CSenderApp BEGIN_MESSAGE_MAP(CSenderApp, CWinApp) //{{AFX_MSG_MAP(CSenderApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() // CSenderApp construction CSenderApp::CSenderApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CSenderApp object CSenderApp theApp; // CSenderApp initialization BOOL CSenderApp::InitInstance() { AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif CSenderDlg dlg; m_pMainWnd = &dlg; int nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; } //Protocol.h文件 #ifndef _PROTOCOL_H_ #define _PROTOCOL_H_ #define MAX_PKT 1024 typedef UINT seqNum; typedef enum { DATA, ACK, NAK } frameKind; typedef enum { NO_ERR, CKSUM_ERR, LOST_ERR } errMode; typedef struct { UCHAR data[MAX_PKT]; } packet; typedef struct { frameKind kind; seqNum seq; seqNum ack; int size; //数据长度,不包括帧头 errMode err; //该字段用于模拟信道出错 } frame_hdr; typedef struct { frame_hdr hdr; packet info; } frame; #endif //_PROTOCOL_H_ //resource.h文件 // Used by Sender.rc #define IDM_ABOUTBOX 0x0010 #define IDD_ABOUTBOX 100 #define IDS_ABOUTBOX 101 #define IDD_SENDER_DIALOG 102 #define IDP_SOCKETS_INIT_FAILED 103 #define IDR_MAINFRAME 128 #define IDR_MENU_POPUP 129 #define IDC_LIST_OUTPUT 1000 #define IDC_STOP_SEND 1003 #define IDC_SEND_WND_SIZE 1005 #define IDC_SEND_INTERVAL 1006 #define IDC_RESEND_TIMER 1007 #define IDC_CHKSUM_ERR 1008 #define IDC_RANDOM_ERR 1009 #define IDC_MANUAL_ERR 1010 #define IDC_FRAME_LOST 1011 #define IDC_CUR_FRAME 1012 #define IDC_BOTTOM 1013 #define IDC_TOP 1014 #define IDC_START_SEND 1015 #define ID_MENU_CLEANUP 32771
java调用Web Service时,代码报错org.xml.sax.SAXException
![图片说明](https://img-ask.csdn.net/upload/201612/07/1481101881_669159.png) 程序要用的lib是老师以前给的,其实我也不知道哪些是不需要的就全加进去了。我加进去的lib如上图。 代码如下,调用服务的网站为www.gpsso.com,我想调用里面的快递查询的方法,然后返回查询到的物流信息。 求大神帮忙改改错,或者能帮忙写个例子。 谢谢大家了 import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Vector; import javax.xml.namespace.QName; import org.apache.axis.client.Call; import org.apache.axis.client.Service; import org.apache.axis.encoding.XMLType; public class PutExpress { private String url = "http://www.gpsso.com/webservice/kuaidi/kuaidi.asmx";;//提供接口的地址 private String soapaction = "http://gpsso.com/";; //域名,这是在server定义的 private String operationName = "KuaidiQuery"; public PutExpress() { Scanner in = new Scanner(System.in); String Compay=in.nextLine(); String OrderNo=in.nextLine(); Service service=new Service(); try{ Call call=(Call)service.createCall(); call.setTargetEndpointAddress(url); call.setOperationName(new QName(soapaction,operationName)); //设置要调用哪个方法 call.addParameter(new QName(soapaction,"Compay"), //设置要传递的参数 org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN); call.addParameter(new QName(soapaction,"OrderNo"), //设置要传递的参数 org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN); call.setReturnType(new QName(soapaction,operationName),Vector.class); //要返回的数据类型(自定义类型) //call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);//(标准的类型) call.setUseSOAPAction(true); call.setSOAPActionURI(soapaction + operationName); Vector v=(Vector)call.invoke(new Object[]{Compay,OrderNo});//调用方法并传递参数 for(int i=0;i<v.size();i++) { System.out.println(v.get(i)); } }catch(Exception ex) { ex.printStackTrace(); } } public static void main(String args[]) { PutExpress pw=new PutExpress(); } } 我是刚接触到web service的菜鸟,希望能有大大帮忙解决一下。
用tensorflow做机器翻译时训练代码有问题
``` # -*- coding:UTF-8 -*- import tensorflow as tf src_path = 'D:/Python37/untitled1/train.tags.en-zh.en.deletehtml' trg_path = 'D:/Python37/untitled1/train.tags.en-zh.zh.deletehtml' SRC_TRAIN_DATA = 'D:/Python37/untitled1/train.tags.en-zh.en.deletehtml.segment' # 源语言输入文件 TRG_TRAIN_DATA = 'D:/Python37/untitled1/train.tags.en-zh.zh.deletehtml.segment' # 目标语言输入文件 CHECKPOINT_PATH = './model/seq2seq_ckpt' # checkpoint保存路径 HIDDEN_SIZE = 1024 # LSTM的隐藏层规模 NUM_LAYERS = 2 # 深层循环神经网络中LSTM结构的层数 SRC_VOCAB_SIZE = 10000 # 源语言词汇表大小 TRG_VOCAB_SIZE = 4000 # 目标语言词汇表大小 BATCH_SIZE = 100 # 训练数据batch的大小 NUM_EPOCH = 5 # 使用训练数据的轮数 KEEP_PROB = 0.8 # 节点不被dropout的概率 MAX_GRAD_NORM = 5 # 用于控制梯度膨胀的梯度大小上限 SHARE_EMB_AND_SOFTMAX = True # 在softmax层和词向量层之间共享参数 MAX_LEN = 50 # 限定句子的最大单词数量 SOS_ID = 1 # 目标语言词汇表中<sos>的ID """ function: 数据batching,产生最后输入数据格式 Parameters: file_path-数据路径 Returns: dataset- 每个句子-对应的长度组成的TextLineDataset类的数据集对应的张量 """ def MakeDataset(file_path): dataset = tf.data.TextLineDataset(file_path) # map(function, sequence[, sequence, ...]) -> list # 通过定义可以看到,这个函数的第一个参数是一个函数,剩下的参数是一个或多个序列,返回值是一个集合。 # function可以理解为是一个一对一或多对一函数,map的作用是以参数序列中的每一个元素调用function函数,返回包含每次function函数返回值的list。 # lambda argument_list: expression # 其中lambda是Python预留的关键字,argument_list和expression由用户自定义 # argument_list参数列表, expression 为函数表达式 # 根据空格将单词编号切分开并放入一个一维向量 dataset = dataset.map(lambda string: tf.string_split([string]).values) # 将字符串形式的单词编号转化为整数 dataset = dataset.map(lambda string: tf.string_to_number(string, tf.int32)) # 统计每个句子的单词数量,并与句子内容一起放入Dataset dataset = dataset.map(lambda x: (x, tf.size(x))) return dataset """ function: 从源语言文件src_path和目标语言文件trg_path中分别读取数据,并进行填充和batching操作 Parameters: src_path-源语言,即被翻译的语言,英语. trg_path-目标语言,翻译之后的语言,汉语. batch_size-batch的大小 Returns: dataset- 每个句子-对应的长度 组成的TextLineDataset类的数据集 """ def MakeSrcTrgDataset(src_path, trg_path, batch_size): # 首先分别读取源语言数据和目标语言数据 src_data = MakeDataset(src_path) trg_data = MakeDataset(trg_path) # 通过zip操作将两个Dataset合并为一个Dataset,现在每个Dataset中每一项数据ds由4个张量组成 # ds[0][0]是源句子 # ds[0][1]是源句子长度 # ds[1][0]是目标句子 # ds[1][1]是目标句子长度 #https://blog.csdn.net/qq_32458499/article/details/78856530这篇博客看一下可以细致了解一下Dataset这个库,以及.map和.zip的用法 dataset = tf.data.Dataset.zip((src_data, trg_data)) # 删除内容为空(只包含<eos>)的句子和长度过长的句子 def FilterLength(src_tuple, trg_tuple): ((src_input, src_len), (trg_label, trg_len)) = (src_tuple, trg_tuple) # tf.logical_and 相当于集合中的and做法,后面两个都为true最终结果才会为true,否则为false # tf.greater Returns the truth value of (x > y),所以以下所说的是句子长度必须得大于一也就是不能为空的句子 # tf.less_equal Returns the truth value of (x <= y),所以所说的是长度要小于最长长度 src_len_ok = tf.logical_and(tf.greater(src_len, 1), tf.less_equal(src_len, MAX_LEN)) trg_len_ok = tf.logical_and(tf.greater(trg_len, 1), tf.less_equal(trg_len, MAX_LEN)) return tf.logical_and(src_len_ok, trg_len_ok) #两个都满足才返回true # filter接收一个函数Func并将该函数作用于dataset的每个元素,根据返回值True或False保留或丢弃该元素,True保留该元素,False丢弃该元素 # 最后得到的就是去掉空句子和过长的句子的数据集 dataset = dataset.filter(FilterLength) # 解码器需要两种格式的目标句子: # 1.解码器的输入(trg_input), 形式如同'<sos> X Y Z' # 2.解码器的目标输出(trg_label), 形式如同'X Y Z <eos>' # 上面从文件中读到的目标句子是'X Y Z <eos>'的形式,我们需要从中生成'<sos> X Y Z'形式并加入到Dataset # 编码器只有输入,没有输出,而解码器有输入也有输出,输入为<sos>+(除去最后一位eos的label列表) # 例如train.en最后都为2,id为2就是eos def MakeTrgInput(src_tuple, trg_tuple): ((src_input, src_len), (trg_label, trg_len)) = (src_tuple, trg_tuple) # tf.concat用法 https://blog.csdn.net/qq_33431368/article/details/79429295 trg_input = tf.concat([[SOS_ID], trg_label[:-1]], axis=0) return ((src_input, src_len), (trg_input, trg_label, trg_len)) dataset = dataset.map(MakeTrgInput) # 随机打乱训练数据 dataset = dataset.shuffle(10000) # 规定填充后的输出的数据维度 padded_shapes = ( (tf.TensorShape([None]), # 源句子是长度未知的向量 tf.TensorShape([])), # 源句子长度是单个数字 (tf.TensorShape([None]), # 目标句子(解码器输入)是长度未知的向量 tf.TensorShape([None]), # 目标句子(解码器目标输出)是长度未知的向量 tf.TensorShape([])) # 目标句子长度(输出)是单个数字 ) # 调用padded_batch方法进行padding 和 batching操作 batched_dataset = dataset.padded_batch(batch_size, padded_shapes) return batched_dataset """ function: seq2seq模型 Parameters: Returns: """ class NMTModel(object): """ function: 模型初始化 Parameters: Returns: """ def __init__(self): # 定义编码器和解码器所使用的LSTM结构 self.enc_cell = tf.nn.rnn_cell.MultiRNNCell( [tf.nn.rnn_cell.LSTMCell(HIDDEN_SIZE) for _ in range(NUM_LAYERS)]) self.dec_cell = tf.nn.rnn_cell.MultiRNNCell( [tf.nn.rnn_cell.LSTMCell(HIDDEN_SIZE) for _ in range(NUM_LAYERS)]) # 为源语言和目标语言分别定义词向量 self.src_embedding = tf.get_variable('src_emb', [SRC_VOCAB_SIZE, HIDDEN_SIZE]) self.trg_embedding = tf.get_variable('trg_emb', [TRG_VOCAB_SIZE, HIDDEN_SIZE]) # 定义softmax层的变量 if SHARE_EMB_AND_SOFTMAX: self.softmax_weight = tf.transpose(self.trg_embedding) else: self.softmax_weight = tf.get_variable('weight', [HIDDEN_SIZE, TRG_VOCAB_SIZE]) self.softmax_bias = tf.get_variable('softmax_loss', [TRG_VOCAB_SIZE]) """ function: 在forward函数中定义模型的前向计算图 Parameters:   MakeSrcTrgDataset函数产生的五种张量如下(全部为张量) src_input: 编码器输入(源数据) src_size : 输入大小 trg_input:解码器输入(目标数据) trg_label:解码器输出(目标数据) trg_size: 输出大小 Returns: """ def forward(self, src_input, src_size, trg_input, trg_label, trg_size): batch_size = tf.shape(src_input)[0] # 将输入和输出单词转为词向量(rnn中输入数据都要转换成词向量) # 相当于input中的每个id对应的embedding中的向量转换 src_emb = tf.nn.embedding_lookup(self.src_embedding, src_input) trg_emb = tf.nn.embedding_lookup(self.trg_embedding, trg_input) # 在词向量上进行dropout src_emb = tf.nn.dropout(src_emb, KEEP_PROB) trg_emb = tf.nn.dropout(trg_emb, KEEP_PROB) # 使用dynamic_rnn构造编码器 # 编码器读取源句子每个位置的词向量,输出最后一步的隐藏状态enc_state # 因为编码器是一个双层LSTM,因此enc_state是一个包含两个LSTMStateTuple类的tuple, # 每个LSTMStateTuple对应编码器中一层的状态 # enc_outputs是顶层LSTM在每一步的输出,它的维度是[batch_size, max_time, HIDDEN_SIZE] # seq2seq模型中不需要用到enc_outputs,而attention模型会用到它 with tf.variable_scope('encoder'): enc_outputs, enc_state = tf.nn.dynamic_rnn(self.enc_cell, src_emb, src_size, dtype=tf.float32) # 使用dynamic_rnn构造解码器 # 解码器读取目标句子每个位置的词向量,输出的dec_outputs为每一步顶层LSTM的输出 # dec_outputs的维度是[batch_size, max_time, HIDDEN_SIZE] # initial_state=enc_state表示用编码器的输出来初始化第一步的隐藏状态 # 编码器最后编码结束最后的状态为解码器初始化的状态 with tf.variable_scope('decoder'): dec_outputs, _ = tf.nn.dynamic_rnn(self.dec_cell, trg_emb, trg_size, initial_state=enc_state) # 计算解码器每一步的log perplexity # 输出重新转换成shape为[,HIDDEN_SIZE] output = tf.reshape(dec_outputs, [-1, HIDDEN_SIZE]) # 计算解码器每一步的softmax概率值 logits = tf.matmul(output, self.softmax_weight) + self.softmax_bias # 交叉熵损失函数,算loss loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=tf.reshape(trg_label, [-1]), logits=logits) # 在计算平均损失时,需要将填充位置的权重设置为0,以避免无效位置的预测干扰模型的训练 label_weights = tf.sequence_mask(trg_size, maxlen=tf.shape(trg_label)[1], dtype=tf.float32) label_weights = tf.reshape(label_weights, [-1]) cost = tf.reduce_sum(loss * label_weights) cost_per_token = cost / tf.reduce_sum(label_weights) # 定义反向传播操作 trainable_variables = tf.trainable_variables() # 控制梯度大小,定义优化方法和训练步骤 # 算出每个需要更新的值的梯度,并对其进行控制 grads = tf.gradients(cost / tf.to_float(batch_size), trainable_variables) grads, _ = tf.clip_by_global_norm(grads, MAX_GRAD_NORM) # 利用梯度下降优化算法进行优化.学习率为1.0 optimizer = tf.train.GradientDescentOptimizer(learning_rate=1.0) # 相当于minimize的第二步,正常来讲所得到的list[grads,vars]由compute_gradients得到,返回的是执行对应变量的更新梯度操作的op train_op = optimizer.apply_gradients(zip(grads, trainable_variables)) return cost_per_token, train_op """ function: 使用给定的模型model上训练一个epoch,并返回全局步数,每训练200步便保存一个checkpoint Parameters: session : 会议 cost_op : 计算loss的操作op train_op: 训练的操作op saver:  保存model的类 step:   训练步数 Returns: """ def run_epoch(session, cost_op, train_op, saver, step): # 训练一个epoch # 重复训练步骤直至遍历完Dataset中所有数据 while True: try: # 运行train_op并计算cost_op的结果也就是损失值,训练数据在main()函数中以Dataset方式提供 cost, _ = session.run([cost_op, train_op]) # 步数为10的倍数进行打印 if step % 10 == 0: print('After %d steps, per token cost is %.3f' % (step, cost)) # 每200步保存一个checkpoint if step % 200 == 0: saver.save(session, CHECKPOINT_PATH, global_step=step) step += 1 except tf.errors.OutOfRangeError: break return step """ function: 主函数 Parameters: Returns: """ def main(): # 定义初始化函数 initializer = tf.random_uniform_initializer(-0.05, 0.05) # 定义训练用的循环神经网络模型 with tf.variable_scope('nmt_model', reuse=None, initializer=initializer): train_model = NMTModel() # 定义输入数据 data = MakeSrcTrgDataset(SRC_TRAIN_DATA, TRG_TRAIN_DATA, BATCH_SIZE) iterator = data.make_initializable_iterator() (src, src_size), (trg_input, trg_label, trg_size) = iterator.get_next() # 定义前向计算图,输入数据以张量形式提供给forward函数 cost_op, train_op = train_model.forward(src, src_size, trg_input, trg_label, trg_size) # 训练模型 # 保存模型 saver = tf.train.Saver() step = 0 with tf.Session() as sess: # 初始化全部变量 tf.global_variables_initializer().run() # 进行NUM_EPOCH轮数 for i in range(NUM_EPOCH): print('In iteration: %d' % (i + 1)) sess.run(iterator.initializer) step = run_epoch(sess, cost_op, train_op, saver, step) if __name__ == '__main__': main() ``` 问题如下,不知道怎么解决,谢谢! Traceback (most recent call last): File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py", line 1334, in _do_call return fn(*args) File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py", line 1319, in _run_fn options, feed_dict, fetch_list, target_list, run_metadata) File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py", line 1407, in _call_tf_sessionrun run_metadata) tensorflow.python.framework.errors_impl.InvalidArgumentError: StringToNumberOp could not correctly convert string: This [[{{node StringToNumber}}]] [[{{node IteratorGetNext}}]] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:/Python37/untitled1/train_model.py", line 277, in <module> main() File "D:/Python37/untitled1/train_model.py", line 273, in main step = run_epoch(sess, cost_op, train_op, saver, step) File "D:/Python37/untitled1/train_model.py", line 231, in run_epoch cost, _ = session.run([cost_op, train_op]) File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py", line 929, in run run_metadata_ptr) File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py", line 1152, in _run feed_dict_tensor, options, run_metadata) File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py", line 1328, in _do_run run_metadata) File "D:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py", line 1348, in _do_call raise type(e)(node_def, op, message) tensorflow.python.framework.errors_impl.InvalidArgumentError: StringToNumberOp could not correctly convert string: This [[{{node StringToNumber}}]] [[node IteratorGetNext (defined at D:/Python37/untitled1/train_model.py:259) ]]
Spark中如何将多个LabeledPoint合并成一个LabeledPoint,用以训练分类模型
使用pyspark.mllib,对几个用textFile读取的RDD(a,b,c,d)打标签 ``` A = a.map(lambda features:LabeledPoint(0.0,features)) B = b.map(lambda features:LabeledPoint(1.0,features)) C = c.map(lambda features: LabeledPoint(2.0,features)) D = d.map(lambda features:LabeledPoint(3.0,features)) ``` 现在如何将A,B,C,D四个整合成为一个训练数据集,或保存为LibSVMFile再读取,用来作为机器学习分类模型的训练数据集呢? 网上很多都是临时创建的LabeledPoint(label,Vectors.dense(features)),这样确实可以用一个变量表示。 但对于多个这样的要怎么合成一个变量表示呢,用union会出错。 ``` traindata = A.union(B) traindata = data.union(C) traindata = data.union(D) ``` 或者 ``` traindata = A.union([B,C,D]) ``` 都会出错,包括《Spark快速大数据分析》书上源码试过,用union都不行。 ``` Traceback (most recent call last): File "/home/hadoop/Desktop/app.py", line 36, in <module> data = normalFea.union([icmpFea,synFea,udpFea]) File "/opt/spark-2.3.2-bin-hadoop2.7/python/lib/pyspark.zip/pyspark/rdd.py", line 557, in union AttributeError: 'list' object has no attribute '_jrdd_deserializer' ``` 这个报错是针对第二种的,第一种也会报错。求大神解答。。
OkHttp框架使用问题,菜鸟急求啊
这是我的OkHttp框架 但不知道怎么在MainActivity里面用 我随便用了 但好像提交不了数据 求大神指定啊,本人是名菜鸟 public class OkHttpUtil { private static final String TAG = "OkHttpUtil"; private static OkHttpUtil mInstance; private OkHttpClient mOkHttpClient; private Handler mDelivery; private OkHttpUtil() { mOkHttpClient = new OkHttpClient(); mDelivery = new Handler(Looper.getMainLooper()); } private synchronized static OkHttpUtil getmInstance() { if (mInstance == null) { mInstance = new OkHttpUtil(); } return mInstance; } private void getRequest(String url, final ResultCallback callback) { final Request request = new Request.Builder().url(url).build(); deliveryResult(callback, request); } private void postRequest(String url, final ResultCallback callback, List<Param> params) { Request request = buildPostRequest(url, params); deliveryResult(callback, request); } private void deliveryResult(final ResultCallback callback, Request request) { mOkHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { sendFailCallback(callback, e); } @Override public void onResponse(Call call, Response response) throws IOException { try { String str = response.body().string(); sendSuccessCallBack(callback, str); } catch (final Exception e) { Log.e(TAG, e.toString()); sendFailCallback(callback, e); } } }); } private void sendFailCallback(final ResultCallback callback, final Exception e) { mDelivery.post(new Runnable() { @Override public void run() { if (callback != null) { callback.onFailure(e); } } }); } private void sendSuccessCallBack(final ResultCallback callback, final Object obj) { mDelivery.post(new Runnable() { @Override public void run() { if (callback != null) { callback.onSuccess(obj); } } }); } private Request buildPostRequest(String url, List<Param> params) { FormBody.Builder builder = new FormBody.Builder(); for (Param param : params) { builder.add(param.key, param.value); } RequestBody requestBody = builder.build(); return new Request.Builder().url(url).post(requestBody).build(); } private void postImageRequest(String url, ResultCallback callback, List<Param> params) { Request request = buildPostImageRequest(url, params); deliveryResult(callback, request); } private Request buildPostImageRequest(String url, List<Param> params) { if(params == null || params.size()==0){ throw new RuntimeException("上传图片路径为null"); } MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM); for (Param param : params) { File file = new File(param.value); if(file.exists()){ builder.addFormDataPart(param.key, file.getName(), RequestBody.create(MediaType.parse("image/*"), file)); } } RequestBody requestBody = builder.build(); return new Request.Builder().url(url).post(requestBody).build(); } /**********************对外接口************************/ /** * get请求 * @param url 请求url * @param callback 请求回调 */ public static void get(String url, ResultCallback callback) { getmInstance().getRequest(url, callback); } /** * post请求 * @param url 请求url * @param callback 请求回调 * @param params 请求参数 */ public static String post(String url, final ResultCallback callback, List<Param> params) { getmInstance().postRequest(url,callback,params); return url; } /** * post请求, 图片上传 * @param url 请求url * @param callback 请求回调 * @param params 请求参数 */ public static void uploadImage(String url, final ResultCallback callback, List<Param> params) { getmInstance().postImageRequest(url, callback, params); } /** * http请求回调类,回调方法在UI线程中执行 * @param <T> */ public static abstract class ResultCallback<T> { /** * 请求成功回调 * @param response */ public abstract void onSuccess(T response); /** * 请求失败回调 * @param e */ public abstract void onFailure(Exception e); } /** * post请求参数类 */ public static class Param { String key; String value; public Param(String key, String value) { this.key = key; this.value = value; } } } 这是我的MainActivity public class MainActivity extends AppCompatActivity { private Button btn; private static String PATH = "http://192.168.31.177:8081"; // 服务端地址 private static URL url; // private HttpUtils httpUtils; private OkHttpUtil okHttpUtil; private OkHttpUtil.ResultCallback<MainActivity> resultCallback; public MainActivity(OkHttpUtil.ResultCallback resultCallback) { this.resultCallback = resultCallback; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } public void initView(){ btn = (Button) findViewById(R.id.post_btn); btn.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { strSendPost(); } }); } public void strSendPost(){ // Map<String, String> map = new HashMap<String, String>(); List<OkHttpUtil.Param> list = new ArrayList<>(); // params.put("shopId","371"); // params.put("advertA map.put("mode","iisue"); // map.put("call","shopService.qryAdvertList"); // map.put("params","{\"advertAreaId\":\"1\",\"shopId\":\"371\"}\n"); // map.put("version","1.0.0");reaId","1") // String result =okHttpUtil.post(PATH, resultCallback,list); System.out.println("--->>" + result); } }
java调用存储过程返回游标的结果集无法关闭的问题
有如果典型的java的spring jdbc调用了存储过程,返回游标形结果集。如果循环调用此方法。则会造成 ORA-01000: 超出打开游标的最大数。原因是没有及时关闭oracle中的游标,但按理说jdbcTemplate模版已经关闭了链接,但始终无法关闭游标。请问有什么办法可以关闭游标吗? Object obj=jdbcTemplate.execute(new CallableStatementCreator(){ @Override public CallableStatement createCallableStatement(Connection con) throws SQLException { // TODO Auto-generated method stub String execuSql = "{call batch51(?)}";; cs.registerOutParameter(1, OracleTypes.CURSOR);// 注册输出参数的类型 return cs; } }, new CallableStatementCallback(){ public Object doInCallableStatement(CallableStatement cs) throws SQLException,DataAccessException { List<JSONObject> resultsJson = new ArrayList<JSONObject>(); cs.execute(); ResultSet refcursor = (ResultSet) cs.getObject(1);// 获取游标一行的值 while (refcursor.next()) {// 转换每行的返回值到Map中 JSONObject json = new JSONObject(); json.accumulate("busname",refcursor.getString("busname")); resultsJson.add(json); } refcursor.close(); return resultsJson; } });
Android:RxJava数据流控制 背压策略使用
最近在开发一款人脸比对的项目,使用RxJava1.x实现的比对逻辑 场景如下: 定时抓取摄像头预览图片进行比对 符合条件时使用 takeUntil操作符停止发射数据 然后使用timer过一定时间后重启比对 但是每次重启后都会获取上次最后一张图片去比对 不晓得原因是什么 在每次重启前都清空了订阅事件的 直接上代码: ``` /** * 比对程序 */ @Override public void detect() { // 1. 过滤 数据库中的人脸数量不为空 若为空不能有效比对 直接过滤掉 if (mPersonList.isEmpty()) return; mSubscription = Observable .interval(0, 500, TimeUnit.MILLISECONDS) .onBackpressureDrop() // 使用背压策略:总是接收最新的 // 2. 获得预览图片 .map(new Func1<Long, Bitmap>() { @Override public Bitmap call(Long aLong) { KLog.e("aLong:" + aLong); return mView.takePhoto(); } }) // 3. 过滤掉为null的图片 .filter(new Func1<Bitmap, Boolean>() { @Override public Boolean call(Bitmap bitmap) { return bitmap != null; } }) // 4. 将图片保存在对象DetectSuccessInfo .flatMap(new Func1<Bitmap, Observable<DetectSuccessInfo>>() { @Override public Observable<DetectSuccessInfo> call(Bitmap bitmap) { DetectSuccessInfo detectSuccessInfo = new DetectSuccessInfo(); detectSuccessInfo.setDetectBitmap(bitmap); return Observable.just(detectSuccessInfo); } }) .observeOn(Schedulers.io()) // 运行在子线程 // 5. 提取图片中的人脸特征 无人脸时特征值为----"" .flatMap(new Func1<DetectSuccessInfo, Observable<DetectSuccessInfo>>() { @Override public Observable<DetectSuccessInfo> call(DetectSuccessInfo successInfo) { String[] feature_ = FeatureUtils.extractFeature_(successInfo .getDetectBitmap()); successInfo.setRect(feature_[0]); successInfo.setFeature(feature_[1]); return Observable.just(successInfo); } }) // 6. 过滤条件:图片提取的人脸特征不为空 .filter(new Func1<DetectSuccessInfo, Boolean>() { @Override public Boolean call(DetectSuccessInfo successInfo) { return !TextUtils.isEmpty(successInfo.getFeature()); } }) // 7. 标定人脸相框 .doOnEach(new Action1<Notification<? super DetectSuccessInfo>>() { @Override public void call(Notification<? super DetectSuccessInfo> notification) { DetectSuccessInfo successInfo = (DetectSuccessInfo) notification .getValue(); Bitmap bitmap = successInfo.getDetectBitmap(); int[] result = StringUtils.split2Int(successInfo.getRect()); mView.convertCoordinate(result[0], result[1], result[2], result[3], bitmap.getWidth(), bitmap.getHeight()); } }) // 8. 过滤条件:和数据库查询的人脸集合中的每一个人脸进行比对 选取最大值且有匹配成功的对象 .map(new Func1<DetectSuccessInfo, DetectSuccessInfo>() { @Override public DetectSuccessInfo call(DetectSuccessInfo successInfo) { float[] fea = StringUtils.split2Float(successInfo.getFeature()); List<Object> objects = FeatureUtils.matchWithDbData(mPersonList, fea); if (!objects.isEmpty()) { successInfo.setScore((Float) objects.get(0)); successInfo.setPerson((Person) objects.get(1)); successInfo.setSuc_time(System.currentTimeMillis()); } return successInfo; } }) // 9. 过滤 只有分数大于阈值的才可以继续进行 小于则继续下一次循环开始抓取图片 .filter(new Func1<DetectSuccessInfo, Boolean>() { @Override public Boolean call(DetectSuccessInfo successInfo) { KLog.e("filter:" + successInfo.getScore()); return successInfo.getScore() >= 50; } }) // 10. 判断匹配成功的唯一标准DetectSuccessInfo score属性且大于阈值 // 成功则停止发送数据 .takeUntil(new Func1<DetectSuccessInfo, Boolean>() { @Override public Boolean call(DetectSuccessInfo successInfo) { KLog.e("takeUntil:" + successInfo.getScore()); return successInfo.getScore() >= 50; } }) // 11. 每次匹配成功 开启子线程入库 .doOnNext(new Action1<DetectSuccessInfo>() { @Override public void call(final DetectSuccessInfo successInfo) { Schedulers.io().createWorker().schedule(new Action0() { @Override public void call() { DetectRecord record = new DetectRecord(); record.setDetectScore(String.valueOf(successInfo.getScore ())); record.setDetectTime(successInfo.getSuc_time()); record.setPerson_id(successInfo.getPerson().get_id()); record.setDetectImage(ImageUtils.BitmapToBytes(successInfo .getDetectBitmap())); mDaoManager.insertRecord(record); KLog.e("保存比对数据入库"); } }); } }) .subscribeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<DetectSuccessInfo>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { KLog.e("Error:" + e.getMessage()); } @Override public void onNext(DetectSuccessInfo successInfo) { // 12. 匹配成功刷新页面 mView.me_succeed(successInfo); } @Override public void onStart() { super.onStart(); mView.resetUI(); } }); KLog.e("detect----subscription:" + mSubscription); addSubscribe(mSubscription); } ``` 重启代码: ``` /** * 比对成功后延时1.5秒重新开始匹配 */ @Override public void reStart() { Subscription subscription = Observable.timer(1500, TimeUnit.MILLISECONDS) .compose(SchedulersCompat.<Long>applyIoSchedulers()) .subscribe(new Action1<Long>() { @Override public void call(Long aLong) { cleanSubscribe(mSubscription); // 重新开始匹配 mView.resetUI(); detect(); } }); addSubscribe(subscription); } ``` 在线求大神指点!!!
终于明白阿里百度这样的大公司,为什么面试经常拿ThreadLocal考验求职者了
点击上面↑「爱开发」关注我们每晚10点,捕获技术思考和创业资源洞察什么是ThreadLocalThreadLocal是一个本地线程副本变量工具类,各个线程都拥有一份线程私有的数
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
此博客仅为我业余记录文章所用,发布到此,仅供网友阅读参考,如有侵权,请通知我,我会删掉。 补充 有不少读者留言说本文章没有用,因为天气预报直接打开手机就可以收到了,为何要多此一举发送到邮箱呢!!!那我在这里只能说:因为你没用,所以你没用!!! 这里主要介绍的是思路,不是天气预报!不是天气预报!!不是天气预报!!!天气预报只是用于举例。请各位不要再刚了!!! 下面是我会用到的两个场景: 每日下
死磕YOLO系列,YOLOv1 的大脑、躯干和手脚
YOLO 是我非常喜欢的目标检测算法,堪称工业级的目标检测,能够达到实时的要求,它帮我解决了许多实际问题。 这就是 YOLO 的目标检测效果。它定位了图像中物体的位置,当然,也能预测物体的类别。 之前我有写博文介绍过它,但是每次重新读它的论文,我都有新的收获,为此我准备写一个系列的文章来详尽分析它。这是第一篇,从它的起始 YOLOv1 讲起。 YOLOv1 的论文地址:https://www.c...
知乎高赞:中国有什么拿得出手的开源软件产品?(整理自本人原创回答)
知乎高赞:中国有什么拿得出手的开源软件产品? 在知乎上,有个问题问“中国有什么拿得出手的开源软件产品(在 GitHub 等社区受欢迎度较好的)?” 事实上,还不少呢~ 本人于2019.7.6进行了较为全面的回答,对这些受欢迎的 Github 开源项目分类整理如下: 分布式计算、云平台相关工具类 1.SkyWalking,作者吴晟、刘浩杨 等等 仓库地址: apache/skywalking 更...
20行Python代码爬取王者荣耀全英雄皮肤
引言 王者荣耀大家都玩过吧,没玩过的也应该听说过,作为时下最火的手机MOBA游戏,咳咳,好像跑题了。我们今天的重点是爬取王者荣耀所有英雄的所有皮肤,而且仅仅使用20行Python代码即可完成。 准备工作 爬取皮肤本身并不难,难点在于分析,我们首先得得到皮肤图片的url地址,话不多说,我们马上来到王者荣耀的官网: 我们点击英雄资料,然后随意地选择一位英雄,接着F12打开调试台,找到英雄原皮肤的图片...
简明易理解的@SpringBootApplication注解源码解析(包含面试提问)
欢迎关注文章系列 ,关注我 《提升能力,涨薪可待》 《面试知识,工作可待》 《实战演练,拒绝996》 欢迎关注我博客,原创技术文章第一时间推出 也欢迎关注公 众 号【Ccww笔记】,同时推出 如果此文对你有帮助、喜欢的话,那就点个赞呗,点个关注呗! 《提升能力,涨薪可待篇》- @SpringBootApplication注解源码解析 一、@SpringBootApplication 的作用是什...
西游记团队中如果需要裁掉一个人,会先裁掉谁?
2019年互联网寒冬,大批企业开始裁员,下图是网上流传的一张截图: 裁员不可避免,那如何才能做到不管大环境如何变化,自身不受影响呢? 我们先来看一个有意思的故事,如果西游记取经团队需要裁员一名,会裁掉谁呢,为什么? 西游记团队组成: 1.唐僧 作为团队teamleader,有很坚韧的品性和极高的原则性,不达目的不罢休,遇到任何问题,都没有退缩过,又很得上司支持和赏识(直接得到唐太宗的任命,既给袈...
Python语言高频重点汇总
Python语言高频重点汇总 GitHub面试宝典仓库 回到首页 目录: Python语言高频重点汇总 目录: 1. 函数-传参 2. 元类 3. @staticmethod和@classmethod两个装饰器 4. 类属性和实例属性 5. Python的自省 6. 列表、集合、字典推导式 7. Python中单下划线和双下划线 8. 格式化字符串中的%和format 9. 迭代器和生成器 10...
究竟你适不适合买Mac?
我清晰的记得,刚买的macbook pro回到家,开机后第一件事情,就是上了淘宝网,花了500元钱,找了一个上门维修电脑的师傅,上门给我装了一个windows系统。。。。。。 表砍我。。。 当时买mac的初衷,只是想要个固态硬盘的笔记本,用来运行一些复杂的扑克软件。而看了当时所有的SSD笔记本后,最终决定,还是买个好(xiong)看(da)的。 已经有好几个朋友问我mba怎么样了,所以今天尽量客观
程序员一般通过什么途径接私活?
二哥,你好,我想知道一般程序猿都如何接私活,我也想接,能告诉我一些方法吗? 上面是一个读者“烦不烦”问我的一个问题。其实不止是“烦不烦”,还有很多读者问过我类似这样的问题。 我接的私活不算多,挣到的钱也没有多少,加起来不到 20W。说实话,这个数目说出来我是有点心虚的,毕竟太少了,大家轻喷。但我想,恰好配得上“一般程序员”这个称号啊。毕竟苍蝇再小也是肉,我也算是有经验的人了。 唾弃接私活、做外
ES6基础-ES6的扩展
进行对字符串扩展,正则扩展,数值扩展,函数扩展,对象扩展,数组扩展。 开发环境准备: 编辑器(VS Code, Atom,Sublime)或者IDE(Webstorm) 浏览器最新的Chrome 字符串的扩展: 模板字符串,部分新的方法,新的unicode表示和遍历方法: 部分新的字符串方法 padStart,padEnd,repeat,startsWith,endsWith,includes 字...
Python爬虫爬取淘宝,京东商品信息
小编是一个理科生,不善长说一些废话。简单介绍下原理然后直接上代码。 使用的工具(Python+pycharm2019.3+selenium+xpath+chromedriver)其中要使用pycharm也可以私聊我selenium是一个框架可以通过pip下载 pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple/ 
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
你知道的越多,你不知道的越多 点赞再看,养成习惯 本文 GitHub https://github.com/JavaFamily 已收录,有一线大厂面试点思维导图,也整理了很多我的文档,欢迎Star和完善,大家面试可以参照考点复习,希望我们一起有点东西。 前前言 为啥今天有个前前言呢? 因为你们的丙丙啊,昨天有牌面了哟,直接被微信官方推荐,知乎推荐,也就仅仅是还行吧(心里乐开花)
Java工作4年来应聘要16K最后没要,细节如下。。。
前奏: 今天2B哥和大家分享一位前几天面试的一位应聘者,工作4年26岁,统招本科。 以下就是他的简历和面试情况。 基本情况: 专业技能: 1、&nbsp;熟悉Sping了解SpringMVC、SpringBoot、Mybatis等框架、了解SpringCloud微服务 2、&nbsp;熟悉常用项目管理工具:SVN、GIT、MAVEN、Jenkins 3、&nbsp;熟悉Nginx、tomca
Python爬虫精简步骤1 获取数据
爬虫的工作分为四步: 1.获取数据。爬虫程序会根据我们提供的网址,向服务器发起请求,然后返回数据。 2.解析数据。爬虫程序会把服务器返回的数据解析成我们能读懂的格式。 3.提取数据。爬虫程序再从中提取出我们需要的数据。 4.储存数据。爬虫程序把这些有用的数据保存起来,便于你日后的使用和分析。 这一篇的内容就是:获取数据。 首先,我们将会利用一个强大的库——requests来获取数据。 在电脑上安装
作为一个程序员,CPU的这些硬核知识你必须会!
CPU对每个程序员来说,是个既熟悉又陌生的东西? 如果你只知道CPU是中央处理器的话,那可能对你并没有什么用,那么作为程序员的我们,必须要搞懂的就是CPU这家伙是如何运行的,尤其要搞懂它里面的寄存器是怎么一回事,因为这将让你从底层明白程序的运行机制。 随我一起,来好好认识下CPU这货吧 把CPU掰开来看 对于CPU来说,我们首先就要搞明白它是怎么回事,也就是它的内部构造,当然,CPU那么牛的一个东
破14亿,Python分析我国存在哪些人口危机!
2020年1月17日,国家统计局发布了2019年国民经济报告,报告中指出我国人口突破14亿。 猪哥的朋友圈被14亿人口刷屏,但是很多人并没有看到我国复杂的人口问题:老龄化、男女比例失衡、生育率下降、人口红利下降等。 今天我们就来分析一下我们国家的人口数据吧! 更多有趣分析教程,扫描下方二维码关注vx公号「裸睡的猪」 即可查看! 一、背景 1.人口突破14亿 2020年1月17日,国家统计局发布
web前端javascript+jquery知识点总结
Javascript javascript 在前端网页中占有非常重要的地位,可以用于验证表单,制作特效等功能,它是一种描述语言,也是一种基于对象(Object)和事件驱动并具有安全性的脚本语言 ,语法同java类似,是一种解释性语言,边执行边解释。 JavaScript的组成: ECMAScipt 用于描述: 语法,变量和数据类型,运算符,逻辑控制语句,关键字保留字,对象。 浏览器对象模型(Br
Qt实践录:开篇
本系列文章介绍笔者的Qt实践之路。
在家远程办公效率低?那你一定要收好这个「在家办公」神器!
相信大家都已经收到国务院延长春节假期的消息,接下来,在家远程办公可能将会持续一段时间。 但是问题来了。远程办公不是人在电脑前就当坐班了,相反,对于沟通效率,文件协作,以及信息安全都有着极高的要求。有着非常多的挑战,比如: 1在异地互相不见面的会议上,如何提高沟通效率? 2文件之间的来往反馈如何做到及时性?如何保证信息安全? 3如何规划安排每天工作,以及如何进行成果验收? ......
作为一个程序员,内存和磁盘的这些事情,你不得不知道啊!!!
截止目前,我已经分享了如下几篇文章: 一个程序在计算机中是如何运行的?超级干货!!! 作为一个程序员,CPU的这些硬核知识你必须会! 作为一个程序员,内存的这些硬核知识你必须懂! 这些知识可以说是我们之前都不太重视的基础知识,可能大家在上大学的时候都学习过了,但是嘞,当时由于老师讲解的没那么有趣,又加上这些知识本身就比较枯燥,所以嘞,大家当初几乎等于没学。 再说啦,学习这些,也看不出来有什么用啊!
这个世界上人真的分三六九等,你信吗?
偶然间,在知乎上看到一个问题 一时间,勾起了我深深的回忆。 以前在厂里打过两次工,做过家教,干过辅导班,做过中介。零下几度的晚上,贴过广告,满脸、满手地长冻疮。   再回首那段岁月,虽然苦,但让我学会了坚持和忍耐。让我明白了,在这个世界上,无论环境多么的恶劣,只要心存希望,星星之火,亦可燎原。   下文是原回答,希望能对你能有所启发。   如果我说,这个世界上人真的分三六九等,
为什么听过很多道理,依然过不好这一生?
记录学习笔记是一个重要的习惯,不希望学习过的东西成为过眼云烟。做总结的同时也是一次复盘思考的过程。 本文是根据阅读得到 App上《万维钢·精英日课》部分文章后所做的一点笔记和思考。学习是一个系统的过程,思维模型的建立需要相对完整的学习和思考过程。以下观点是在碎片化阅读后总结的一点心得总结。
B 站上有哪些很好的学习资源?
哇说起B站,在小九眼里就是宝藏般的存在,放年假宅在家时一天刷6、7个小时不在话下,更别提今年的跨年晚会,我简直是跪着看完的!! 最早大家聚在在B站是为了追番,再后来我在上面刷欧美新歌和漂亮小姐姐的舞蹈视频,最近两年我和周围的朋友们已经把B站当作学习教室了,而且学习成本还免费,真是个励志的好平台ヽ(.◕ฺˇд ˇ◕ฺ;)ノ 下面我们就来盘点一下B站上优质的学习资源: 综合类 Oeasy: 综合
雷火神山直播超两亿,Web播放器事件监听是怎么实现的?
Web播放器解决了在手机浏览器和PC浏览器上播放音视频数据的问题,让视音频内容可以不依赖用户安装App,就能进行播放以及在社交平台进行传播。在视频业务大数据平台中,播放数据的统计分析非常重要,所以Web播放器在使用过程中,需要对其内部的数据进行收集并上报至服务端,此时,就需要对发生在其内部的一些播放行为进行事件监听。 那么Web播放器事件监听是怎么实现的呢? 01 监听事件明细表 名
3万字总结,Mysql优化之精髓
本文知识点较多,篇幅较长,请耐心学习 MySQL已经成为时下关系型数据库产品的中坚力量,备受互联网大厂的青睐,出门面试想进BAT,想拿高工资,不会点MySQL优化知识,拿offer的成功率会大大下降。 为什么要优化 系统的吞吐量瓶颈往往出现在数据库的访问速度上 随着应用程序的运行,数据库的中的数据会越来越多,处理时间会相应变慢 数据是存放在磁盘上的,读写速度无法和内存相比 如何优化 设计
一条链接即可让黑客跟踪你的位置! | Seeker工具使用
搬运自:冰崖的部落阁(icecliffsnet) 严正声明:本文仅限于技术讨论,严禁用于其他用途。 请遵守相对应法律规则,禁止用作违法途径,出事后果自负! 上次写的防社工文章里边提到的gps定位信息(如何防止自己被社工或人肉) 除了主动收集他人位置信息以外,我们还可以进行被动收集 (没有技术含量) Seeker作为一款高精度地理位置跟踪工具,同时也是社交工程学(社会工程学)爱好者...
作为程序员的我,大学四年一直自学,全靠这些实用工具和学习网站!
我本人因为高中沉迷于爱情,导致学业荒废,后来高考,毫无疑问进入了一所普普通通的大学,实在惭愧...... 我又是那么好强,现在学历不行,没办法改变的事情了,所以,进入大学开始,我就下定决心,一定要让自己掌握更多的技能,尤其选择了计算机这个行业,一定要多学习技术。 在进入大学学习不久后,我就认清了一个现实:我这个大学的整体教学质量和学习风气,真的一言难尽,懂的人自然知道怎么回事? 怎么办?我该如何更好的提升
前端JS初级面试题二 (。•ˇ‸ˇ•。)老铁们!快来瞧瞧自己都会了么
1. 传统事件绑定和符合W3C标准的事件绑定有什么区别? 传统事件绑定 &lt;div onclick=""&gt;123&lt;/div&gt; div1.onclick = function(){}; &lt;button onmouseover=""&gt;&lt;/button&gt; 注意: 如果给同一个元素绑定了两次或多次相同类型的事件,那么后面的绑定会覆盖前面的绑定 (不支持DOM事...
相关热词 c# 时间比天数 c# oracle查询 c# 主动推送 事件 c# java 属性 c# 控制台 窗体 c# 静态类存值 c#矢量作图 c#窗体调用外部程式 c# enum是否合法 c# 如何卸载引用
立即提问