首页 文章 精选 留言 我的

精选列表

搜索[资源操作],共10025篇文章
优秀的个人博客,低调大师

Flink操作Hbase

现在有这样一个场景,我们需要将hbase做成一个数据流,而不是数据集。根据Flink自带的Flink-Hbase只能帮我们做到数据集,所以这个时候选择了重写Hbase的数据源。 package com.yjp.flink.demo11; import org.apache.flink.streaming.api.functions.source.SourceFunction; import org.apache.flink.table.shaded.org.joda.time.DateTime; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.util.Bytes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * 以Hbase为数据源 * 从Hbase中获取数据,然后以流的形式发射 * Date : 9:50 2018/3/12 */ public class HbaseSource implements SourceFunction<String> { private static Logger loggerFactory = LoggerFactory.getLogger(HbaseSource.class); private static final long serialVersionUID = 1; private volatile boolean isRunning = true; /** * 开始的时间戳 */ private long startTime; /** * 每次查询多长时间的数据 */ private long interval; /** * 需要查询的列名 */ private ArrayList<String> columns; /** * 需要查询的表名 */ private String tableName; public HbaseSource(long startTime, long interval, ArrayList<String> columns, String tableName) { this.startTime = startTime; this.interval = interval; this.columns = columns; this.tableName = tableName; } public HbaseSource() { } @Override public void run(SourceContext<String> out) { if (isRunning) { long endTime = DateTime.now().getMillis() - interval; ResultScanner rs = new HbaseSource().getHbaseData(tableName, startTime, endTime - startTime, columns); new HbaseSource().transmitData(rs, out); startTime = endTime; } while (isRunning) { ResultScanner rs = new HbaseSource().getHbaseData(tableName, startTime, interval, columns); new HbaseSource().transmitData(rs, out); startTime += interval; try { Thread.sleep(interval); } catch (InterruptedException e) { throw new RuntimeException("休眠异常", e); } } } @Override public void cancel() { } /** * 获取数据集 * * @param startTime 时间戳开始的时间 * @param interval 间隔时间 * @return 对应的结果集 */ private ResultScanner getHbaseData(String tableName, long startTime, long interval, List<String> columns) { Configuration conf = HBaseConfiguration.create(); HTable table; Scan scan; try { table = new HTable(conf, tableName); scan = new Scan(); scan.setTimeRange(startTime, startTime + interval); for (String column : columns) { String[] columnName = column.split(":"); scan.addColumn(Bytes.toBytes(columnName[0]), Bytes.toBytes(columnName[1])); } return table.getScanner(scan); } catch (IOException e) { throw new RuntimeException("读取数据异常", e); } } private void transmitData(ResultScanner rs, SourceContext<String> out) { Result result; try { while ((result = rs.next()) != null && isRunning) { KeyValue[] kvs = result.raw(); for (KeyValue kv : kvs) { String value = new String(kv.getValue()); out.collect(value); } } } catch (IOException e) { throw new RuntimeException("结果集遍历异常", e); } } } 然后将数据结果加工和处理存入Hbase中 package com.yjp.flink.hbase; import org.apache.flink.api.common.functions.FlatMapFunction; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.tuple.Tuple3; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.datastream.DataStreamSource; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.table.api.Table; import org.apache.flink.table.api.java.StreamTableEnvironment; import org.apache.flink.util.Collector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; public class HbaseToHbase { public static Logger logger = LoggerFactory.getLogger(HbaseToHbase.class); public static void main(String[] args) throws Exception { StreamExecutionEnvironment sEnv = StreamExecutionEnvironment.getExecutionEnvironment(); StreamTableEnvironment tEnv = StreamTableEnvironment.getTableEnvironment(sEnv); sEnv.getConfig().disableSysoutLogging(); List<String> getColumns = new ArrayList<String>(3); getColumns.add("cf1_name"); getColumns.add("cf2_amount"); getColumns.add("cf3_groupId"); List<String> columnFamily = new ArrayList<>(3); columnFamily.add("cf1"); columnFamily.add("cf2"); columnFamily.add("cf3"); List<String> setColumns = new ArrayList<>(3); setColumns.add("cf2:result"); DataStreamSource<Orders> orderDataStream = sEnv.addSource(new HbaseStreamDataSource("Orders", 0L, 2000L, getColumns, Orders.class)); DataStream<Tuple3<String, Double, Integer>> dataStream = orderDataStream.flatMap( new FlatMapFunction<Orders, Tuple3<String, Double, Integer>>() { @Override public void flatMap(Orders value, Collector<Tuple3<String, Double, Integer>> out) throws Exception { out.collect(new Tuple3<String, Double, Integer>(value.getCf1_name(), value.getCf2_amount(), value.getCf3_groupId())); } }); dataStream.keyBy(2).sum(1).addSink( new SinkHbase<Tuple3<String, Double, Integer>>( "OrderResult", columnFamily, setColumns, "result")); sEnv.execute("test Hbase"); } } package com.yjp.flink.hbase; import org.apache.flink.api.java.tuple.*; import org.apache.flink.configuration.Configuration; import org.apache.flink.streaming.api.functions.sink.RichSinkFunction; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.Table; import java.lang.reflect.Method; import java.util.*; /** * 自定义Sink * * Date : 17:23 2018/3/12 */ public class SinkHbase<T> extends RichSinkFunction<T> { private static final long serialVersionUID = 1L; /** * 表名 */ private String tableName; /** * 列族名 */ private List<String> columnFails; /** * 列名 以 family:column的形式传入 column与tuple中的值一一对应 */ private List<String> columns; /** * 行名 */ private String rowKey; /** * @param tableName 表名 * @param columnFamily 列族名 当表存在时不用输入 * @param columns 储存的列名 列族:列名 * @param rowKey 传入的行名 */ public SinkHbase(String tableName, List<String> columnFamily, List<String> columns, String rowKey) { this.tableName = tableName; this.columnFails = columnFamily; this.columns = columns; this.rowKey = rowKey; } /** * @param tableName 表名 * @param columns 储存的列名 列族:列名 * @param rowKey 传入的行名 */ public SinkHbase(String tableName, List<String> columns, String rowKey) { this.tableName = tableName; this.columns = columns; this.rowKey = rowKey; } public SinkHbase() { } /** * 初始化完成连接 当表不存在的时候 新建表和family列 * * @param parameters 调用父类的方法 * @throws Exception 创建连接失败 */ @Override public void open(Configuration parameters) throws Exception { super.open(parameters); Admin admin = FactoryConnect.getConnection().getAdmin(); final TableName tableName1 = TableName.valueOf(tableName); if (!admin.tableExists(tableName1)) { HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName1); for (String columnFamily : columnFails) { hTableDescriptor.addFamily(new HColumnDescriptor(columnFamily)); } admin.createTable(hTableDescriptor); } } /** * 执行方法 将数据存入hbase * * @param value 传入的结果 */ @Override public void invoke(T value, Context context) throws Exception { Map<Class, Method> map = new HashMap<>(25); new SinkHbase<T>().initMap(map); Table table = FactoryConnect.getConnection().getTable(TableName.valueOf(tableName)); Set<Class> keys = map.keySet(); for (Class key : keys) { if (value.getClass() == key) { map.get(key).invoke(new AssignmentTuple(), value, rowKey, columns, table); return; } } } private void initMap(Map<Class, Method> map) { try { map.put(Tuple1.class, AssignmentTuple.class.getMethod("setTuple1", Tuple1.class, String.class, ArrayList.class, Table.class)); map.put(Tuple2.class, AssignmentTuple.class.getMethod("setTuple2", Tuple2.class, String.class, ArrayList.class, Table.class)); map.put(Tuple3.class, AssignmentTuple.class.getMethod("setTuple3", Tuple3.class, String.class, ArrayList.class, Table.class)); map.put(Tuple4.class, AssignmentTuple.class.getMethod("setTuple4", Tuple4.class, String.class, ArrayList.class, Table.class)); map.put(Tuple5.class, AssignmentTuple.class.getMethod("setTuple5", Tuple5.class, String.class, ArrayList.class, Table.class)); map.put(Tuple6.class, AssignmentTuple.class.getMethod("setTuple6", Tuple6.class, String.class, ArrayList.class, Table.class)); map.put(Tuple7.class, AssignmentTuple.class.getMethod("setTuple7", Tuple7.class, String.class, ArrayList.class, Table.class)); map.put(Tuple8.class, AssignmentTuple.class.getMethod("setTuple8", Tuple8.class, String.class, ArrayList.class, Table.class)); map.put(Tuple9.class, AssignmentTuple.class.getMethod("setTuple9", Tuple9.class, String.class, ArrayList.class, Table.class)); map.put(Tuple10.class, AssignmentTuple.class.getMethod("setTuple10", Tuple10.class, String.class, ArrayList.class, Table.class)); map.put(Tuple11.class, AssignmentTuple.class.getMethod("setTuple11", Tuple11.class, String.class, ArrayList.class, Table.class)); map.put(Tuple12.class, AssignmentTuple.class.getMethod("setTuple12", Tuple12.class, String.class, ArrayList.class, Table.class)); map.put(Tuple13.class, AssignmentTuple.class.getMethod("setTuple13", Tuple13.class, String.class, ArrayList.class, Table.class)); map.put(Tuple14.class, AssignmentTuple.class.getMethod("setTuple14", Tuple14.class, String.class, ArrayList.class, Table.class)); map.put(Tuple15.class, AssignmentTuple.class.getMethod("setTuple15", Tuple15.class, String.class, ArrayList.class, Table.class)); map.put(Tuple16.class, AssignmentTuple.class.getMethod("setTuple16", Tuple16.class, String.class, ArrayList.class, Table.class)); map.put(Tuple17.class, AssignmentTuple.class.getMethod("setTuple17", Tuple17.class, String.class, ArrayList.class, Table.class)); map.put(Tuple18.class, AssignmentTuple.class.getMethod("setTuple18", Tuple18.class, String.class, ArrayList.class, Table.class)); map.put(Tuple19.class, AssignmentTuple.class.getMethod("setTuple19", Tuple19.class, String.class, ArrayList.class, Table.class)); map.put(Tuple20.class, AssignmentTuple.class.getMethod("setTuple20", Tuple20.class, String.class, ArrayList.class, Table.class)); map.put(Tuple21.class, AssignmentTuple.class.getMethod("setTuple21", Tuple21.class, String.class, ArrayList.class, Table.class)); map.put(Tuple22.class, AssignmentTuple.class.getMethod("setTuple22", Tuple22.class, String.class, ArrayList.class, Table.class)); map.put(Tuple23.class, AssignmentTuple.class.getMethod("setTuple23", Tuple23.class, String.class, ArrayList.class, Table.class)); map.put(Tuple24.class, AssignmentTuple.class.getMethod("setTuple24", Tuple24.class, String.class, ArrayList.class, Table.class)); map.put(Tuple25.class, AssignmentTuple.class.getMethod("setTuple25", Tuple25.class, String.class, ArrayList.class, Table.class)); } catch (NoSuchMethodException e) { throw new RuntimeException("反射失败", e); } } } package com.yjp.flink.hbase; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import java.io.IOException; import java.io.Serializable; /** * 单例模式 安全的拿到连接 * * Date : 16:45 2018/3/16 */ public class FactoryConnect implements Serializable { private static volatile Connection connection; private FactoryConnect() { } public static Connection getConnection() throws IOException { if (null == connection) { synchronized (FactoryConnect.class) { try { if (null == connection) { org.apache.hadoop.conf.Configuration conf = HBaseConfiguration.create(); connection = ConnectionFactory.createConnection(conf); } } catch (Exception e) { System.err.println("读取配置文件异常"); } } } return connection; } } package com.yjp.flink.hbase; import org.apache.flink.api.java.tuple.*; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; import java.time.Instant; import java.util.ArrayList; import java.util.List; /** * 将tuple中的存放在Hbase中 * * Date : 16:49 2018/3/12 */ public class AssignmentTuple { /** * tuple 为1 * * @param tuple1 传入tuple的值 * @param rowKey 传入的rowkey的值 * @param columns 需要赋值的列 * @param table put的table对象 */ public void setTuple1(Tuple1<Object> tuple1, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple1, rowKey, columns, table); } public void setTuple2(Tuple2<Object, Object> tuple2, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple2, rowKey, columns, table); } public void setTuple3(Tuple3<Object, Object, Object> tuple3, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple3, rowKey, columns, table); } public void setTuple4(Tuple4<Object, Object, Object, Object> tuple4, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple4, rowKey, columns, table); } public void setTuple5(Tuple5<Object, Object, Object, Object, Object> tuple5, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple5, rowKey, columns, table); } public void setTuple6(Tuple6 tuple6, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple6, rowKey, columns, table); } public void setTuple7(Tuple7 tuple7, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple7, rowKey, columns, table); } public void setTuple8(Tuple8 tuple8, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple8, rowKey, columns, table); } public void setTuple9(Tuple9 tuple9, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple9, rowKey, columns, table); } public void setTuple10(Tuple10 tuple10, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple10, rowKey, columns, table); } public void setTuple11(Tuple11 tuple11, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple11, rowKey, columns, table); } public void setTuple12(Tuple12 tuple12, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple12, rowKey, columns, table); } public void setTuple13(Tuple13 tuple13, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple13, rowKey, columns, table); } public void setTuple14(Tuple14 tuple14, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple14, rowKey, columns, table); } public void setTuple15(Tuple15 tuple15, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple15, rowKey, columns, table); } public void setTuple16(Tuple16 tuple16, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple16, rowKey, columns, table); } public void setTuple17(Tuple17 tuple17, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple17, rowKey, columns, table); } public void setTuple18(Tuple18 tuple18, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple18, rowKey, columns, table); } public void setTuple19(Tuple19 tuple19, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple19, rowKey, columns, table); } public void setTuple20(Tuple20 tuple20, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple20, rowKey, columns, table); } public void setTuple21(Tuple21 tuple21, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple21, rowKey, columns, table); } public void setTuple22(Tuple22 tuple22, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple22, rowKey, columns, table); } public void setTuple23(Tuple23 tuple23, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple23, rowKey, columns, table); } public void setTuple24(Tuple24 tuple24, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple24, rowKey, columns, table); } public void setTuple25(Tuple25 tuple25, String rowKey, ArrayList<String> columns, Table table) { new AssignmentTuple().putData(tuple25, rowKey, columns, table); } /** * 将tuple中的数据一一对应的赋值给列 * * @param tuple tuple中的数据 * @param rowKey 设置的行值 * @param columns 对应的列名 * @param table 对应的table对象 */ public void putData(Tuple tuple, String rowKey, List<String> columns, Table table) { Put put = new Put(Bytes.toBytes(rowKey)); Long timeStamp = Instant.now().toEpochMilli(); for (int i = 0; i < columns.size(); i++) { String[] split = columns.get(i).split(":"); put.addColumn(Bytes.toBytes(split[0]), Bytes.toBytes(split[1]), timeStamp, Bytes.toBytes(tuple.getField(i).toString())); } try { table.put(put); } catch (IOException e) { throw new RuntimeException("存放失败", e); } } } 为了做到一个通用的数据源和数据存储,于是采用了反射的方法。

优秀的个人博客,低调大师

数据集操作

代码运行报错: ----------> Parent Classloader: java.net.URLClassLoader@1c53fd30 : java.lang.ClassNotFoundException: org.springframework.dao.TransientDataAccessResourceException 八月 10, 2018 5:45:28 下午 com.caucho.hessian.io.SerializerFactory getDeserializer 警告: Hessian/Burlap: 'org.springframework.dao.TransientDataAccessResourceException' is an unknown class in ParallelWebappClassLoader context: cc-web delegate: false ----------> Parent Classloader: java.net.URLClassLoader@1c53fd30 : java.lang.ClassNotFoundException: org.springframework.dao.TransientDataAccessResourceException com.weibo.api.motan.exception.MotanServiceException: error_message: biz exception cause is throwable error:class java.lang.Throwable, errmsg:PreparedStatementCallback; SQL [SELECT `free_pricing` FROM `account` WHERE `account_id`=?]; Before start of result set, status: 503, error_code: 10001,r=null at com.weibo.api.motan.proxy.RefererInvocationHandler.invoke(RefererInvocationHandler.java:127) at com.sun.proxy.$Proxy71.getFreePricingStatus(Unknown Source) at com.btzh.resource.ProfileResource.toCopyright(ProfileResource.java:285) 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.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81) 代码是很简单的一个sql查询: @Override public YesOrNo getFreePricingStatus(Integer accountId) { return jdbcTemplate.query("SELECT `free_pricing` FROM `account` WHERE `account_id`=?", new Object[] { accountId }, new ResultSetExtractor<YesOrNo>() { @Override public YesOrNo extractData(ResultSet rs) throws SQLException, DataAccessException { return YesOrNo.getByValue(rs.getInt("free_pricing")); } }); } 单元测试没有任何问题, 放到项目中运行就出现上面的报错. 后来想是不是因为缺少rs.next(), 导致指针仍然在第一个元素的前一个位置, 导致指针没有下移, 改了下: @Override public YesOrNo getFreePricingStatus(Integer accountId) { return jdbcTemplate.query("SELECT `free_pricing` FROM `account` WHERE `account_id`=?", new Object[] { accountId }, new ResultSetExtractor<YesOrNo>() { @Override public YesOrNo extractData(ResultSet rs) throws SQLException, DataAccessException { if (rs.next()) { return YesOrNo.getByValue(rs.getInt("free_pricing")); } return YesOrNo.NO; } }); } 好了. 但是没想清楚为什么单元测试没有报错, 待续.

优秀的个人博客,低调大师

python操作csv

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34173549/article/details/81285438 '''def build_excel(self): workbook = xlwt.Workbook(encoding='ascii') # 创建表 worksheet = workbook.add_sheet('My Worksheet') # 往表写内容 行 ,列 worksheet.write(1, 3, label='Row 0, Column 0 Value') workbook.save('Excel_Workbook.xlsx') csvFile = open("test42.cs v", 'w', newline='') try: writer = csv.writer(csvFile) writer.writerow(('id', '标题', '发布时间','视频时长', '播放次数', '评论数', '喜欢数', '分享数', '上传用户', '下载地址' )) for i in range(10): writer.writerow((1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) finally: csvFile.close() return csvFile;

优秀的个人博客,低调大师

Hive常用操作

1. 绑定数据 1.1 创建表&创建文本文件 create table fantj.t3(id int,name string,age int) row format delimited fields terminated by ','stored as textfile; hive> create table fantj.t3(id int,name string,age int) row format delimited fields terminated by ','stored as textfile; OK Time taken: 4.467 seconds hive> select * from fantj.t3; OK Time taken: 2.82 seconds 表示行格式用逗号来分割字段。 创建文本文件test.txt 我创建在/home/fantj目录下。 1,jiao,18 2,fantj,20 3,laowang,30 4,laotie,40 1.2 从本地导入到hive LOAD DATA LOCAL INPATH '/home/fantj/test.txt' OVERWRITE INTO TABLE t3; hive> LOAD DATA LOCAL INPATH '/home/fantj/test.txt' OVERWRITE INTO TABLE fantj.t3; Loading data to table fantj.t3 [Warning] could not update stats. OK Time taken: 26.334 seconds select * from fantj.t3; hive> select * from fantj.t3; OK 1 jiao 18 2 fantj 20 3 laowang 30 4 laotie 40 Time taken: 2.303 seconds, Fetched: 4 row(s) 导入成功! 1.3 从hdfs导入到hive 先将test文件上传到hdfs中 [root@s166 fantj]# hadoop fs -put test.txt /hdfs2hive -rw-r--r-- 3 root supergroup 46 /hdfs2hive/test.txt 进入hive,创建表t5 create table fantj.t5(id int,name string,age int) row format delimited fields terminated by ','stored as textfile; hive> create table fantj.t5(id int,name string,age int) row format delimited fields terminated by ','stored as textfile; OK Time taken: 3.214 seconds 执行导入 LOAD DATA INPATH '/hdfs2hive/test.txt' OVERWRITE INTO TABLE fantj.t5; hive> LOAD DATA INPATH '/hdfs2hive/test.txt' OVERWRITE INTO TABLE fantj.t5; Loading data to table fantj.t5 [Warning] could not update stats. OK Time taken: 25.498 seconds 检查是否成功: hive> select * from fantj.t5; OK 1 jiao 18 2 fantj 20 3 laowang 30 4 laotie 40 Time taken: 5.046 seconds, Fetched: 4 row(s)

优秀的个人博客,低调大师

Python操作MySql

一、linux客户端连接mssql server 1.linux下安装unixODBC 2.linux安装FreeTDS (1) 配置FreeTDS。 /etc/freetds/freetds.conf [egServer70] host = server ip port = 1433 tds Version = 7.0 [dsnName] host = server ip port = 1433 tds Version = 8.0 client charset = UTF-8 (2)配置odbc /etc/odbc.ini [dsnName] Driver = FreeTDS Description = Odbc connection via FreeTDS Trace = No Servername = dsnName Database = oneicdb (3)配置odbc /etc/odbc [FreeTDS] Description = FreeTDS Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so FileUsage = 1 CPTimeout = CPResure = client charset = utf-8 UsageCount = 1 [SQL Server] Description = FreeTDS ODBC driver for MSSQL Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so FileUsage = 1 import pyodbc strconn= 'DRIVER={SQL Server};SERVER=.;DATABASE=test;UID=sa;PWD=sa' db = pyodbc.connect(strconn) c = db.cursor() sql = '.....................' c.execute(sql) c.fetchone() c.fetchall() c.close() db.close() 存储过程调用:c.execute("{call sp_MemberAdrInsert_py (?,?,?,?,?,?,?,?,?,?)}", ('a','b','c','d','e','f','g','h','100086',0)) 1、存储过程可以直接返回值,如果返回一个值,那么存储过程里必须有:SET NOCOUNT ON 2、存储过程不可以output值 Welcome to Python world! I have a contract in this world! How about you?

优秀的个人博客,低调大师

phoenix操作hbase

代码实例 package oa.epoint.com.phoenix; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class PhoenixTest { private static String driver = "org.apache.phoenix.jdbc.PhoenixDriver"; public static void main(String[] args) throws SQLException { try { Class.forName(driver); System.out.println("驱动加载成功"); } catch (ClassNotFoundException e) { e.printStackTrace(); } Statement stmt = null; ResultSet rs = null; System.out.println("准备数据库连接"); Connection con = DriverManager.getConnection("jdbc:phoenix:100.2.5.1:2181:/hbase-unsecure"); System.out.println("连接成功"); stmt = con.createStatement(); stmt.executeUpdate("drop table if exists test5"); stmt.executeUpdate("create table if not exists test5 (id BIGINT not null primary key,name varchar)"); stmt.executeUpdate("UPSERT INTO test5 VALUES(123,'xubin')"); con.commit(); String sql = "select * from test5"; rs = stmt.executeQuery(sql); while (rs.next()) { System.out.print("id:"+rs.getInt("id")); System.out.println(",name:"+rs.getString("name")); } stmt.close(); con.close(); } }

优秀的个人博客,低调大师

python操作gmail

import imaplib, re class pygmail( object ): def __init__( self ): self .IMAP_SERVER = 'imap.gmail.com' self .IMAP_PORT = 993 self .M = None self .response = None self .mailboxes = [] def login( self , username, password): self .M = imaplib.IMAP4_SSL( self .IMAP_SERVER, self .IMAP_PORT) rc, self .response = self .M.login(username, password) return rc def get_mailboxes( self ): rc, self .response = self .M. list () for item in self .response: self .mailboxes.append(item.split()[ - 1 ]) return rc def get_mail_count( self , folder = 'Inbox' ): rc, self .response = self .M.select(folder) return self .response[ 0 ] def get_unread_count( self , folder = 'Inbox' ): rc, self .response = self .M.status(folder, "(UNSEEN)" ) unreadCount = re.search( "UNSEEN (\d+)" , self .response[ 0 ]).group( 1 ) return unreadCount def get_imap_quota( self ): quotaStr = self .M.getquotaroot( "Inbox" )[ 1 ][ 1 ][ 0 ] r = re. compile ( '\d+' ).findall(quotaStr) if r = = []: r.append( 0 ) r.append( 0 ) return float (r[ 1 ]) / 1024 , float (r[ 0 ]) / 1024 def get_mails_from( self , uid, folder = 'Inbox' ): status, count = self .M.select(folder, readonly = 1 ) status, response = self .M.search( None , 'FROM' , uid) email_ids = [e_id for e_id in response[ 0 ].split()] return email_ids def get_mail_from_id( self , id ): status, response = self .M.fetch( id , '(body[header.fields (subject)])' ) return response def rename_mailbox( self , oldmailbox, newmailbox): rc, self .response = self .M.rename(oldmailbox, newmailbox) return rc def create_mailbox( self , mailbox): rc, self .response = self .M.create(mailbox) return rc def delete_mailbox( self , mailbox): rc, self .response = self .M.delete(mailbox) return rc def logout( self ): self .M.logout() if __name__ = = "__main__" : demo = pygmail() demo.login( "renwenchao888@gmail.com" , "qqq191430791" ) mailBoxex = demo.get_mailboxes() for i in demo.response: print i demo.logout() ============================================================================= 本文转自被遗忘的博客园博客,原文链接:http://www.cnblogs.com/rollenholt/archive/2011/12/08/2280652.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

PyQt基本操作

PyQt的简介和基本安装方法读者可以自行google解决。先声明,本文章教基础,参考《征服Python》相关章节。不过不得不说,pyQt的教程真的好少,╮(╯▽╰)╭,悲催,大家有什么好的资料推荐一下,谢谢了。 先建立一个基本的界面看看: 1 2 3 4 5 6 7 8 9 10 11 12 import sys from PyQt4 import QtCore, QtGui class MyWindow( QtGui.QMainWindow ): def __init__( self ): QtGui.QMainWindow.__init__( self ) self .setWindowTitle( "PyQt" ) self .resize( 300 , 200 ) app = QtGui.QApplication( sys.argv ) mywindow = MyWindow() mywindow.show() app.exec_() 运行结果:

优秀的个人博客,低调大师

Java文件操作

1.以文件流的方式复制文件 将一个已存在文件复制到指定位置,如本例中将源文件"/home/hadoop/Scene1"拷贝一份重命名为“/home/hadoop/Scene1bak” 代码如下: View Code 输出结果为: 1024 89 而Scene1文件大小也刚好为(1113=1024+89)字节 2.获得控制台用户输入的信息 这个程序用户获得控制台输入的信息,代码如下: View Code 输出结果: 请输入命令: please input you commond 25 please input you commond 注意:这里输入输出的buffer长度是25,但是实际上字符串中有用的只有24个字符,这是因为buffer中最后一位是结束符。 3.利用PrintStream写文件 使用PrintStream能够往空文件中写入文本,代码如下: View Code 运行上述代码,将自动生成printStreamDemo和printStreamDemo2这两个文件,这了这两个文件的文本内容都是: This is 0 line. This is 1 line. This is 2 line. This is 3 line. This is 4 line. This is 5 line. This is 6 line. This is 7 line. This is 8 line. This is 9 line. 4. 利用StringBuffer写文件 代码如下: View Code 运行上述代码将自动生成文件StringBufferDemo,其文本内容为: 这是第0行。 这是第1行。 这是第2行。 这是第3行。 这是第4行。 这是第5行。 这是第6行。 这是第7行。 这是第8行。 这是第9行。 PS:java 流(Stream)的概念(2011-10-13) 流是 Java 中最重要的基本概念之一。文件读写、网络收发、进程通信,几乎所有需要输入输出的地方,都要用到流。流是做什么用的呢?就是做输入输出用的。为什么输入输出要用“流”这种方式呢?因为程序输入输出的基本单位是字节,输入就是获取一串字节,输出就是发送一串字节。但是很多情况下,程序不可能接收所有的字节之后再进行处理,而是接收一点处理一点。比方你下载魔兽世界,不可能全部下载到内存里再保存到硬盘上,而是下载一点就保存一点。这时,流这种方式就非常适合。在 Java 中,每个流都是一个对象。流分为两种:输入流(InputStream)和输出流(OutputStream)。对于输入流,你只要从流当中不停地把字节取出来就是了;而对于输出流,你只要把准备好的字节串传给它就行。 ________Java 程序 | | 外部系统 --|--(输入流)--> 处理逻辑 --(输出流)---|--> 外部系统 |__________________________|总体而言,我们要站在内存的角度想象java的输入流与输出流。输入流就是“我们是内存,外部系统有内容要输入到内存中,所以叫输入流”。输出流就是“我们是内存,我们要将数据从内存输出,写入到外部系统,所以叫输出流。” 本文转自xwdreamer博客园博客,原文链接:http://www.cnblogs.com/xwdreamer/archive/2011/04/14/2297029.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

cisco tftp 操作

1,在Windows*作系统的计算机上安装Cisco TFTP Server软件(文件名为TFTPServer1-1-980730.exe); 2,用Winzip软件将c2500-i-l.113-6.zip文件进行解压,解压后的文件名为c2500-i-l.113-6.bin,将此文件拷入硬盘中-----子目录,如D:\cisco。 3,启动Cisco TFTP Server软件; 4,在TFTP Server软件界面上选择“View”――“Options”,在Options界面上,在“TFTP Server root”选项上选择“Browse”,将该目录指向c2500-i-l.113-6.bin文件所在的目录,如D:\cisco或其它。 5,进入要升级的路由器下,将以太网的地址配置成与安装TFTP软件的计算机在同一个网段,并能ping通该计算机(其实也可以不在同一网段,只要能保证能ping通即可)。 6,在路由器特权状态下(如Router#下),键入Copy tftp flash 系统提示:Address or name of remote host [ ]?时键入TFTP软件所在机器IP地址。 系统提示:Source filename [ ]?时键入要升级的IOS软件文件名,在例中为c2500-i-l(此处为字母l,不是数字1).11(这两个是数字1,不是字母l)3-6.bin(注意.Bin不能丢)。 系统提示Destination filename [ ]?时,直接回车即可,表示和源文件名一致。 后面还有其它提问,按提示*作即可(如还有提示删除以前的IOS文件,以及确认消息等)。 等待系统提示完成时,升级过程完成。 整个过程大约2-3分钟。 7,重新启动。 注意,在升级过程中,千万不可断电或造成路由器与TFTP服务器的网络不畅等问题! 本文转自 yhw85 51CTO博客,原文链接:http://blog.51cto.com/yanghuawu/801243,如需转载请自行联系原作者

优秀的个人博客,低调大师

docker基础操作

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 opsnotes写了好多基础篇 docker http: / / opsnotes.net / 2015 / 07 / 06 / docker_install / 牛刀小试之docker安装部署 dockerpullubuntu: 12.04 dockerpulldl.dockerpool.com: 5000 / ubuntu: 12.04 dockerrun - t - iubuntu: 12.04 / bin / bash dockerimages dockerrunubuntu: 12.04 / bin / echo "helloworld" dockerpsa dockerexport 7582b0eaf376 >ubuntu.tar catubuntu.tar|docker import - test / buntu:v1. 0 dockerrmitest / buntu:v1. 0 dockersearchcentos dockerpullcentos 牛刀小试之docker镜像相关配置 dockerpullubuntu: 12.10 如上命令相当于dockerpullregistry.hub.docker.com / ubuntu:latest.是从docker默认的服务器下载latest镜像 也可以从dockerpool地方下载镜像 dockerrun - t - iubuntu / bin / bash dockerinspect 6d4946999d4f dockersearchmysql 可以看到很多关键字的镜像包括名字描述和镜像的使用欢迎度是否官方创建,感觉是不是有点像github - - automated = false只显示自动创建的镜像 - - no - trunc = false输出信息不截断显示 - s, - - stars = 0 显示指定星级的镜像 使用 - f可以强制删除,但是需要注意的是,强制删除会造成一些相关遗留的问题 dockerrun - tiubuntu: 14.04 / bin / bash dockercommit - m 'addedanewfile' - a 'dockerSteven' c72ad6c5adcdtest dockerimagestest 牛刀小试之docker容器增加删除 dockercreate - itubuntu:latest 启动容器有两种方式 1. 基于镜像新建一个容器并且启动 2. 把在终止的状态容器重新启动 dockerrun相当于dockercreate + dockerstart dockerrunubuntu / bin / echo "helloworld" 登陆到交互式模式下面, - t让docker分配一个伪终端,并绑定到容器的标准输出上 - i让容器的标准输出打开 可以是用crtl + d或者exit退出,需要注意的是,退出意味着终止 dockerrun - tiubuntu: 14.04 / bin / bash 有时候为了业务方便可以使用” - d“参数来后台启动 dockerrun - dubuntu / bin / bash - c "whiletrue;doechoHelloworld;sleep1;done" dockerlogs 6aa 连接的 ID dockerps - a - q dockerrestart 6aa 会将运行的容器终止,然后再重新启动它 dockerrm - f 436efb7b9933 0aced9db36e2 b89ee17998ec 牛刀小试之docker基于容器备份与恢复之export import dockerexporta457>test_for_run.tar cattest_for_run.tar|docker import - test / ubuntu:v1. 0 dockerimagestest / ubuntu 建议在上传环境中因容器是轻量级的,建议可以做成HA这样就可以防止单点故障。在容器故障的时候,可以快速的切换到其他的容器 牛刀小试之docker容器的连接方式 dockerrun - idtubuntu docker 1.3 版本之后自带命令,可以在容器直接运行命令,启动一个bash, exec 工具相对比较简单 docker exec - ti 7d3d35cb9c40 / bin / bash nsenter工具安装使用 把如下内容复制到“ / usr / local / bin / docker - enter”下面。 [root@test - devops~] #cat/usr/local/bin/docker-enter #!/bin/sh if [ - e$(dirname "$0" ) / nsenter];then #withboot2docker,nsenterisnotinthePATHbutitisinthesamefolder NSENTER = $(dirname "$0" ) / nsenter else NSENTER = nsenter fi if [ - z "$1" ];then echo "Usage:`basename" $ 0 "`CONTAINER[COMMAND[ARG]...]" echo"" echo "EnterstheDockerCONTAINERandexecutesthespecifiedCOMMAND." echo "IfCOMMANDisnotspecified,runsaninteractiveshellinCONTAINER." else PID = $(dockerinspect - - format "u" { % raw % } "``.`State`.`Pid`" "$1" ) #可以去掉u"{%raw%}" if [ - z "$PID" ];then exit 1 fi shift OPTS = "--target$PID--mount--uts--ipc--net--pid--" if [ - z "$1" ];then #Nocommandgiven. #UsesutoclearallhostenvironmentvariablesexceptforTERM, #initializetheenvironmentvariablesHOME,SHELL,USER,LOGNAME,PATH, #andstartaloginshell. "$NSENTER" $OPTSsu - root else #Useenvtoclearallhostenvironmentvariables. "$NSENTER" $OPTSenv - - ignore - environment - - "$@" fi fi chmod + x / usr / local / bin / docker - enter dockerrun - idtubuntu docker - entera457769fdd92 牛刀小试之docker数据卷容器共享 数据卷可以在容器之间共享和重用 对数据卷的修改会立马生效 对数据卷的更新不会影响镜像 卷会一直存在,直到没有容器使用 在dockerrun启动的时候可以加 - v参数来创建一个容器卷。注意多次创建可以使用 - v标记多个数据卷 dockerrun - d - P - - nameweb - v / webapptraining / webappecho "helloworld" 本地硬盘挂载 dockerrun - d - P - - nameweb - v / srv / webapp: / opt / webapp / training / webappecho "helloworld" 本地硬盘挂载一个只读的 - ro参数 [root@docker~] #dockerrun-d-P--nameweb-v/srv/webapp:/opt/webapp/:rotraining/webappecho"hellotest" 挂载一个本地主机文件作为数据卷,建议一般不要挂载一个文件 [root@docker~] #dockerrun--rm-it-v~/.bash_history:/.bash_historycentos:6/bin/bash 实战案例:数据卷容器 场景: 如果用户需要在容器之间共享一些持续更新的数据,最简单的办法就是使用数据卷容器。数据卷容器就是一个普通的容器。专门用它提供数据卷供其他容器挂载使用。 优点: 使用数据卷容器可以让用户在容器之间自由的升级和移动数据卷。 mkdir / dbdata dockerrun - it - v / dbdata / - - namedbdatacentos: 6 dockerrun - it - - volumes - from dbdata - - namedb1centos: 6 exit dockerrun - it - - volumes - from dbdata - - namedb2centos: 6 exit 启动容器 dockerstart 96513f616aa4 98a6cca3fee3 a85c2ed8df59 使用docker - enter登陆到db1在dbdata下面创建一个目录uptime 在其他两台机器查看 使用dockerfile创建基于ubuntu的ssh容器 touchDockerfilerun.sh catrun.sh #!/bin/bash chmod 400 authorized_keys 编写dockerFile [root@test - devopssshd_ubuntu] #catDockerfile #继承的镜像 FROMubuntu: 14.04 #作者信息 MAINTAINER from steven(www.opsnotes.net) #安装SSH服务和VIM服务 RUNapt - getinstall - yopenssh - servervim RUNmkdir - p / var / run / sshd RUNmkdir - p / root / .ssh RUNecho 'root:123qwer' |chpasswd RUNsed - i "s/#UsePrivilegeSeparation.*/UsePrivilegeSeparationno/g" / etc / ssh / sshd_config RUNsed - i "s/UsePAM.*/UsePAMno/g" / etc / ssh / sshd_config RUNsed - i 's/^PermitRootLoginwithout-password/PermitRootLoginyes/g' / etc / ssh / sshd_config #取消PAM限制 RUNsed - i '/pam_loginuid.so/csessionoptionalpam_loginuid.so' / etc / pam.d / sshd #复制文件,给脚本可执行权限 ADDauthorized_keys / root / .ssh / authorized_keys ADDrun.sh / run.sh RUNchmod + x / run.sh #设置开放端口 EXPOSE 22 #设置自动开启命令 CMD[ "/run.sh" ] 创建镜像 dockerbuild - tsshd:dockerfile. 测试镜像,运行容器 dockerrun - d - p 10122 : 22 sshd:dockerfile netstat - tlnp 登陆 ssh - p 10122 root@ 121.41 . 118.184 dockercommit创建基于ubuntu的ssh镜像 dockerrun - itubuntu: 14.04 / bin / bash vi / root / .ssh / authorized_keys客户端的公钥放到里面,那台机器需要登陆就需要登陆的public放到里面 dockercommitfb0ubuntu_sshd: 14.04 启动镜像,本地的 10022 端口绑定到docker容器的 22 端口 dockerrun - p 10022 : 22 - dubuntu_sshd: 14.04 / ssh.sh ssh - p 10022 root@ 121.41 . 118.184 使用dockerfile创建基于centos的ssh容器 打包的镜像需要支持SSHkey和密码登录 编写Dockerfile文件 [root@test - devopssshd_centos] #catDockerfile #继承的镜像 FROMcentos: 6 #作者信息 MAINTAINERsteven<www.opsnotes.net> #安装SSH服务和VIM服务 RUNyuminstall - yopenssh - serveropenssh - clientsvim RUNmkdir - p / root / .ssh / ADDauthorized_keys / root / .ssh / authorized_keys RUNssh - keygen - f / etc / ssh / ssh_host_rsa_key RUNssh - keygen - tdsa - f / etc / ssh / ssh_host_dsa_key RUNecho 'root:123qwer' |chpasswd RUNsed - i "s/#UsePrivilegeSeparation.*/UsePrivilegeSeparationno/g" / etc / ssh / sshd_config RUNsed - i "s/UsePAM.*/UsePAMno/g" / etc / ssh / sshd_config #取消PAM限制 RUNsed - i '/pam_loginuid.so/csessionoptionalpam_loginuid.so' / etc / pam.d / sshd #复制文件,给脚本可执行权限 ADDrun.sh / run.sh RUNchmod + x / run.sh #设置开放端口 EXPOSE 22 #设置自动开启命令 CMD[ "/run.sh" ] dockerbuild - t 'sshd/centos62' . 查看镜像是否创建成功 [root@test - devopssshd_centos] #dockerimages 启动docker容器 [root@test - devopssshd_centos] #dockerrun-d-p10125:22sshd/centos62 测试,可以测试key登录以及密码登录 ssh - p 10125 root@ 121.41 . 118.184 zhangkeyuan@opsnotes:~ssh - p 10125 root@ 121.41 . 118.184 docker容器ubuntu安装apache + php [root@test - devopsapache_ubuntu] #pwd / home / docker / apache_ubuntu [root@test - devopsapache_ubuntu] #tree . ├──Dockerfile ├──run.sh └──sample ├──index.html └──index.php [root@test - devopsapache_ubuntu] #catDockerfile #继承的镜像 FROMsshd / ubuntu #作者信息 MAINTAINER from steven(www.opsnotes.net) #setenv ENVDEBIAN_FRONTENDnoninteractive #install #RUNapt-get-yqinstallapache2&&rm-rf/var/lib/apt/lists/* RUNapt - getupdate&&apt - get - yinstallapache2php5php5 - clilibapache2 - mod - php5php5 - gdphp5 - jsonphp5 - ldapphp5 - mysqlphp5 - pgsql #RUNecho"Asia/Shanghai">/etc/timezone&&dpkg-reconfigure-fnoninteractivetzdata #addscripts ADDrun.sh / run.sh RUNchmod + x / * .sh #addwebsite RUNrm - rf / var / www / html / * COPYsample / / var / www / html / #setapacheenv ENVAPACHE_RUN_USERwww - data ENVAPACHE_RUN_GROUPwww - data ENVAPACHE_LOG_DIR / var / log / apache2 ENVAPACHE_PID_FILE / var / run / apache2.pid ENVAPACHE_RUN_DIR / var / run / apache2 ENVAPACHE_LOCK_DIR / var / lock / apache2 ENVAPACHE_SERVERADMINadmin@opsnotes.net ENVAPACHE_SERVERNAMElocalhost ENVAPACHE_SERVERALIASdocker.localhost ENVAPACHE_DOCUMENTROOT / var / www EXPOSE 80 CMD[ "/run.sh" ] [root@test - devopsapache_ubuntu] #catrun.sh #!/bin/bash / usr / sbin / sshd& / usr / sbin / apache2ctl - DFOREGROUND [root@test - devopsapache_ubuntu] #catsample/index.htmlsample/index.php Hellodocker for apache2 <?php phpinfo(); ?> dockerbuild - tapache / ubuntu. 允许DOCKER镜像指定端口以及映射 dockerrun - d - p 10122 : 22 - p 888 : 80 apache / ubuntu docker - enterfbe logout docker - 创建nginx镜像 [root@test - devopsnginx_ubuntu] #tree . ├──Dockerfile └──run.sh [root@test - devopsnginx_ubuntu] #catDockerfile #继承的镜像 FROMsshd / ubuntu #作者信息 MAINTAINER from steven(www.opsnotes.net) #install RUNapt - getinstall - ynginx RUNsed - i 's/listen\[\:\:\]:80default_serveripv6only=on;/#listen\[\:\:\]:80default_serveripv6only=on;/g' / etc / nginx / sites - enabled / default RUNecho "\ndaemonoff;" >> / etc / nginx / nginx.conf #addscripts ADDrun.sh / run.sh RUNchmod + x / * .sh WORKDIR / etc / nginx #Exposeports. EXPOSE 80 #Definedefaultcommand. CMD[ "/run.sh" ] [root@test - devopsnginx_ubuntu] #catrun.sh #!/bin/bash / usr / sbin / sshd& / usr / sbin / nginx dockerbuild - tnginx / ubuntu. 本文转自 liqius 51CTO博客,原文链接:http://blog.51cto.com/szgb17/1911458,如需转载请自行联系原作者

优秀的个人博客,低调大师

EditText操作收集

1.android EditText插入字符串到光标所在位置 EditText mTextInput=(EditText)findViewById(R.id.input);//EditText对象 int index = mTextInput.getSelectionStart();//获取光标所在位置 String text="I want to input str"; Editable edit = mTextInput.getEditableText();//获取EditText的文字 if (index < 0 || index >= edit.length() ){ edit.append(text); }else{ edit.insert(index,text);//光标所在位置插入文字 } 2.在EditText移动光标 我自己设计了一个拨号键盘,用来模拟android的手机拨号键,自己画了的键盘,显示的控件时editText。 但是点拨号键时光标不能随之输入的字符后移,而是一直呆在最前面。在看了android的文档关于edittext以及它的父类都没有看到相应的解决方法。 最后在google中搜索到一个解决方法。 EditText inputField = new EditText(this); Editable etext = inputField.getText(); int position = etext.length(); Selection.setSelection(etext, position); 最后可以将光标移动到EditText文本的右边。 3.EditText始终不弹出软件键盘 1.EditText默认不弹出软件键盘 方法一: 在AndroidMainfest.xml中选择哪个activity,设置windowSoftInputMode属性为adjustUnspecified|stateHidden 例如:<activity android:name=".Main" android:label="@string/app_name" android:windowSoftInputMode="adjustUnspecified|stateHidden" android:configChanges="orientation|keyboardHidden"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> 方法二: 让EditText失去焦点,使用EditText的clearFocus方法 例如:EditText edit=(EditText)findViewById(R.id.edit); edit.clearFocus(); 方法三: 强制隐藏Android输入法窗口 例如:EditText edit=(EditText)findViewById(R.id.edit); InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(edit.getWindowToken(),0); 2.EditText始终不弹出软件键盘 例:EditText edit=(EditText)findViewById(R.id.edit); edit.setInputType(InputType.TYPE_NULL); 4.三种方式限制EditText的输入字数[转] 方法一:利用TextWatcher editText.addTextChangedListener(new TextWatcher() { private CharSequence temp; private boolean isEdit = true; private int selectionStart ; private int selectionEnd ; @Override public void beforeTextChanged(CharSequence s, int arg1, int arg2, int arg3) { temp = s; } @Override public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) { } @Override public void afterTextChanged(Editable s) { selectionStart = editText.getSelectionStart(); selectionEnd = editText.getSelectionEnd(); Log.i("gongbiao1",""+selectionStart); if (temp.length() > Constant.TEXT_MAX) { Toast.makeText(KaguHomeActivity.this, R.string.edit_content_limit, Toast.LENGTH_SHORT) .show(); s.delete(selectionStart-1, selectionEnd); int tempSelection = selectionStart; editText.setText(s); editText.setSelection(tempSelection); } } }); 方法二:利用InputFilter editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(100)}); //其中100最大输入字数 方法三:在XML中设定 Xml代码 <EditText . . . Android:maxLength="100" /> 本文转自农夫山泉别墅博客园博客,原文链接:http://www.cnblogs.com/yaowen/p/4917944.html,如需转载请自行联系原作者

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册