首页 文章 精选 留言 我的

精选列表

搜索[笔记],共9150篇文章
优秀的个人博客,低调大师

学习笔记-4.1用户管理命令

复习: /etc/passwd: 用户名:密码:UID:GID:注释:家目录:默认shell /etc/group: 组名:密码:GID:以此组为其附加组的用户列表 /etc/shadow: 用户名:密码:最近一次修改密码的时间:最短使用期限,最长使用期限: 警告时间:非活动时间:过期时间 useradd [options] USERNAME useradd -u 1000 user1 -u 指定其UID -g GID(基本组) 指定组一定要存在 -G GID,... (附加组) -c "COMMENT"指定注释信息 -d /path/to/directory指定家目录,默认是home下 -s SHELL useradd -s /sbin/nologin user5 su - user5 -m -k 强制复制bash配置文件到家目录 -M 创建用户,不创建家目录 -r 添加一个系统用户 /etc/login.defs /etc/shells:指定了当前系统可用的安全shell 环境变量:PATH HISTSIZE SHELL userdel: userdel [option] USERNAME 不指定选项,不会删除家目录 -r 删除用户的同时,同时删除用户的家目录 id :查看用户的账号属性信息 -u -g -G -n 上面都可用和-n合用 finger USERNAME(user1)查看用户账号相关信息 修改用户账号属性: usermod -u usermod -u 2002 user2 -g (基本组,事先存在的组) -G 附加组,已有附件组,修改了后原有附件组就没有了 -a -G:追加附件组(-a与-G联合使用) -c 注释 -d -m 为用户指定新的家目录,并移动此前新建的文件到新的家目录 -s shell -l 修改用户名 -L:锁定账号 -U:解锁 chsh:修改用户的默认shell chfn:修改用户的注释信息(fn是finger的缩写) 密码管理: passwd [USERNAME] --stdin -l 锁定账号 -u 解锁 -d 删除用户密码(禁止登录) echo "redhat" | passwd --stdin user3 pwch(passwdcheck)检查用户账号完整性 组管理: 创建组:groupadd groupadd -g GID -r 添加为系统组 groupmod -g GID -n GRPNAME groupdel gpasswd:为组设定密码 newgrp 临时切换基本组 exit退出 练习: 1 创建一个用户mandriva ,其ID号2002,基本组为distro(组ID3003),附加组 为linux: # groupadd -g 3003 distro # groupadd linux # useradd -u 2002 -g distro -G linux mandriva 2 创建一个用户fedora,其全名为Fedora Community,默认shell为tcsh # useradd -c "Fedora Community" -s /bin/tcsh/ fedora 3 修改mandriva的ID号为4004,基本组为linux,附加组为distro和Fedora # usermod -u 4004 -g linux -G distro,fedora mandriva 4 给Fedora加密码,并设定其密码最短使用期限为2天,最长为50天 # passwd -n 2 -x 50 fedora 5 将madriva的默认shell改为/bin/bash # usermod -s /bin/bash mandrira 6 添加系统用户hbase,且不允许其登陆系统 #useradd -r -s /sbin/noglogin hbase change(改变密码过期信息的) -d 最近一次的修改时间 -E 过期时间 -r: 非活动时间 -m 最短使用时间 -M 最长使用时间 -w:警告时间 本文转自飞行萌51CTO博客,原文链接: http://blog.51cto.com/8527508/1939822,如需转载请自行联系原作者

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

ELK日志分析集群部署笔记

ELK是什么?E=ElasticSearch ,一款基于的Lucene的分布式搜索引擎,我们熟悉的github,就是由ElastiSearch提供的搜索,据传已经有10TB+的数据量。L=LogStash , 一款分布式日志收集系统,支持多输入源,并内置一些过滤操作,支持多输入元K=Kibana , 一款配合ElasticSearch的web可视化界面,内置非常各种查询,聚合操作,并拥有漂亮的图形化展示功能为什么要用ELK?在实际应用中,我们的日志是非常重要的,它通常会记录一些比较重要的信息,如应用程序的log记录的error,warn级别的log,通常在量小的情况下,我们可以直接vi+awk+sed+grep定位原因,在量大的时候,这种方式就捉襟见肘了,而且我们还要各种聚合,或者基于异常多个关键词的搜索,并有且,或,交,并,差,补,排序等一些操作,而且相应速度必须给力,如果线上环境出了故障,能够立刻准确定位,ELK就是高手,在百万大军中取上将首级,犹如探囊取物,所以这时候ELK就非常适合了,当然除此之外,ELK也经常在运维工作中大放光彩,在应用级别的实时监控,非常适合一些重要核心服务的预警。ELK如何安装搭建?环境要求:Linux系统:Centos6.5 [root@ELK-Server ~]# cat /etc/redhat-release CentOS release 6.5 (Final) Java版本:JDK1.8 [root@ELK-Server ~]# java -version openjdk version "1.8.0_51" OpenJDK Runtime Environment (build 1.8.0_51-b16) OpenJDK 64-Bit Server VM (build 25.51-b03, mixed mode) ELK均为最新版本:(1)ElasticSearch1.7.2 基于Lucene4.10.4的版本(2)Logstash1.5.4(3)Kibana4.1.2集群拓扑:ElasticSearch 3台机器:集群名:search机器名+es节点名 => ip地址h1 => 192.168.1.120h2 => 192.168.1.121h3 => 192.168.1.122Logstash 192.168.1.120Kibana 192.168.1.120下载:elasticsearch: wget https://download.elastic.co/elasticsearch/elasticsearch/elasticsearch-1.7.3.tar.gzlogstash : wget https://download.elastic.co/logstash/logstash/logstash-1.5.4.tar.gzkibana : wget https://download.elastic.co/kibana/kibana/kibana-4.1.2-linux-x64.tar.gz 一: 安装elasticsearch集群:(1)解压到指定目录(2)配置elasticsearch.yml里面,集群名字和节点名字,如果不配置默认集群名为elasticsearch,节点名随机生成一个(3) 在线安装head和bigdisk插件直接在elasticsearch的根目录下,分别输入:bin/plugin --install mobz/elasticsearch-head 安装headbin/plugin --install lukas-vlcek/bigdesk 安装bigdesk(4)scp分发安装完毕后的elasticsearch(5)依次启动各个机器上的elasticsearch #/usr/local/elasticsearch/bin/elasticsearch 如果启动时遇到以下报错信息: [root@localhost elasticsearch]# ./bin/elasticsearch {1.7.3}: Initialization Failed ... - RuntimeException[Java version: 1.7.0_45 suffers from critical bug https://bugs.openjdk.java.net/browse/JDK-8024830 which can cause data corruption. Please upgrade the JVM, see http://www.elastic.co/guide/en/elasticsearch/reference/current/_installation.html for current recommendations. If you absolutely cannot upgrade, please add -XX:-UseSuperWord to the JVM_OPTS environment variable. Upgrading is preferred, this workaround will result in degraded performance.] 解决方法: # yum -y install java-1.8.0* # yum remove java 查看下java版本号:是否是1.8.0(因为最新版elasticsearch需要最新的java支持) [root@localhost elasticsearch]# java -version openjdk version "1.8.0_71" OpenJDK Runtime Environment (build 1.8.0_71-b15) OpenJDK 64-Bit Server VM (build 25.71-b15, mixed mode) 问题2: [root@localhost elasticsearch]# ./bin/elasticsearch Can't start up: not enough memory 解决方法也是重启安装下java 就行了 (6)head显示如下: (7)bigdisk显示如下:二:安装logstash(1)解压到指定目录(2)在根木下新建一个conf目录,在里面新建一个配置文件first.conf (3)启动logstash执行命令: bin/logstash -f conf/first.conf三:安装kibana(1)解压到指定目录(2)在根目录执行bin/kibana直接启动(3)访问http://192.168.1.120:5601/ 配置一个ElasticSearch索引(4)在logstach里面添加数据(5)查看图表:刚新加的数据四: 至此,ELK组件已经安装完毕,带图形化界面的简单日志查询分析系统就搞定了本篇只是一个简单的入门例子,如需深入可以研究elastic的官网文档:https://www.elastic.co/guide/index.html 本文转自yangxuncai110 51CTO博客,原文链接:http://blog.51cto.com/zlyang/1737622,如需转载请自行联系原作者

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

openstack学习笔记七 swift安装

项目--对象存储--容器 在容器里你创建的即使是一个文件夹,那么体现在硬盘里,也是一个文件,也就是对象object 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 [root@h1~(keystone_admin)] #openstackservicelist +----------------------------------+------------+--------------+ |ID|Name|Type| +----------------------------------+------------+--------------+ |30c62c3c0797462a8bd4ff059a71296e|swift|object-store| [root@h1~(keystone_admin)] #keystoneendpoint-list|grep30c62c3c0797462a8bd4ff059a71296e |2408bc6cb5164053b86c0983fd39961a|RegionOne|http: //192 .168.1.201:8080 /v1/AUTH_ %(tenant_id)s|http: //192 .168.1.201:8080 /v1/AUTH_ %(tenant_id)s|http: //192 .168.1.201:8080|30c62c3c0797462a8bd4ff059a71296e| [root@h1~(keystone_admin)] #swiftlist h1 [root@h1~(keystone_admin)] #swiftlisth1 test1/ test1 /k1 .pem [root@h1~(keystone_admin)] #find/srv/node/swiftloopback/-typef-name"*.data" /srv/node/swiftloopback/objects/188901/27f/b87961659e1149b7094bb52b5d60f27f/1467698512 .58656.data ##删除k1后就没有了 /srv/node/swiftloopback/objects/59261/c81/39df7c7803321e4878fdcec1ac469c81/1467698493 .15690.data 映射 :ring(环) 映射到硬盘 容器 在容器里面创建对象 对象 文件就是对象 账户 权限 ring文件 保存到硬盘 account.ring.gz 账户 container.ring.gz 容器 object.ring.gz 对象 保存到硬盘里的目录,这个目录为zone /srv/node/swiftloopback/ 挂载点 必须放在/srv/node/目录下 zone1 zone2 两个相同,备份 packstack方式安装完成后,上传一个文件,只在硬盘里保留一份 对象先映射到 虚拟节点/分区partition 2^n 再映射到zone 目的:减少数据的迁移量 swift服务 1 一致性服务 consisteny server auditor 定期扫描,如果出现问题,就把有问题的文件放隔离区 replicate 从另外的zone复制相同的文件过来,实现数据同步 update 如果replicate失效了,那么等段时间再试 2 代维服务proxy server 接受用户发送过来的请求,比如上传、删除等请求 3 存储服务 容器服务器 container server 对象服务器 object server 账户服务器 acount server 安装软件 1 2 [root@h4~] #yumlistopenstack-swift* [root@h4~] #yum-yinstallopenstack-swift.noarchopenstack-swift-account.noarchopenstack-swift-container.noarchopenstack-swift-object.noarchopenstack-swift-proxy.noarchmemcache*python-swiftclient 任何服务都要向keystone进行注册 1 2 3 [root@h4~(keystone_admin)] #keystoneuser-create--nameswift--passhequan [root@h4~(keystone_admin)] #keystonetenant-create--nameservices [root@h4~(keystone_admin)] #keystoneuser-role-add--userswift--tenantservices--roleadmin 创建服务,指定endpoint 1 2 [root@h4~(keystone_admin)] #keystoneservice-create--nameswift--typeobject-store--description"swift" keystoneendpoint-create--service- id 0995c9a9ed4847da86435bca9a7be8fc--publicurl 'http://192.168.1.204:8080/v1/AUTH_%(tenant_id)s' --internalurl 'http://192.168.1.204:8080/v1/AUTH_%(tenant_id)s' --adminurl 'http://192.168.1.204:8080' 配置swift 准备了2个分区 1 2 3 zone1zone2在 /srv/node 12 /dev/sdb1 /srv/node/zone1 xfsdefaults00 ##挂载 13 /dev/sdb2 /srv/node/zone2 xfsdefaults00 1 [root@h4~(keystone_admin)] #chown-Rswift.swift/srv/node/ 1 2 3 4 5 6 7 8 9 10 [root@h4swift(keystone_admin)] #catswift.conf [swift- hash ] swift_hash_path_suffix=%SWIFT_HASH_PATH_SUFFIX% [root@h1~(keystone_admin)] #find/srv/node/swiftloopback/-typef-name"*.data" /srv/node/swiftloopback/objects/102340/afe/63f12ea37cca17f0227381adcf93eafe/1467982747 .16551.data zone对象类型/分区的编号 /sufix/ 文件名字的 hash /上传文件的时间戳 [root@h1~(keystone_admin)] #date--date=@1467982747.16551 2016年07月08日星期五20:59:07CST 创建ring文件的准备工作 创建模板,设定有几个备份,有多少分区。 1 2 3 [root@h4swift(keystone_admin)] #swift-ring-builderaccount.buildercreate1221 [root@h4swift(keystone_admin)] #swift-ring-builderobject.buildercreate1221 [root@h4swift(keystone_admin)] #swift-ring-buildercontainer.buildercreate1221 指定映射位置 1 2 3 4 5 6 7 8 [root@h4swift] #vimaccount-server.conf#3个都要改ip 6bind_ip=192.168.1.204 [root@h4swift(keystone_admin)] #swift-ring-builderaccount.builderaddz1-192.168.1.204:6202/zone1100 [root@h4swift(keystone_admin)] #swift-ring-builderaccount.builderaddz2-192.168.1.204:6202/zone2100 [root@h4swift(keystone_admin)] #swift-ring-builderobject.builderaddz1-192.168.1.204:6200/zone1100 [root@h4swift(keystone_admin)] #swift-ring-builderobject.builderaddz2-192.168.1.204:6200/zone2100 [root@h4swift(keystone_admin)] #swift-ring-buildercontainer.builderaddz1-192.168.1.204:6201/zone1100 [root@h4swift(keystone_admin)] #swift-ring-buildercontainer.builderaddz2-192.168.1.204:6201/zone2100 创建ring文件 1 2 3 4 5 [root@h4swift(keystone_admin)] #swift-ring-builderaccount.builderrebalance [root@h4swift(keystone_admin)] #swift-ring-builderobject.builderrebalance [root@h4swift(keystone_admin)] #swift-ring-buildercontainer.builderrebalance [root@h4swift(keystone_admin)] #ls*.gz account.ring.gzcontainer.ring.gzobject.ring.gz 启动服务 1 2 3 4 5 6 [root@h4srv(keystone_admin)] #systemctlstartopenstack-swift-accountopenstack-swift-objectopenstack-swift-container [root@h4srv(keystone_admin)] #systemctlis-activeopenstack-swift-accountopenstack-swift-objectopenstack-swift-container active active active [root@h4srv(keystone_admin)] #systemctlenableopenstack-swift-accountopenstack-swift-objectopenstack-swift-container 代维服务proxy server 1 2 3 4 5 6 7 8 9 10 11 [root@h4swift(keystone_admin)] #vimproxy-server.conf 53[filter:authtoken] 54 paste .filter_factory=keystonemiddleware.auth_token:filter_factory 55admin_tenant_name=services 56admin_user=swift 57admin_password=hequan 58 # 59identity_uri=http: //192 .168.1.204:35357/ 60auth_port=35357 61auth_protocol=http 62 #auth_uri=http://192.168.1.204:5000/ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 [root@h4swift(keystone_admin)] #systemctlstartopenstack-swift-proxy.service [root@h4swift(keystone_admin)] #systemctlenableopenstack-swift-proxy.service [root@h4swift(keystone_admin)] #systemctlstartmemcached.service [root@h4swift(keystone_admin)] #systemctlenablememcached.service [root@h4swift(keystone_admin)] #swiftposth1 [root@h4swift(keystone_admin)] #swiftlist h1 [root@h4swift(keystone_admin)] #swiftuploadh1/etc/hosts 任意一个分区挂了,还是可以正常查看 两个都挂了,就看不到了 本文转自 295631788 51CTO博客,原文链接:http://blog.51cto.com/hequan/1812861,如需转载请自行联系原作者

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

Nginx学习笔记(一) Nginx架构

Nginx全程是什么?Nginx ("engine x") 是一个高性能的 HTTP 和反向代理服务器,也是一个 IMAP/POP3/SMTP代理服务器。 daemon守护线程 nginx在启动后,在unix系统中会以daemon的方式在后台运行,后台进程包含一个master进程和多个worker进程。 当然nginx也是支持多线程的方式的,只是我们主流的方式还是多进程的方式,也是nginx的默认方式。 master进程主要用来管理worker进程,包含:接收来自外界的信号,向各worker进程发送信号,监控worker进程的运行状态,当worker进程退出后(异常情况下),会自动重新启动新的worker进程。 worker进程则是处理基本的网络事件。多个worker进程之间是对等的,他们同等竞争来自客户端的请求,各进程互相之间是独立的。一个请求,只可能在一个worker进程中处理,一个worker进程,不可能处理其它进程的请求。 worker进程的个数是可以设置的,一般我们会设置与机器cpu核数一致。更多的worker数,只会导致进程来竞争cpu资源了,从而带来不必要的上下文切换。而且,nginx为了更好的利用多核特性,具有cpu绑定选项,我们可以将某一个进程绑定在某一个核上,这样就不会因为进程的切换带来cache的失效。 惊群现象 每个worker进程都是从master进程fork过来。在master进程里面,先建立好需要listen的socket之后,然后再fork出多个worker进程,这样每个worker进程都可以去accept这个socket(当然不是同一个socket,只是每个进程的这个socket会监控在同一个ip地址与端口,这个在网络协议里面是允许的)。一般来说,当一个连接进来后,所有在accept在这个socket上面的进程,都会收到通知,而只有一个进程可以accept这个连接,其它的则accept失败。 相对于线程,采用进程的优点 进程之间不共享资源,不需要加锁,所以省掉了锁带来的开销。 采用独立的进程,可以让互相之间不会影响,一个进程退出后,其它进程还在工作,服务不会中断,master进程则很快重新启动新的worker进程。 编程上更加容易。 多线程的问题 而多线程在多并发情况下,线程的内存占用大,线程上下文切换造成CPU大量的开销。想想apache的常用工作方式(apache也有异步非阻塞版本,但因其与自带某些模块冲突,所以不常用),每个请求会独占一个工作线程,当并发数上到几千时,就同时有几千的线程在处理请求了。这对操作系统来说,是个不小的挑战,线程带来的内存占用非常大,线程的上下文切换带来的cpu开销很大,自然性能就上不去了,而这些开销完全是没有意义的。 异步非阻塞 异步的概念和同步相对的,也就是不是事件之间不是同时发生的。 非阻塞的概念是和阻塞对应的,阻塞是事件按顺序执行,每一事件都要等待上一事件的完成,而非阻塞是如果事件没有准备好,这个事件可以直接返回,过一段时间再进行处理询问,这期间可以做其他事情。但是,多次询问也会带来额外的开销。 总的来说,Nginx采用异步非阻塞的好处在于: 不需要创建线程,每个请求只占用少量的内存 没有上下文切换,事件处理非常轻量 淘宝tengine团队说测试结果是“24G内存机器上,处理并发请求可达200万”。 本文转自cococo点点博客园博客,原文链接:http://www.cnblogs.com/coder2012/p/3141469.html,如需转载请自行联系原作者

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

Android开发学习笔记:浅谈WebView

WebView(网络视图)能加载显示网页,可以将其视为一个浏览器。它使用了WebKit渲染引擎加载显示网页,实现WebView有以下两种不同的方法: 第一种方法的步骤: 1.在要Activity中实例化WebView组件:WebView webView = new WebView(this); 2.调用WebView的loadUrl()方法,设置WevView要显示的网页: 互联网用:webView.loadUrl("http://www.google.com"); 本地文件用:webView.loadUrl("file:///android_asset/XX.html");本地文件存放在:assets文件中 3.调用Activity的setContentView()方法来显示网页视图 4.用WebView点链接看了很多页以后为了让WebView支持回退功能,需要覆盖覆盖Activity类的onKeyDown()方法,如果不做任何处理,点击系统回退剪键,整个浏览器会调用finish()而结束自身,而不是回退到上一页面 5.需要在AndroidManifest.xml文件中添加权限,否则会出现Web page not available错误。<uses-permissionandroid:name="android.permission.INTERNET"/> 下面是具体例子: MainActivity.java packagecom.android.webview.activity; importandroid.app.Activity; importandroid.os.Bundle; importandroid.view.KeyEvent; importandroid.webkit.WebView; publicclassMainActivityextendsActivity{ privateWebViewwebview; @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); //实例化WebView对象 webview=newWebView(this); //设置WebView属性,能够执行Javascript脚本 webview.getSettings().setJavaScriptEnabled(true); //加载需要显示的网页 webview.loadUrl("http://www.51cto.com/"); //设置Web视图 setContentView(webview); } @Override //设置回退 //覆盖Activity类的onKeyDown(intkeyCoder,KeyEventevent)方法 publicbooleanonKeyDown(intkeyCode,KeyEventevent){ if((keyCode==KeyEvent.KEYCODE_BACK)&&webview.canGoBack()){ webview.goBack();//goBack()表示返回WebView的上一页面 returntrue; } returnfalse; } 在AndroidManifest.xml文件中的17行添加权限 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.webview.activity" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="10" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.INTERNET"/> </manifest> 效果图: 第二种方法的步骤: 1、在布局文件中声明WebView 2、在Activity中实例化WebView 3、调用WebView的loadUrl( )方法,设置WevView要显示的网页 4、为了让WebView能够响应超链接功能,调用setWebViewClient( )方法,设置 WebView视图 5、用WebView点链接看了很多页以后为了让WebView支持回退功能,需要覆盖覆盖Activity类的onKeyDown()方法,如果不做任何处理,点击系统回退剪键,整个浏览器会调用finish()而结束自身,而不是回退到上一页面 6、需要在AndroidManifest.xml文件中添加权限,否则出现Web page not available错误。 <uses-permission android:name="android.permission.INTERNET"/> 下面是具体的例子: MainActivity.java packagecom.android.webview.activity; importandroid.app.Activity; importandroid.os.Bundle; importandroid.view.KeyEvent; importandroid.webkit.WebView; importandroid.webkit.WebViewClient; publicclassMainActivityextendsActivity{ privateWebViewwebview; @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); webview=(WebView)findViewById(R.id.webview); //设置WebView属性,能够执行Javascript脚本 webview.getSettings().setJavaScriptEnabled(true); //加载需要显示的网页 webview.loadUrl("http://www.51cto.com/"); //设置Web视图 webview.setWebViewClient(newHelloWebViewClient()); } @Override //设置回退 //覆盖Activity类的onKeyDown(intkeyCoder,KeyEventevent)方法 publicbooleanonKeyDown(intkeyCode,KeyEventevent){ if((keyCode==KeyEvent.KEYCODE_BACK)&&webview.canGoBack()){ webview.goBack();//goBack()表示返回WebView的上一页面 returntrue; } returnfalse; } //Web视图 privateclassHelloWebViewClientextendsWebViewClient{ @Override publicbooleanshouldOverrideUrlLoading(WebViewview,Stringurl){ view.loadUrl(url); returntrue; } } } main.xml <?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> 在AndroidManifest.xml文件中的17行添加权限 <?xmlversion="1.0"encoding="utf-8"?> <manifestxmlns:android="http://schemas.android.com/apk/res/android" package="com.android.webview.activity" android:versionCode="1" android:versionName="1.0"> <uses-sdkandroid:minSdkVersion="10"/> <applicationandroid:icon="@drawable/icon"android:label="@string/app_name"> <activityandroid:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <actionandroid:name="android.intent.action.MAIN"/> <categoryandroid:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> <uses-permissionandroid:name="android.permission.INTERNET"/> </manifest> 效果图: 本文转自 lingdududu 51CTO博客,原文链接:http://blog.51cto.com/liangruijun/647456

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

python学习笔记文件操作(六)

1、文件操作流程: 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件 如下文件: 1 2 3 4 5 6 2017 - 03 - 24 11 : 25 : 06 : 349 - info:[debug][AndroidBootstrap]Sendingcommandtoandroid:{ "cmd" : "shutdown" } 2017 - 03 - 24 11 : 25 : 06 : 355 - info:[debug][AndroidBootstrap]Receivedcommandresult from bootstrap 2017 - 03 - 24 11 : 25 : 06 : 356 - info:[debug][UiAutomator]ShuttingdownUiAutomator 2017 - 03 - 24 11 : 25 : 06 : 357 - info:[debug][UiAutomator]Movingtostate 'stopping' 2017 - 03 - 24 11 : 25 : 06 : 360 - info:[AndroidBootstrap][BOOTSTRAPLOG][debug]Gotdata from client:{ "cmd" : "shutdown" } 2017 - 03 - 24 11 : 25 : 06 : 361 - info:[AndroidBootstrap][BOOTSTRAPLOG][debug]Gotcommandof type SHUTDOWN 操作流程: 1 2 3 f = open ( 'log.txt' , 'r' ) print (f.read()) f.close() 注意: 在win系统中log文件是utf8保存的,打开文件时open函数是通过操作系统打开的文件,而win操作系统默认的是gbk编码,所以直接打开会乱码,需要f=open('hello',encoding='utf8'),hello文件如果是gbk保存的,则直接打开即可。 2、文件打开模式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 #======================================================================== # #CharacterMeaning # #------------------------------------------------------------------------ # #'r'openforreading(default) # #'w'openforwriting,truncatingthefilefirst # #'x'createanewfileandopenitforwriting # #'a'openforwriting,appendingtotheendofthefileifitexists # #'b'binarymode # #'t'textmode(default) # #'+'openadiskfileforupdating(readingandwriting) # #'U'universalnewlinemode(deprecated) # #======================================================================== 3、文件操作方法 获取文件内容 1 2 3 4 f = open ( 'log.txt' , 'r' ) data = f.read() print (data) f.close() 输出: 2017-03-24 11:25:06:349 - info: [debug] [AndroidBootstrap] Sending command to android: {"cmd":"shutdown"} 2017-03-24 11:25:06:355 - info: [debug] [AndroidBootstrap] Received command result from bootstrap 2017-03-24 11:25:06:356 - info: [debug] [UiAutomator] Shutting down UiAutomator 2017-03-24 11:25:06:357 - info: [debug] [UiAutomator] Moving to state 'stopping' 2017-03-24 11:25:06:360 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"shutdown"} 2017-03-24 11:25:06:361 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command of type SHUTDOWN =========================================================================================== 1 2 3 4 f= open ( 'log.txt' , 'r' ) data1=f. read (10) #读取10个字符。(在这里汉字也只占一个单位) print(data1) f.close() 输出: 2017-03-24 readline和readlines =========================================================================================== 1 2 3 f = open ( 'log.txt' , 'r' ) print (f.readlines()) #返回的是一个列表,注意换行符 f.close() 输出: ['2017-03-24 11:25:06:349 - info: [debug] [AndroidBootstrap] Sending command to android: {"cmd":"shutdown"}\n', '2017-03-24 11:25:06:355 - info: [debug] [AndroidBootstrap] Received command result from bootstrap\n', '2017-03-24 11:25:06:356 - info: [debug] [UiAutomator] Shutting down UiAutomator\n', "2017-03-24 11:25:06:357 - info: [debug] [UiAutomator] Moving to state 'stopping'\n", '2017-03-24 11:25:06:360 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"shutdown"}\n', '2017-03-24 11:25:06:361 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command of type SHUTDOWN'] =========================================================================================== 1 2 3 4 5 f = open ( 'log.txt' , 'r' ) print (f.readline()) #逐行读取 print (f.readline()) print (f.readline(),f.readline(),f.readline()) #逐行读取,每行末尾换行符 f.close() 输出:(注意每行末尾的换行符) 2017-03-24 11:25:06:349 - info: [debug] [AndroidBootstrap] Sending command to android: {"cmd":"shutdown"} 2017-03-24 11:25:06:355 - info: [debug] [AndroidBootstrap] Received command result from bootstrap 2017-03-24 11:25:06:356 - info: [debug] [UiAutomator] Shutting down UiAutomator 2017-03-24 11:25:06:357 - info: [debug] [UiAutomator] Moving to state 'stopping' 2017-03-24 11:25:06:360 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"shutdown"} =========================================================================================== 1 2 3 4 f = open ( 'log.txt' , 'r' ) for line in f.readlines(): print (line.strip()) f.close() 输出: 2017-03-24 11:25:06:349 - info: [debug] [AndroidBootstrap] Sending command to android: {"cmd":"shutdown"} 2017-03-24 11:25:06:355 - info: [debug] [AndroidBootstrap] Received command result from bootstrap 2017-03-24 11:25:06:356 - info: [debug] [UiAutomator] Shutting down UiAutomator 2017-03-24 11:25:06:357 - info: [debug] [UiAutomator] Moving to state 'stopping' 2017-03-24 11:25:06:360 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"shutdown"} 2017-03-24 11:25:06:361 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command of type SHUTDOWN =========================================================================================== 1 2 3 4 5 f = open ( 'log.txt' , 'r' ) print (f) for i in f: print (i.strip()) f.close() 输出: <_io.TextIOWrapper name='log.txt' mode='r' encoding='cp936'> 2017-03-24 11:25:06:349 - info: [debug] [AndroidBootstrap] Sending command to android: {"cmd":"shutdown"} 2017-03-24 11:25:06:355 - info: [debug] [AndroidBootstrap] Received command result from bootstrap 2017-03-24 11:25:06:356 - info: [debug] [UiAutomator] Shutting down UiAutomator 2017-03-24 11:25:06:357 - info: [debug] [UiAutomator] Moving to state 'stopping' 2017-03-24 11:25:06:360 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"shutdown"} 2017-03-24 11:25:06:361 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command of type SHUTDOWN =========================================================================================== 1 2 3 4 5 6 7 8 n = 0 f = open ( 'log.txt' , 'r' ) for i in f: if n = = 3 : i = ' '.join([i.strip(),' this is line 4 ']) print (i.strip()) n + = 1 f.close() 输出: 2017-03-24 11:25:06:349 - info: [debug] [AndroidBootstrap] Sending command to android: {"cmd":"shutdown"} 2017-03-24 11:25:06:355 - info: [debug] [AndroidBootstrap] Received command result from bootstrap 2017-03-24 11:25:06:356 - info: [debug] [UiAutomator] Shutting down UiAutomator 2017-03-24 11:25:06:357 - info: [debug] [UiAutomator] Moving to state 'stopping' this is line 4 2017-03-24 11:25:06:360 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {"cmd":"shutdown"} 2017-03-24 11:25:06:361 - info: [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command of type SHUTDOWN =========================================================================================== tell和seek 1 2 3 4 5 6 f = open ( 'log.txt' , 'r' ) print (f.read( 25 )) print (f.tell()) #取出光标所在位置 print (f.seek( 0 )) #移动光标到指定的位置 print (f.read( 50 )) f.close() 输出: 2017-03-24 11:25:06:349 - 25 0 2017-03-24 11:25:06:349 - info: [debug] [AndroidBo 注意:read后不管是中文字符还是英文字符,都统一算一个单位,read(6),此刻就读了6个中文字符;而seek和tell对于英文字符就是占一个,中文字符占三个,区分与read()的不同. =========================================================================================== flush:同步把数据从缓存移动到磁盘上去 1 2 3 4 5 6 7 8 9 10 11 12 #进度条实例 import sys,time for i in range ( 30 ): sys.stdout.write( "*" ) sys.stdout.flush() time.sleep( 0.1 ) #print的flush import sys,time for i in range ( 30 ): print ( '*' ,end = '',flush = True ) time.sleep( 0.1 ) =========================================================================================== 其他扩展: #truncate():截断数据(不能在r模式下)#在w模式下:先清空,再写,再截断#在a模式下:直接将指定位置后的内容截断 # r+:光标默认在0位置开始写,从0开始覆盖数据# w+:先清空,再写读# a+:光标默认在最后位置 =========================================================================================== with: 为了避免打开文件后忘记关闭,可以通过管理上下文,即: 1 2 with open ( 'log.txt' , 'r' )asf: print (f.readline()) 在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。 1 2 3 4 #with同时管理多个文件对象 with open ( 'log1' , 'r' )asf_read, open ( 'log2' , 'w' )asf_write: for line in f_read: f_write.write(line) 本文转自cqtesting51CTO博客,原文链接:http://blog.51cto.com/cqtesting/1959698 ,如需转载请自行联系原作者

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

openstack学习笔记四 组件框架

组件 nova 对虚拟机管理 cinder 云硬盘 swift 对象存储 容器 glance 镜像 neutron 网络 kestone 验证 所有的组件都得要向keystone进行注册,登记 利用 rebitmq互相通信 环境需要mysql 框架 控制节点 keystone dashboard 计算节点 跑虚拟机的机器 网络节点 为计算节点里的虚拟机提供路由 DHCP 存储节点 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 [root@h1~] #sourcekeystonerc_admin [root@h1~(keystone_admin)] #open open openstack-configopenstack-service opensslopenstack-dbopenstack-status openstackopenstack-keystone-sample-dataopenvt [root@h1~(keystone_admin)] #openstack-status ==Novaservices== openstack-nova-api:active openstack-nova-compute:active openstack-nova-network:inactive(disabledonboot) openstack-nova-scheduler:active openstack-nova-cert:active openstack-nova-conductor:active openstack-nova-console:inactive(disabledonboot) openstack-nova-consoleauth:active openstack-nova-xvpvncproxy:inactive(disabledonboot) ==Glanceservices== openstack-glance-api:active openstack-glance-registry:active ==Keystoneservice== openstack-keystone:inactive(disabledonboot) ==Horizonservice== openstack-dashboard:active ==neutronservices== neutron-server:active neutron-dhcp-agent:active neutron-l3-agent:active neutron-metadata-agent:active neutron-openvswitch-agent:active ==Swiftservices== openstack-swift-proxy:active openstack-swift-account:active openstack-swift-container:active openstack-swift-object:active ==Cinderservices== openstack-cinder-api:active openstack-cinder-scheduler:active openstack-cinder-volume:active openstack-cinder-backup:active ==Ceilometerservices== openstack-ceilometer-api:active openstack-ceilometer-central:active openstack-ceilometer-compute:active openstack-ceilometer-collector:active openstack-ceilometer-alarm-notifier:active openstack-ceilometer-alarm-evaluator:active openstack-ceilometer-notification:active ==Supportservices== mysqld:active(disabledonboot) openvswitch:active dbus:active target:active rabbitmq-server:active memcached:active ==Keystone users == /usr/lib/python2 .7 /site-packages/keystoneclient/shell .py:64:DeprecationWarning:ThekeystoneCLIisdeprecated in favorofpython-openstackclient.ForaPythonlibrary, continue usingpython-keystoneclient. 'python-keystoneclient.' ,DeprecationWarning) /usr/lib/python2 .7 /site-packages/keystoneclient/v2_0/client .py:145:DeprecationWarning:Constructinganinstanceofthekeystoneclient.v2_0.client.Clientclasswithoutasessionisdeprecatedasofthe1.7.0releaseandmayberemoved in the2.0.0release. 'the2.0.0release.' ,DeprecationWarning) /usr/lib/python2 .7 /site-packages/keystoneclient/v2_0/client .py:147:DeprecationWarning:Usingthe 'tenant_name' argumentisdeprecated in version '1.7.0' andwillberemoved in version '2.0.0' ,pleaseusethe 'project_name' argumentinstead super(Client,self).__init__(**kwargs) /usr/lib/python2 .7 /site-packages/debtcollector/renames .py:43:DeprecationWarning:Usingthe 'tenant_id' argumentisdeprecated in version '1.7.0' andwillberemoved in version '2.0.0' ,pleaseusethe 'project_id' argumentinstead return f(*args,**kwargs) /usr/lib/python2 .7 /site-packages/keystoneclient/httpclient .py:376:DeprecationWarning:ConstructinganHTTPClientinstancewithoutusingasessionisdeprecatedasofthe1.7.0releaseandmayberemoved in the2.0.0release. 'the2.0.0release.' ,DeprecationWarning) +----------------------------------+------------+---------+----------------------+ | id |name|enabled|email| +----------------------------------+------------+---------+----------------------+ |1627cc3d61c04f9db9608e9703a01371|admin|True|root@localhost| |04247710cdf34914a7f5b315ab166731|ceilometer|True|ceilometer@localhost| |cb5e12e30a4a4c1dae57255c184b8b30|cinder|True|cinder@localhost| |632fb20205ea4c40988d7d65b2844ff6|glance|True|glance@localhost| |23c4fb48a5a247d68e50c6b74fb6f035|http|True|| |80069f5c8edc454b8038e7f116df4ff5|neutron|True|neutron@localhost| |adbcaaf58d09495988b57be8e82b4e6b|nova|True|nova@localhost| |4f488ff4859e4973afefea6e7872ed83|swift|True|swift@localhost| +----------------------------------+------------+---------+----------------------+ ==Glanceimages== +--------------------------------------+-----------+ |ID|Name| +--------------------------------------+-----------+ |2a0db075-f221-4285-9ff9-38b755a322c1|centos7.2| +--------------------------------------+-----------+ ==Novamanagedservices== +----+------------------+---------------+----------+---------+-------+----------------------------+-----------------+ |Id|Binary|Host|Zone|Status|State|Updated_at|DisabledReason| +----+------------------+---------------+----------+---------+-------+----------------------------+-----------------+ |1|nova-consoleauth|h1.hequan.com|internal|enabled|up|2016-07-05T07:06:34.000000|-| |2|nova-scheduler|h1.hequan.com|internal|enabled|up|2016-07-05T07:06:34.000000|-| |3|nova-conductor|h1.hequan.com|internal|enabled|up|2016-07-05T07:06:34.000000|-| |5|nova-compute|h1.hequan.com|nova|enabled|up|2016-07-05T07:06:34.000000|-| |6|nova-cert|h1.hequan.com|internal|enabled|up|2016-07-05T07:06:34.000000|-| |7|nova-compute|h2.hequan.com|nova|enabled|up|2016-07-05T07:06:34.000000|-| +----+------------------+---------------+----------+---------+-------+----------------------------+-----------------+ ==Novanetworks== +--------------------------------------+---------+------+ |ID|Label|Cidr| +--------------------------------------+---------+------+ |bebbc903-5846-4e8d-9c19-f0248cb6e08d|put-ex|-| |494cbfae-b26d-4e29-859e-35c55f017f19|he_sub2|-| |1f8a8d0c-2e32-4aaa-83d6-3ba52a768292|quan|-| |67d35cd2-3b95-48a7-96b7-6ba1f0eb7d5d|he_sub|-| +--------------------------------------+---------+------+ ==Novainstanceflavors== +----+-----------+-----------+------+-----------+------+-------+-------------+-----------+ |ID|Name|Memory_MB|Disk|Ephemeral|Swap|VCPUs|RXTX_Factor|Is_Public| +----+-----------+-----------+------+-----------+------+-------+-------------+-----------+ |1|m1.tiny|512|1|0||1|1.0|True| |2|m1.small|2048|20|0||1|1.0|True| |3|m1.medium|4096|40|0||2|1.0|True| |4|m1.large|8192|80|0||4|1.0|True| |5|m1.xlarge|16384|160|0||8|1.0|True| +----+-----------+-----------+------+-----------+------+-------+-------------+-----------+ ==Novainstances== +--------------------------------------+------+----------------------------------+--------+------------+-------------+-----------------------------------+ |ID|Name|TenantID|Status|TaskState|PowerState|Networks| +--------------------------------------+------+----------------------------------+--------+------------+-------------+-----------------------------------+ |95311ed2-6091-4ce7-a2be-caab8e2760ce|1|43986fb013804aa0a04ca277e4d0e69c|ACTIVE|-|Running|quan=192.168.10.12,192.168.2.104| +--------------------------------------+------+------ 本文转自 295631788 51CTO博客,原文链接:http://blog.51cto.com/hequan/1795980,如需转载请自行联系原作者

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

[Docker]Docker快速上手学习笔记

0. 学习的一些疑问 如何热更新镜像(images)?(你可以快速启动或者销毁容器。这种时间几乎是实时的) 如何热更新游戏服? 好处在于各个应用之间环境相互独立,即使某一个容器崩溃也不会影响到其它容器; 每个容器使用端口如何维护?(方法1写在Dockerfile里面,不灵活;方法2在run的时候-p指定); 那这样的话,会存在好多linux用户,相当于每一个容器就要维护一个物理机(虚拟); 需要一套工具来管理维护镜像、容器的操作和状态; 目前主流使用docker都是应用到哪些场景中? 1. docker的二个软件 Docker: 开源的容器虚拟化平台; Docker Hub: Software-as-a-Service平台,用来共享和管理docker容器。 2. docker的三大模块 Docker images.(镜像) Docker registries.(仓库) Docker container.(容器) 3. 常用命令 3.1. 常用镜像命令 docker image(查看镜像信息) docker build(创建镜像) Dockerfile '#注释' FROM 基于哪个镜像为基础 MAINTAINER 维护者信息 RUN 运行指令 ADD 复制本地文件到镜像 EXPOSE 设置开放端口 CMD 容器启动后允许的程序 WORKDIR 切换工作目录 -t 添加tag build后面需要接路径 3.2. 少用镜像命令 docker pull(获取镜像) docker push(上传镜像) docker search(搜索镜像) -s N 只搜索指定星级以上的镜像 docker rmi(删除镜像) docker tag [id] [new name:tag] (修改tag) docker save(保存镜像) docker load(加载镜像) docker load --input xxx.tar docker load < xxx.tar load与import的区别,镜像是完整的与快照是丢弃历史记录和元数据信息的 docker rmi $(docker images -q -f "dangling=true")(清理所有未打过标签的本地镜像) 3.3. 常用容器命令 docker run([下载镜像并]启动容器) -t 分配一个伪终端 -i 打开标准输入 -d 后台运行 -v创建并挂载数据卷(可有多个) --volumes-from 挂载数据卷(可有多个) -p 指定映射端口 (ip:port:containerPort/udp|ip::containerPort|port:containerPort) -P 随机映射端口 --name 自定义容器名字 --rm 终止后立即删除容器 --link:容器互联 docker start(启动已终止容器) docker stop(终止容器) nsenter(进入容器)(推荐) PID=$(docker inspect --format "{{ .State.Pid }}") nsenter --target $PID --mount --uts --ipc --net --pid 3.4. 少用容器命令 docker commit(提交容器) -m --massage="" 提交信息 -a --author="" 作者信息 -p --pause=true 提交时暂停容器运行 docker attach(进入容器) docker ps(查看正在运行的容器) -a 查看已终止 docker logs [container ID or NAMES] 查看(后台)运行日志 docker export(导出容器为文件) docker export> xxx.tar docker import(文件快照导入镜像) cat xxx.tar | docker import - test/name:v1.0 docker importhttp://xxx.tgztest/name docker rm(删除容器) 默认不会删除运行中的容器 docker rm $(docker ps -a -q) 清理所有处于终止状态的容器 -v 同时删除数据卷 4. 安装 4.1. 在CentOS7中安装 curl -sSL https://get.docker.com/ | sh //下载官服脚本按照 chkconfig docker on //设置开机自动启动 4.2. 在CentOS6中安装 4.2.1. 添加yum软件源 tee /etc/yum.repo.d/docker.repo << 'EOF' [dockerrepo] name=Docker Repository baseurl=https://yum.dockerproject.org/repo/main/centos/$releasever/ enabled=1 gpgcheck=1 gpgkey=https://yum.dockerproject.org/gpg EOF 4.2.2. 安装docker yum update yum install -y docker-engine 4.2.3. No module named yum 如果在执行yum update的时候出现了No module named yum错误,可能是存在与yum不对应的python版本引起。可以通过修改yum和yum-updatest的执行脚本(/usr/bin/yum和/usr/bin/yum-updatest)的注释来指定python版本。譬如: #!/usr/bin/python 修改为 #!/usr/bin/python2.6 5. 基础环境 可以下载bashrc_docker文件,加载到环境.bashrc中,其可以提供一些方便的命令用于做一些比较复杂的过程。 .bashrc_docker(https://raw.githubusercontent.com/yeasy/docker_practice/master/_local/.bashrc_docker) 定义了以下命令 - docker-pid(获取容器pid) - docker-enter(进入容器) 下载和加载到linux环境中: wget -P ~ https://raw.githubusercontent.com/yeasy/docker_practice/master/_local/.bashrc_docker echo "[ -f ~/.bashrc_docker ] && . ~/.bashrc_docker" >> ~/.bashrc;source ~/.bashrc 6. 仓库 6.1. 私有仓库 官服提供了一个docker-registry镜像来供私有仓库的搭建。 docker run -d -p 2010:5000 registry vi /etc/docker/daemon.json {"insecure-registries":["myregistry.example.com:5000"]} cul http://x.x.x.x:2010/v2/linerl/tags/list API文档:https://github.com/docker/distribution/blob/master/docs/spec/api.md 7. 学习后的一些结论 本身是虚拟机技术实现的服务器大多数带有随时可扩展升级的性质,没有资源分配的需求,没有必要用到docker; docker适合在做负载均衡的短链接的web服务上面,应用场景都是以镜像、容器为操作单位的最佳; 如果有业务可以做到镜像、容器来维护就可以的,说明这个业务就很合适使用docker。 以上只是本人刚开始学习的一些理解,当然docker的能力我还远远没理解到,适合的场景肯定还有很多。目前的记录只是为了以后查阅和学习巩固。 本文转自 Ron Ngai 博客园博客,原文链接:http://www.cnblogs.com/rond/p/6020564.html,如需转载请自行联系原作者

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

操作主机角色笔记

操作主机角色 1架构主机 架构主机控制整个林的架构的全部更新 手工安装 运行——regsvr32 schmmgmt.dll 运行——mmc——文件——添加或删除管理单元——Active Directory架构 2域命名主机 域命名主机控制林中域的添加或删除,可以防止林中的域名重复. 管理工具——Active Directory域和信任关系 3PDC仿真主机 管理来自客户端的密码更改 最小化密码变化的复制等待时间 管理工具——Active Directory用户和计算机——右击域名——操作主机——PDC 4RID主机 RID主机将相对ID(RID)序列分配给域中每个域控制器 管理工具——Active Directory用户和计算机——右击域名——操作主机——RID 5基础结构主机 基础结构主机负责更新从它所在域中的对象到其他域中对象的引用 转移操作主机角色 转移架构主机 Active Directory架构——更改Active Directory域控制器——更改目录服务器——第2台域控制器 Active Directory架构——操作主机——更改 转移RID、PDC、基础结构主机 Active Directory用户和计算机——更改Active Directory域控制器——更改目录服务器——第2台域控制器 Active Directory用户和计算机——操作主机——RID——更改 Active Directory用户和计算机——操作主机——PDC——更改 Active Directory用户和计算机——操作主机——基础结构主机——更改 转移域命名主机 Active Directory域和信任关系——更改Active Directory域控制器——更改目录服务器——第2台域控制器 Active Directory域和信任关系——操作主机——更改 使用命令行转移操作主机 1cmd 2ntdsutil 3roles 4connection 5connect to server dc02.benet.com(目标域控制器) 6quit 帮助命令help 7transferPDC 8transferRID master 9transfer infrastructure master 基础结构 10transfer domain naming master域命名 11transfer schema master 架构 使用命令行占用操作主机 1cmd 2ntdsutil 3roles 4connection 5connect to server dc02.benet.com(目标域控制器) 6quit 帮助命令help 7seizePDC 8seizeRID master 9seize infrastructure master 基础结构 10seize domain naming master 域命名 11seize schema master 架构 在占用角色时,一定要保证DNS能正确解析域名 授权还原 非授权还原 本文转自 jin626889 51CTO博客,原文链接:http://blog.51cto.com/zuoshou/1291883,如需转载请自行联系原作者

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

Android笔记:定时提醒、闹钟实现

android要实现定时的功能那肯定就要用到闹铃相关的技术, 那么android闹铃实现是基于 AlarmManager 这个类的,首先我们来看一下它的几个主要的方法。 两个核心的方法 : 1 private final IAlarmManagermService; 1 2 3 4 5 6 public void set( int type, long triggerAtMillis,PendingIntentoperation){ try { mService.set(type,triggerAtMillis,operation); } catch (RemoteExceptionex){ } } 和 1 2 3 4 5 6 7 public void setRepeating( int type, long triggerAtMillis, long intervalMillis,PendingIntentoperation){ try { mService.setRepeating(type,triggerAtMillis,intervalMillis,operation); } catch (RemoteExceptionex){ } } 第一个方法主要功能是注册一个比较简单的闹铃,第二个方法是注册一个重复的闹铃,这里重复的意思是指:设置5s, 那么每隔5s会执行一次 。 我们看到这里具体的实现都是基于IAlarmManager的,而IAlarmManager是一个aidl(Android Interface definition language),具体的就不详细介绍了,大家有兴趣的可以自己研究一下。 下面我来看下set(int type, long triggerAtMillis, PendingIntent operation)方法是如何调用的: 1 2 3 4 5 6 7 8 9 10 11 //进行闹铃注册 Intentintent= new Intent(MainActivity. this ,AlarmReceiver. class ); PendingIntentsender=PendingIntent.getBroadcast(MainActivity. this , 0 ,intent, 0 ); //过10s执行这个闹铃 Calendarcalendar=Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.SECOND, 10 ); AlarmManagermanager=(AlarmManager)getSystemService(ALARM_SERVICE); manager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),sender); 看一下AlarmReceiver 的源码: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 /** * *@ClassName:AlarmReceiver *@Description:闹铃时间到了会进入这个广播,这个时候可以做一些该做的业务。 *@authorHuHood *@date2013-11-25下午4:44:30 * */ public class AlarmReceiver extends BroadcastReceiver{ @Override public void onReceive(Contextcontext,Intentintent){ Toast.makeText(context, "闹铃响了,可以做点事情了~~" ,Toast.LENGTH_LONG).show(); } } 还有别忘了,AndroidManifest.xml中需要加入: 1 <receiverandroid:name= "com.example.alarmmanagerdemo.AlarmReceiver" android:process= ":remote" > 运行之后,过10s 弹出 "闹铃响了,可以做点事情了~~", 说明成功了。 ok,这个结果肯定不是我们想要的,我们想要的功能是每天定时提醒的功能,那么需要基于 setRepeating(int type, long triggerAtMillis,long intervalMillis, PendingIntent operation) 这个方法来实现,代码如下: 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 Intentintent= new Intent(MainActivity. this ,AlarmReceiver. class ); PendingIntentsender=PendingIntent.getBroadcast(MainActivity. this , 0 ,intent, 0 ); long firstTime=SystemClock.elapsedRealtime(); //开机之后到现在的运行时间(包括睡眠时间) long systemTime=System.currentTimeMillis(); Calendarcalendar=Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); //这里时区需要设置一下,不然会有8个小时的时间差 calendar.setTimeZone(TimeZone.getTimeZone( "GMT+8" )); calendar.set(Calendar.MINUTE,mMinute); calendar.set(Calendar.HOUR_OF_DAY,mHour); calendar.set(Calendar.SECOND, 0 ); calendar.set(Calendar.MILLISECOND, 0 ); //选择的定时时间 long selectTime=calendar.getTimeInMillis(); //如果当前时间大于设置的时间,那么就从第二天的设定时间开始 if (systemTime>selectTime){ Toast.makeText(MainActivity. this , "设置的时间小于当前时间" ,Toast.LENGTH_SHORT).show(); calendar.add(Calendar.DAY_OF_MONTH, 1 ); selectTime=calendar.getTimeInMillis(); } //计算现在时间到设定时间的时间差 long time=selectTime-systemTime; firstTime+=time; //进行闹铃注册 AlarmManagermanager=(AlarmManager)getSystemService(ALARM_SERVICE); manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,DAY,sender); Log.i(TAG, "time====" +time+ ",selectTime=====" +selectTime+ ",systemTime====" +systemTime+ ",firstTime===" +firstTime); Toast.makeText(MainActivity. this , "设置重复闹铃成功!" ,Toast.LENGTH_LONG).show(); 以上的思路大致是这样的,首先根据设置的时间,算出当前时间离设置时间的时间差,加上这个时间差,我们就知道第一次提醒的时间,然后再设定重复的时间间隔,我们这里设置1天就可以了。现在解释一下setRepeating中第一个参数:AlarmManager.RTC,硬件闹钟,不唤醒手机(也可能是其它设备)休眠;当手机休眠时不发射闹钟。AlarmManager.RTC_WAKEUP,硬件闹钟,当闹钟发躰时唤醒手机休眠;AlarmManager.ELAPSED_REALTIME,真实时间流逝闹钟,不唤醒手机休眠;当手机休眠时不发射闹钟。AlarmManager.ELAPSED_REALTIME_WAKEUP,真实时间流逝闹钟,当闹钟发躰时唤醒手机休眠;RTC闹钟和ELAPSED_REALTIME最大的差别就是前者可以通过修改手机时间触发闹钟事件,后者要通过真实时间的流逝,即使在休眠状态,时间也会被计算。以上摘自:http://hualang.iteye.com/blog/1304054还有,我们这里是调用广播的形式来实现的,也可以用service的方式来进行实现,只要把PendingIntent改动一下即可,相关代码:PendingIntent.getService(MainActivity.this, 0,new Intent(MainActivity.this,AlarmService.class), 0);其他的均相同。完整Demo下载:http://download.csdn.net/detail/jakend/6612033 本文转自 glblong 51CTO博客,原文链接:http://blog.51cto.com/glblong/1679698,如需转载请自行联系原作者

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

Android笔记:Intent的Component使用

使用components有两种方式: 1 2 3 ComponentNamecom= new ComponentName(MainActivity. this ,MyActivity. class ); //first ComponentNamecom= new ComponentName( "com.example.testcomponent" , "com.example.testcomponent.MyActivity" ); //second 第二种方式的第二个参数必须写全包名,不然会报错的。 一样的,主Activity中: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 button.setOnClickListener( new Button.OnClickListener() { @Override public void onClick(Viewarg0) { //TODOAuto-generatedmethodstub Intentintent= new Intent(); ComponentNamecom= new ComponentName( "com.example.testcomponent" , "com.example.testcomponent.MyActivity" ); intent.setComponent(com); Strings= "ThisisaTest." ; intent.putExtra( "id" ,s); startActivity(intent); } }); 在目标Ativity中获取数据和上面是一样的,但是,在目标Activity中就可以获取到源目标,知道是从哪儿传递过来的: 1 2 3 4 5 6 7 8 text=(TextView)findViewById(R.id.text); Intentintent=getIntent(); Stringstr=intent.getStringExtra( "id" ); ComponentNamecom=intent.getComponent(); StringpkgName=com.getPackageName(); StringclassName=com.getClassName(); text.setText(str+ "\n" +pkgName+ "\n" +className); 本文转自 glblong 51CTO博客,原文链接:http://blog.51cto.com/glblong/1611832,如需转载请自行联系原作者

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

CCNP-CIT中文笔记

故障处理方法 一、网络的复杂性 一般网络包括路由、拨号、交换、视频、WAN(ISDN、帧中继、ATM、…)、LAN、VLAN、… 二、故障处理模型 1、 界定问题(Define the Problem) 详细而精确地描述故障的症状和潜在的原因 2、 收集详细信息(Gather Facts) 信息来源:关键用户、网络管理系统、路由器/交换机 1) 识别症状: 2) 重现故障:校验故障依然存在 3) 调查故障频率: 4) 确定故障的范围:有三种方法建立故障范围 Ø由外到内故障处理(Outside-In Troubleshooting):通常适用于有多个主机不能连接到一台服务器或服务器集 Ø由内到外故障处理(Inside-Out Troubleshooting): Ø半分故障处理(Divide-by-Half Troubleshooting) 3、 考虑可能情形(Consider Possibilities) 考虑引起故障的可能原因 4、 建立一份行动计划(Create the Action Plan) 5、 部署行动计划(Implement the Action Plan) 用于纠正网络故障原因。从最象故障源处,想出处理方法 每完成一个步骤,检查故障是否解决 6、 观察行动计划执行结果(Observe Results) 7、 如有行动计划不能解决问题,重复上述过程(Iterate as Needed) 三、记录所做修改 在通过行动计划解决问题后,建议把记录作为故障处理的一部分,记录所有的配置修改。 第2章 网络文档 一、网络基线 解决网络问题的最简单途径是把当前配置和以前的配置相比较。 基线文档由不同的网络和系统文档组成,它包括: Ø网络配置表 Ø网络拓扑图 ØES网络配置表 ØES网络拓扑图 创建网络的注意事项: 1) 确定文档覆盖的范围; 2) 保持一致:收集网络中所有设备的相同信息; 3) 明确目标:了解文档的用途; 4) 文档易于使用和访问; 5) 及时维护更新文档。 二、网络配置表 网络配置表的通常目标是提供网络中使用的硬件和软件组成的列表,其组成有: 分级 项目 杂项信息 设备名、设备型号、CPU类型、FLASH、DRAM、接口描述、用户名口令 第1层 介质类型、速率、双工模式、接口号、连接插座或端口 第2层 MAC地址、STP状态、STP根桥、速端口信息、VLAN、Etherchannel配置、封装、中继状态、接口类型、端口安全、VTP状态、VTP模式 第3层 IP地址、IPX地址、HSRP地址、子网掩码、路由协议、ACL、隧道信息、环路接口 在多数情形下,存储这些信息的最佳方式是电子表格或数据库,电子表格用于较小的网络,数据库用于较大的网络。 三、网络拓扑图 网络拓扑图是图示网络的各组成部分之间如何在逻辑上和物理上相互连接。 1、网络拓扑图的组成 分级 项目 杂项信息 设备名、设备型号、设置间连接、接口描述 第1层 介质类型、接口号 第2层 MAC地址、VLAN、封装、中继状态、接口类型、DLCI 第3层 IP地址、子网掩码、路由协议 对于大型的网络,可以制作多个网络拓扑图,每个网络拓扑图反映一个分离的部分。 2、建立网络拓扑图 四、发现网络配置信息 1、收集路由器和第3层交换机网络配置信息 show version ;显示设备型号、Flash、DRAM、IOS版本 show ip interface brief ;显示接口简要信息(类型、状态、协议状态、IP地址) show interface e0/0 ;显示某接口详细信息(MAC、IP、MASK、…) show ip protocols ;显示IP路由协议信息 show ip interface e0/0 ;显示接口的IP协议信息(状态、IP地址、ACL、…) 2、收集交换机配置信息 交换机网络配置表包含的信息:设备名、型号、位置、Flash、DRAM、CATOS版本、管理地址、VTP域、VTP模式、端口号、端口速率、端口双工、VLAN、STP状态、速端口状态、中继状态、… show version ;显示IOS或CATOS版本、DRAM、Flash show vtp domain ;(CatOS)显示VTP域和VTP模式 show vtp status ;(IOS) show interface ;(CatOS)显示管理接口信息 show port ;(CatOS)显示每个端口的简要信息(号、VLAN、双工、…) show interface ;(IOS) show trunk ;(CatOS)显示中继信息(模式、封装、允许端口、剪裁、…) show interface trunk ;(IOS) show spantree 45 ;(CatOS)显示端口的STP模式、类型、状态、速端口、…) show spanning-tree 45 ;(IOS) 3、发现相邻CISCO设备的信息 CDP(Cisco Discovery Protocol)是CISCO的专用协议,用于识别直接相邻的CISCO设备信息,CDP工作在第2层。 Show cdp neighbor ;显示相邻CISCO设备的简要信息(ID、相邻接口、平台、…) Show cdp neighbor detail;显示相邻CISCO设备的详细信息(包含第3层信息) 五、创建网络文档的过程 1、 LOGIN ;登录到设备进入特权模式。 2、 接口发现 ;发现关于设备的所需信息 3、 Document ;在网络配置表中记录发现的信息。 4、 Diagram ;从网络配置表传输所需信息到网络拓扑图 5、 设备发现 ;判断是否有相邻设备没有记录文档。 本文转自gauyanm 51CTO博客,原文链接:http://blog.51cto.com/gauyanm/229048,如需转载请自行联系原作者

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

Android开发学习笔记:浅谈Toast

一.Toast的简介 Toast是Android中一种提供给用户简短信息的视图,该视图已浮于应用程序之上的形式呈现给用户。因为它并不获得焦点,即使用户正在输入什么也不会受到影响。它的目标是尽可能已不显眼的方式,使用户看到你提供的信息。显示的时间是有限制的,过一段时间后会自动消失,不过Toast本身可以控制显示时间的长短。 二.Toast的常用方法 int getDuration() 返回Toast视图显示持续的时间. int getGravity() 取得提示信息在屏幕上显示的位置. float getHorizontalMargin() 返回横向栏外空白 float getVerticalMargin() 返回纵向栏外空白. View getView() 返回View对象. int getXOffset() 返回相对于参照位置的横向偏移像素量。 int getYOffset() 返回相对于参照位置的纵向偏移像素量 staticToast makeText(Contextcontext, int resId, int duration) 生成一个从资源中取得的包含文本视图的标准Toast对象。 context使用的上下文。通常是你的Application或Activity对象 resId要使用的字符串资源ID,可以是已格式化文本。 duration该信息的存续期间。值为LENGTH_SHORT或LENGTH_LONG staticToast makeText(Contextcontext,CharSequencetext, int duration) 生成一个包含文本视图的标准Toast对象. void setDuration(int duration) 设置Toast视图显示持续的时间,LENGTH_LONG表示持续时间较长,LENGTH_SHORT表示持续时间较短 void setGravity(int gravity, int xOffset, int yOffset) 设置提示信息在屏幕上的显示位置.(自定义Toast的显示位置,例如toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0)可以把Toast定位在左上角。Toast提示的位置xOffset:大于0向右移,小于0向左移) void setMargin(float horizontalMargin, float verticalMargin) 设置视图的栏外空白. horizontalMargin容器的边缘与提示信息的横向空白(与容器宽度的比) verticalMargin容器的边缘与提示信息的纵向空白(与容器高度的比)。 void setText(int resId) 更新之前通过makeText()方法生成的Toast对象的文本内容.resId为Toast指定的新的字符串资源ID。 void setText(CharSequences) 更新之前通过makeText()方法生成的Toast对象的文本内容. s为Toast指定的新的文本 void setView(Viewview) 设置要显示的View.注意这个方法可以显示自定义的toast视图,可以包含图像,文字等等。是比较常用的方法 void show() 按照指定的存续期间显示提示信息 三.Toast的不同显示样式 效果图(有五种不同的Toast显示样式): main.xml <?xmlversion="1.0"encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/btn_1" android:text="@string/btn1" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_2" android:text="@string/btn2" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_3" android:text="@string/btn3" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_4" android:text="@string/btn4" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_5" android:text="@string/btn5" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> toast.xml <?xmlversion="1.0"encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp" android:background="#708090" > <ImageView android:id="@+id/img" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="带图片文字的Toast" /> </LinearLayout> strings.xml <?xmlversion="1.0"encoding="utf-8"?> <resources> <stringname="hello">HelloToast!</string> <stringname="app_name">ToastDemo</string> <stringname="btn1">系统默认的Toast</string> <stringname="btn2">自定义位置的Toast</string> <stringname="btn3">带只有图片的Toast</string> <stringname="btn4">有图有文字的Toast</string> <stringname="btn5">自定义布局的Toast</string> </resources> ToastDemoActivity.java packagecom.android.toast.activity; importandroid.app.Activity; importandroid.content.Context; importandroid.os.Bundle; importandroid.view.Gravity; importandroid.view.LayoutInflater; importandroid.view.View; importandroid.view.View.OnClickListener; importandroid.widget.Button; importandroid.widget.ImageView; importandroid.widget.LinearLayout; importandroid.widget.Toast; publicclassToastDemoActivityextendsActivity{ privateButtonbtn_1,btn_2,btn_3,btn_4,btn_5; privateToasttoast=null; @Override protectedvoidonCreate(BundlesavedInstanceState){ //TODOAuto-generatedmethodstub super.onCreate(savedInstanceState); setContentView(R.layout.main); btn_1=(Button)findViewById(R.id.btn_1); btn_2=(Button)findViewById(R.id.btn_2); btn_3=(Button)findViewById(R.id.btn_3); btn_4=(Button)findViewById(R.id.btn_4); btn_5=(Button)findViewById(R.id.btn_5); btn_1.setOnClickListener(newButtonClick()); btn_2.setOnClickListener(newButtonClick()); btn_3.setOnClickListener(newButtonClick()); btn_4.setOnClickListener(newButtonClick()); btn_5.setOnClickListener(newButtonClick()); } classButtonClickimplementsOnClickListener{ @Override publicvoidonClick(Viewv){ //TODOAuto-generatedmethodstub switch(v.getId()){ caseR.id.btn_1: toast.makeText(ToastDemoActivity.this,"默认的Toast显示",Toast.LENGTH_LONG).show(); break; caseR.id.btn_2: //getApplicationContext()得到程序当前的默认Context toast=Toast.makeText(getApplicationContext(),"自定义位置的Toast显示", Toast.LENGTH_LONG); //设置Toast的位置 toast.setGravity(Gravity.CENTER,toast.getXOffset()/2,toast.getYOffset()/2); toast.show(); break; caseR.id.btn_3: toast=Toast.makeText(getApplicationContext(),"只有图片的Toast显示", Toast.LENGTH_LONG); ImageViewimg=newImageView(ToastDemoActivity.this); img.setImageResource(R.drawable.android); toast.setView(img); toast.show(); break; caseR.id.btn_4: toast=Toast.makeText(getApplicationContext(),"有图有字的Toast",Toast.LENGTH_LONG); LinearLayoutlayout=(LinearLayout)toast.getView(); ImageViewimg1=newImageView(getApplicationContext()); img1.setImageResource(R.drawable.android); layout.addView(img1,0); toast.show(); break; caseR.id.btn_5: //将一个xml布局转换成一个view对象 LayoutInflaterinflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); Viewview=inflater.inflate(R.layout.toast,null); Toasttoast=newToast(getApplicationContext()); //在view中查找查找ImageView控件 ImageViewimage=(ImageView)view.findViewById(R.id.img); image.setImageResource(R.drawable.android); toast.setView(view); toast.show(); break; default: break; } } } } 本文转自 lingdududu 51CTO博客,原文链接: http://blog.51cto.com/liangruijun/638913

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

Android学习笔记(四)Android 组件

EditText和setOnKeyListener事件实现文本处理 package com.example.test12; import android.os.Bundle; import android.app.Activity; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.support.v4.app.NavUtils; public class MainActivity extends Activity { private TextView text; private EditText edit; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text=(TextView)findViewById(R.id.textView1); edit=(EditText)findViewById(R.id.editText1); edit.setOnKeyListener(editlistener); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } View.OnKeyListener editlistener=new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // TODO Auto-generated method stub text.setText(edit.getText()); return false; } }; } 带背景图片的按钮 使用ImageButton来实现带背景图片的按钮。 OnFocusChangeListener焦点变化监听 ImageButton.setImageResourse()用来指定按钮的背景颜色 package com.example.test13; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; import android.support.v4.app.NavUtils; public class MainActivity extends Activity { private TextView tv; private ImageButton ibt; private Button bt; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv=(TextView)findViewById(R.id.textView1); ibt=(ImageButton)findViewById(R.id.imageButton1); bt=(Button)findViewById(R.id.button1); ibt.setOnFocusChangeListener(focusChange); bt.setOnClickListener(clicked); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } View.OnFocusChangeListener focusChange=new View.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { // TODO Auto-generated method stub if(hasFocus){ tv.setText("Got Focus!!!"); ibt.setImageResource(R.drawable.image1); } else{ tv.setText("Lost Focus!!!"); ibt.setImageResource(R.drawable.image2); } } }; View.OnClickListener clicked=new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub if(tv.getText()=="Got Focus!!!"){ tv.setText("Lost Focus!!!"); ibt.setImageResource(R.drawable.image2); } else{ tv.setText("Got Focus!!!"); ibt.setImageResource(R.drawable.image1); } } }; } Toast实现提示条(Toast总结) Toast.makeText()让文字显示与Toast对象中,会显示一段时间后自动消失。 Toast.makeText( MainActivity.this, "这个是Toast.makeText提示", Toast.LENGTH_LONG).show(); CheckBox和RadioButton复选框 通过CheckBox.setOnCheckedChangeLister来监听CheckBox 相框的实现 可以通过ImageButton和ImageView来实现,推荐ImageButton,它可以直接添加点击监听 java.io.File实现文件搜索 在JAVA I/O的API中,提供了java.io.File对象。 package com.example.test14; import java.io.File; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import android.support.v4.app.NavUtils; public class MainActivity extends Activity { private TextView result; private Button bt; private EditText edit; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); result=(TextView)findViewById(R.id.textView2); bt=(Button)findViewById(R.id.button1); edit=(EditText)findViewById(R.id.editText1); bt.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub String keyword=edit.getText().toString(); if(keyword.equals("")){ Toast.makeText( MainActivity.this, "不能为空!", Toast.LENGTH_LONG).show(); } else{ result.setText(searchFile(keyword)); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } private String searchFile(String Keyword){ String searchResult=""; File[] files=new File("/").listFiles(); for(File f:files){ if(f.getName().indexOf(Keyword)>=0) searchResult+=f.getPath()+"\n";// \n换行 } if(searchResult.equals("")) searchResult="找不到文件!!!!"; return searchResult; } } 本文转自cococo点点博客园博客,原文链接:http://www.cnblogs.com/coder2012/archive/2013/05/17/3083991.html,如需转载请自行联系原作者

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

Android开发学习笔记:浅谈ToggleButton

ToggleButton(开关按钮)是Android系统中比较简单的一个组件,是一个具有选中和未选择状态双状态的按钮,并且需要为不同的状态设置不同的显示文本。 ToggleButton常用的XML属性 属性名称 描述 android:disabledAlpha 设置按钮在禁用时透明度。 android:textOff 未选中时按钮的文本 android:textOn 选中时按钮的文本 下面是具体的例子: 第一个例子是通过Toast显示ToggleButton不同的状态时的信息 MainActivity.java packagecom.android.togglebutton; importandroid.app.Activity; importandroid.os.Bundle; importandroid.view.View; importandroid.view.View.OnClickListener; importandroid.widget.Toast; importandroid.widget.ToggleButton; publicclassMainActivityextendsActivity{ //声明ToggleButton privateToggleButtontogglebutton; @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); togglebutton=(ToggleButton)findViewById(R.id.togglebutton); togglebutton.setOnClickListener(newOnClickListener(){ publicvoidonClick(Viewv){ //当按钮第一次被点击时候响应的事件 if(togglebutton.isChecked()){ Toast.makeText(MainActivity.this,"你喜欢球类运动",Toast.LENGTH_SHORT).show(); } //当按钮再次被点击时候响应的事件 else{ Toast.makeText(MainActivity.this,"你不喜欢球类运动",Toast.LENGTH_SHORT).show(); } } }); } } main.xml <?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <ToggleButton android:id="@+id/togglebutton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOn="喜欢" android:textOff="不喜欢" /> </LinearLayout> strings.xml <?xmlversion="1.0"encoding="utf-8"?> <resources> <stringname="hello">你喜不喜欢球类运动?</string> <stringname="app_name">测试ToggleButton</string> </resources> 效果图: 第二个例子通过图片的变化显示ToggleButton不同的状态时的图片 MainActivity.java packagecom.android.togglebutton; importandroid.app.Activity; importandroid.os.Bundle; importandroid.widget.CompoundButton; importandroid.widget.CompoundButton.OnCheckedChangeListener; importandroid.widget.ImageView; importandroid.widget.ToggleButton; publicclassMainActivityextendsActivity{ //声明ImageView,ToggleButton privateImageViewimageView; privateToggleButtontoggleButton; @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); //通过findViewById获得ImageView,ToggleButton imageView=(ImageView)findViewById(R.id.imageView); toggleButton=(ToggleButton)findViewById(R.id.toggleButton); toggleButton.setOnCheckedChangeListener(newOnCheckedChangeListener(){ publicvoidonCheckedChanged(CompoundButtonbuttonView,booleanisChecked){ toggleButton.setChecked(isChecked); //使用三目运算符来响应按钮变换的事件 imageView.setImageResource(isChecked?R.drawable.pic_on:R.drawable.pic_off); } }); } } main.xml <?xmlversion="1.0"encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/pic_off" android:layout_gravity="center_horizontal" /> <ToggleButton android:id="@+id/toggleButton" android:layout_width="130dip" android:layout_height="wrap_content" android:textOn="开灯" android:textOff="关灯" android:layout_gravity="center_horizontal" /> </LinearLayout> 效果图: 本文转自 lingdududu 51CTO博客,原文链接:http://blog.51cto.com/liangruijun/655014

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

学习笔记-安装ELK5

ELK日志平台是一个完整的日志分析系统,有三个开源工具构建组成,分别是:Elasticsearch、Logstash和Kibana。Elasticsearch用于数据分析和深度搜索;Logstash作用是从其他服务器上传输和转发日志,对其集中管理,进行分析;Kibana则是提供了强大的UI展示,将数据可视化。 安装ELK日志平台 ELK基础环境需要java环境,官网要求5.x版本要大于java8。而且安装方式多样化,支持zip、tar.gz、rpm包、deb包、window环境还有docker环境。根据自己喜好选择吧。 我选择的是yum安装,简单方便,系统要求的话没有辣么严格,官网说yum安装方式不再支持centos5.x系列了,非要用centos5.x就去使用tar.gz包吧,官网有具体方法,不再复述。yum安装方式centos6.x和centos7.x都可以,但是我推荐用centos7.x安装,不知道为啥,感觉centos7.x支持更好,centos6.x装完经常会出问题。 还有一点需要说下就是,ELK各个组件版本要一致,官网要求的! 在一个就是安装顺序,为的是确保每个组件相互调用时都能正常运行: 1、Elasticsearch X-Pack for Elasticsearch Kibana X-Pack for Kibana LogstashBeatsElasticsearch Hadoop 安装Elasticsearch 1、导入Elasticsearch安装包PGP Key 1 2 rpm-- import https: //artifacts .elastic.co /GPG-KEY-elasticsearch 2、创建yum源 1 2 3 4 5 6 7 8 9 10 [root@localhost~] #cat>>/etc/yum.repos.d/elasticsearch.repo<<EOF >[elasticsearch-5.x] >name=Elasticsearchrepository for 5.xpackages >baseurl=https: //artifacts .elastic.co /packages/5 .x /yum >gpgcheck=1 >gpgkey=https: //artifacts .elastic.co /GPG-KEY-elasticsearch >enabled=1 >autorefresh=1 > type =rpm-md >EOF 3、安装、启动Elasticsearch进程并开机启动 1 2 3 4 [wangpeng@localhost~]$ sudo yum install elasticsearch [wangpeng@localhost~]$ sudo /bin/systemctl daemon-reload [wangpeng@localhost~]$ sudo /bin/systemctl enable elasticsearch.service [wangpeng@localhost~]$ sudo systemctlstartelasticsearch.service 4、检查Elasticsearch是否已经启动 查看9200、9300是否已经启动 1 2 3 4 5 6 7 8 9 10 11 12 13 14 [wangpeng@localhost~]$curlhttp: //localhost :9200 { "name" : "F5Mw8Pp" , "cluster_name" : "elasticsearch" , "cluster_uuid" : "zVEeXtPNTaeH-TKah7Buzw" , "version" :{ "number" : "5.4.0" , "build_hash" : "780f8c4" , "build_date" : "2017-04-28T17:43:27.229Z" , "build_snapshot" : false , "lucene_version" : "6.5.0" }, "tagline" : "YouKnow,forSearch" } 5、配置Elasticsearch rpm包配置文件在/etc/elasticsearch下面的elasticsearch.yml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 vim /etc/elasticsearch/elasticsearch .yml cluster.name:elasticsearch- test node.name:node-1 path.data: /var/lib/elasticsearch path.logs: /var/log/elasticsearch network.host:0.0.0.0 [wangpeng@localhost~]$ sudo systemctlrestartelasticsearch.service [wangpeng@localhost~]$curlhttp: //localhost :9200 { "name" : "node-1" , "cluster_name" : "elasticsearch-test" , "cluster_uuid" : "zVEeXtPNTaeH-TKah7Buzw" , "version" :{ "number" : "5.4.0" , "build_hash" : "780f8c4" , "build_date" : "2017-04-28T17:43:27.229Z" , "build_snapshot" : false , "lucene_version" : "6.5.0" }, "tagline" : "YouKnow,forSearch" } 6、将/etc/elasticsearch/配置拷贝到/usr/share/elasticsearch/config下面 1 2 3 4 [wangpeng@localhost~]$ sudo mkdir /usr/share/elasticsearch/config [wangpeng@localhost~]$ sudo ln -sf /etc/elasticsearch/ * /usr/share/elasticsearch/config/ [wangpeng@localhost~]$ sudo chown -Relasticsearch:elasticsearch /usr/share/elasticsearch [wangpeng@localhost~]$ sudo systemctlrestartelasticsearch.service 注意:这一点好多人不会注意,因为你不修复也不会启动失败,但是就是写不进数据进去,这个坑好久才发现,看下日志会报错,但是却能启动,我也是服了!~ 7、装个head插件 这个插件5.X官网不再支持了,插件命令没有了,因为它有自己x-pack插件了,但是我装了x-pack发现着实让人吐血,有安全认证方面的问题,导致elk各种问题出现,目前还没研究明白,时间不充裕。 这个head插件我是直接抄的网上大神制作,略有改动。 7.1、下载并配置nodejs 由于head插件本质上还是一个nodejs的工程,因此需要安装node,使用npm来安装依赖的包。(npm可以理解为maven) 去官网下载nodejs,https://nodejs.org/en/download/ 1 2 3 4 5 6 wgethttps: //nodejs .org /dist/v8 .1.1 /node-v8 .1.1-linux-x64. tar .xz tar xfnode-v8.1.1-linux-x64. tar .xz mv node-v8.1.1-linux-x64 /usr/local/node chown -Relasticsearch:elasticsearch /usr/local/node ln -sf /usr/local/node/bin/node /usr/bin/node ln -sf /usr/local/node/bin/npm /usr/bin/npm 7.2、安装grunt 1 2 npm install -ggrunt-cli ln -sf /usr/local/node/bin/grunt /usr/bin/grunt cd /var/lib/elasticsearch 7.3、下载、安装并配置head 1 2 3 4 5 6 yum-y install git cd /var/lib/elasticsearch gitclonegit: //github .com /mobz/elasticsearch-head .git chown -Relasticsearch:elasticsearchelasticsearch- head / cd elasticsearch- head / npm install 7.4、配置head文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 [root@elk-node1~] #cd/var/lib/elasticsearch/elasticsearch-head/ vimGruntfile.js connect:{ server:{ options:{ port:9100, hostname : "0.0.0.0" , base: '.' , keepalive: true } } } [root@elk-node1elasticsearch- head ] #cd_site/ [root@elk-node1_site] #vimapp.js 把localhost修改成你es的服务器地址: 1 this.base_uri=this.config.base_uri||this.prefs.get( "app-base_uri" )|| "http://10.10.10.10:9200" ; 7.5、启动head插件 1 gruntserver& 安装Kibana 1、yum安装Kibana 1 [wangpeng@localhost~]$ sudo yum install kibana rpm包配置文件在/etc/kibana下面的kibana.yml /etc/kibana/kibana.yml 2、配置Kibana文件 1 2 3 4 [wangpeng@localhost~]$vim /etc/kibana/kibana .yml server.port:5601 server.host: "0.0.0.0" elasticsearch.url: "http://localhost:9200" 3、启动并设置开机启动 1 2 3 [wangpeng@localhost~]$ sudo systemctl enable kibana.service Created symlink from /etc/systemd/system/multi-user .target.wants /kibana .serviceto /etc/systemd/system/kibana .service [wangpeng@localhost~]$ sudo systemctlstartkibana.service 安装Logstash 1、yum安装Logstash 1 2 3 4 5 [wangpeng@localhost~]$ sudo yum-y install logstash [wangpeng@localhost~]$ sudo systemctlstartlogstash.service [wangpeng@localhost~]$ sudo ln -s /usr/share/logstash/bin/logstash /usr/bin/logstash [wangpeng@localhost~]$ sudo -ulogstashsh-c 'mkdir-pv/usr/share/logstash/config' [wangpeng@localhost~]$ sudo -ulogstashsh-c 'ln-s/etc/logstash/*/usr/share/logstash/config/' 2、测试Logstash是否能正常运行 1 2 3 4 5 6 7 8 9 10 11 12 13 [wangpeng@localhost~]$ sudo logstash-e 'input{stdin{}}output{stdout{}}' helloworld 2017-06-02T07:14:13.130Zlocalhosthelloworld [wangpeng@localhost~]$ sudo logstash-e'input{stdin{}}output{ stdout{codec=>rubydebug}}' helloworld Thestdinpluginisnowwaiting for input: { "@timestamp" =>2017-06-02T07:17:44.053Z, "@version" => "1" , "host" => "localhost" , "message" => "helloworld" } 3、写个测试文件,测试一下es是否能够接受数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 [wangpeng@localhost~]$vim /etc/logstash/conf .d /test .conf input{ stdin{} } output{ elasticsearch{ hosts=> "127.0.0.1:9200" index=> "test-messages-%{+YYYY.MM.dd}" } } [wangpeng@localhost~]$logstash-f /etc/logstash/conf .d /test .conf-t SendingLogstash'slogsto /var/log/logstash which isnowconfiguredvialog4j2.properties ConfigurationOK [wangpeng@localhost~]$logstash-f /etc/logstash/conf .d /test .conf SendingLogstash'slogsto /var/log/logstash which isnowconfiguredvialog4j2.properties Thestdinpluginisnowwaiting for input: helloworld thisis test message studylogstash 4、Kibana里添加该索引(测试),只要es里面能产生索引,Kibana就能加在上去 安装调试先到这里。 本文转自 wangpengtai 51CTO博客,原文链接:http://blog.51cto.com/wangpengtai/1939138,如需转载请自行联系原作者

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

XenDesktop学习笔记3之架构

架构: 1、物理组件: DDC一台 PVS+XenCenter 一台 AD+DHCP+DNS 一台 XenServer 一台 用户设备 一台 2、软件要求 XenServer 5.5 (目前5.6还存在不稳定性) XenCenter 5.5 Xendesktop Delivery Controller Provisiong servies 5.1 citrix 联机插件11.2 操作系统 服务器为server 2003 sp2 标准版或企业版 客户机:Xp Sp3 或Win 7 3、网络要求 划分在同一个Vlan里或者一个单独的网段 4、硬件要求 服务器三台 CPU支持虚拟化 内存最少8G 硬盘:100G的本地存储 网卡:100M,千兆最好不过了。 本文转自shj1985122951CTO博客,原文链接:http://blog.51cto.com/shenhj/397523,如需转载请自行联系原作者

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

Android笔记:热门标签,流式布局

一、测试效果未成功 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 package cn.app.meiya.aa.widget; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; /** *类似话题标签的流式布局,测试效果无效 *http://www.apkbus.com/android-239725-1-1.html *Createdbylonshineon15/7/16. */ public class TopicFlowLayout extends ViewGroup{ //存储所有子View private List<List<View>>mAllChildViews= new ArrayList<>(); //每一行的高度 private List<Integer>mLineHeight= new ArrayList<>(); public TopicFlowLayout(Contextcontext){ this (context, null ); //TODOAuto-generatedconstructorstub } public TopicFlowLayout(Contextcontext,AttributeSetattrs){ this (context,attrs, 0 ); //TODOAuto-generatedconstructorstub } public TopicFlowLayout(Contextcontext,AttributeSetattrs, int defStyle){ super (context,attrs,defStyle); //TODOAuto-generatedconstructorstub } @Override protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec){ //TODOAuto-generatedmethodstub //父控件传进来的宽度和高度以及对应的测量模式 int sizeWidth=MeasureSpec.getSize(widthMeasureSpec); int modeWidth=MeasureSpec.getMode(widthMeasureSpec); int sizeHeight=MeasureSpec.getSize(heightMeasureSpec); int modeHeight=MeasureSpec.getMode(heightMeasureSpec); //如果当前ViewGroup的宽高为wrap_content的情况 int width= 0 ; //自己测量的宽度 int height= 0 ; //自己测量的高度 //记录每一行的宽度和高度 int lineWidth= 0 ; int lineHeight= 0 ; //获取子view的个数 int childCount=getChildCount(); for ( int i= 0 ;i<childCount;i++){ Viewchild=getChildAt(i); //测量子View的宽和高 measureChild(child,widthMeasureSpec,heightMeasureSpec); //得到LayoutParams MarginLayoutParamslp=(MarginLayoutParams)getLayoutParams(); //子View占据的宽度 int childWidth=child.getMeasuredWidth()+lp.leftMargin+lp.rightMargin; //子View占据的高度 int childHeight=child.getMeasuredHeight()+lp.topMargin+lp.bottomMargin; //换行时候 if (lineWidth+childWidth>sizeWidth){ //对比得到最大的宽度 width=Math.max(width,lineWidth); //重置lineWidth lineWidth=childWidth; //记录行高 height+=lineHeight; lineHeight=childHeight; } else { //不换行情况 //叠加行宽 lineWidth+=childWidth; //得到最大行高 lineHeight=Math.max(lineHeight,childHeight); } //处理最后一个子View的情况 if (i==childCount- 1 ){ width=Math.max(width,lineWidth); height+=lineHeight; } } //wrap_content setMeasuredDimension(modeWidth==MeasureSpec.EXACTLY?sizeWidth:width, modeHeight==MeasureSpec.EXACTLY?sizeHeight:height); super .onMeasure(widthMeasureSpec,heightMeasureSpec); } @Override protected void onLayout( boolean changed, int l, int t, int r, int b){ //TODOAuto-generatedmethodstub mAllChildViews.clear(); mLineHeight.clear(); //获取当前ViewGroup的宽度 int width=getWidth(); int lineWidth= 0 ; int lineHeight= 0 ; //记录当前行的view List<View>lineViews= new ArrayList<View>(); int childCount=getChildCount(); for ( int i= 0 ;i<childCount;i++){ Viewchild=getChildAt(i); MarginLayoutParamslp=(MarginLayoutParams)child.getLayoutParams(); int childWidth=child.getMeasuredWidth(); int childHeight=child.getMeasuredHeight(); //如果需要换行 if (childWidth+lineWidth+lp.leftMargin+lp.rightMargin>width){ //记录LineHeight mLineHeight.add(lineHeight); //记录当前行的Views mAllChildViews.add(lineViews); //重置行的宽高 lineWidth= 0 ; lineHeight=childHeight+lp.topMargin+lp.bottomMargin; //重置view的集合 lineViews= new ArrayList(); } lineWidth+=childWidth+lp.leftMargin+lp.rightMargin; lineHeight=Math.max(lineHeight,childHeight+lp.topMargin+lp.bottomMargin); lineViews.add(child); } //处理最后一行 mLineHeight.add(lineHeight); mAllChildViews.add(lineViews); //设置子View的位置 int left= 0 ; int top= 0 ; //获取行数 int lineCount=mAllChildViews.size(); for ( int i= 0 ;i<lineCount;i++){ //当前行的views和高度 lineViews=mAllChildViews.get(i); lineHeight=mLineHeight.get(i); for ( int j= 0 ;j<lineViews.size();j++){ Viewchild=lineViews.get(j); //判断是否显示 if (child.getVisibility()==View.GONE){ continue ; } MarginLayoutParamslp=(MarginLayoutParams)child.getLayoutParams(); int cLeft=left+lp.leftMargin; int cTop=top+lp.topMargin; int cRight=cLeft+child.getMeasuredWidth(); int cBottom=cTop+child.getMeasuredHeight(); //进行子View进行布局 child.layout(cLeft,cTop,cRight,cBottom); left+=child.getMeasuredWidth()+lp.leftMargin+lp.rightMargin; } left= 0 ; top+=lineHeight; } } /** *与当前ViewGroup对应的LayoutParams */ @Override public LayoutParamsgenerateLayoutParams(AttributeSetattrs){ //TODOAuto-generatedmethodstub return new MarginLayoutParams(getContext(),attrs); } } 用法: 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 <fontcolor= "#362e2b" ><fontstyle= "background-color:rgb(255,255,255)" ><fontface= "Arial" ><fontstyle= "font-size:14px" > package com.czm.flowlayout; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.ViewGroup.LayoutParams; import android.view.ViewGroup.MarginLayoutParams; import android.widget.TextView; /** * *@authorcaizhiming *@createdon2015-4-13 */ public class MainActivity extends Activity{ private StringmNames[]={ "welcome" , "android" , "TextView" , "apple" , "jamy" , "kobebryant" , "jordan" , "layout" , "viewgroup" , "margin" , "padding" , "text" , "name" , "type" , "search" , "logcat" }; private XCFlowLayoutmFlowLayout; @Override protected void onCreate(BundlesavedInstanceState){ super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); initChildViews(); } private void initChildViews(){ //TODOAuto-generatedmethodstub mFlowLayout=(XCFlowLayout)findViewById(R.id.flowlayout); MarginLayoutParamslp= new MarginLayoutParams( LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); lp.leftMargin= 5 ; lp.rightMargin= 5 ; lp.topMargin= 5 ; lp.bottomMargin= 5 ; for ( int i= 0 ;i<mNames.length;i++){ TextViewview= new TextView( this ); view.setText(mNames[i]); view.setTextColor(Color.WHITE); view.setBackgroundDrawable(getResources().getDrawable(R.drawable.textview_bg)); mFlowLayout.addView(view,lp); } } }</font></font></font></font> 二、测试可用 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 package cn.app.meiya.aa.widget; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; /** *http://www.bkjia.com/Androidjc/1013458.html *Createdbylonshineon15/7/16. */ public class FlowLayout extends ViewGroup{ private float mVerticalSpacing; //每个item纵向间距 private float mHorizontalSpacing; //每个item横向间距 public FlowLayout(Contextcontext){ super (context); } public FlowLayout(Contextcontext,AttributeSetattrs){ super (context,attrs); } public void setHorizontalSpacing( float pixelSize){ mHorizontalSpacing=pixelSize; } public void setVerticalSpacing( float pixelSize){ mVerticalSpacing=pixelSize; } @Override protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec){ int selfWidth=resolveSize( 0 ,widthMeasureSpec); int paddingLeft=getPaddingLeft(); int paddingTop=getPaddingTop(); int paddingRight=getPaddingRight(); int paddingBottom=getPaddingBottom(); int childLeft=paddingLeft; int childTop=paddingTop; int lineHeight= 0 ; //通过计算每一个子控件的高度,得到自己的高度 for ( int i= 0 ,childCount=getChildCount();i<childCount;++i){ ViewchildView=getChildAt(i); LayoutParamschildLayoutParams=childView.getLayoutParams(); childView.measure( getChildMeasureSpec(widthMeasureSpec,paddingLeft+paddingRight, childLayoutParams.width), getChildMeasureSpec(heightMeasureSpec,paddingTop+paddingBottom, childLayoutParams.height)); int childWidth=childView.getMeasuredWidth(); int childHeight=childView.getMeasuredHeight(); lineHeight=Math.max(childHeight,lineHeight); if (childLeft+childWidth+paddingRight>selfWidth){ childLeft=paddingLeft; childTop+=mVerticalSpacing+lineHeight; lineHeight=childHeight; } else { childLeft+=childWidth+mHorizontalSpacing; } } int wantedHeight=childTop+lineHeight+paddingBottom; setMeasuredDimension(selfWidth,resolveSize(wantedHeight,heightMeasureSpec)); } @Override protected void onLayout( boolean changed, int l, int t, int r, int b){ int myWidth=r-l; int paddingLeft=getPaddingLeft(); int paddingTop=getPaddingTop(); int paddingRight=getPaddingRight(); int childLeft=paddingLeft; int childTop=paddingTop; int lineHeight= 0 ; //根据子控件的宽高,计算子控件应该出现的位置。 for ( int i= 0 ,childCount=getChildCount();i<childCount;++i){ ViewchildView=getChildAt(i); if (childView.getVisibility()==View.GONE){ continue ; } int childWidth=childView.getMeasuredWidth(); int childHeight=childView.getMeasuredHeight(); lineHeight=Math.max(childHeight,lineHeight); if (childLeft+childWidth+paddingRight>myWidth){ childLeft=paddingLeft; childTop+=mVerticalSpacing+lineHeight; lineHeight=childHeight; } childView.layout(childLeft,childTop,childLeft+childWidth,childTop+childHeight); childLeft+=childWidth+mHorizontalSpacing; } } } 本文转自 glblong 51CTO博客,原文链接:http://blog.51cto.com/glblong/1675221,如需转载请自行联系原作者

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

学习笔记TF065:TensorFlowOnSpark

Hadoop生态大数据系统分为Yam、 HDFS、MapReduce计算框架。TensorFlow分布式相当于MapReduce计算框架,Kubernetes相当于Yam调度系统。TensorFlowOnSpark,利用远程直接内存访问(Remote Direct Memory Access,RDMA)解决存储功能和调度,实现深度学习和大数据融合。TensorFlowOnSpark(TFoS),雅虎开源项目。https://github.com/yahoo/TensorFlowOnSpark 。支持ApacheSpark集群分布式TensorFlow训练、预测。TensorFlowOnSpark提供桥接程序,每个Spark Executor启动一个对应TensorFlow进程,通过远程进程通信(RPC)交互。 TensorFlowOnSpark架构。TensorFlow训练程序用Spark集群运行,管理Spark集群步骤:预留,在Executor执行每个TensorFlow进程保留一个端口,启动数据消息监听器。启动,在Executor启动TensorFlow主函数。数据获取,TensorFlow Readers和QueueRunners机制直接读取HDFS数据文件,Spark不访问数据;Feeding,SparkRDD 数据发送TensorFlow节点,数据通过feed_dict机制传入TensorFlow计算图。关闭,关闭Executor TensorFlow计算节点、参数服务节点。Spark Driver->Spark Executor->参数服务器->TensorFlow Core->gRPC、RDMA->HDFS数据集。http://yahoohadoop.tumblr.com/post/157196317141/open-sourcing-tensorflowonspark-distributed-deep 。 TensorFlowOnSpark MNIST。https://github.com/yahoo/TensorFlowOnSpark/wiki/GetStarted_standalone 。Standalone模式Spark集群,一台计算机。安装 Spark、Hadoop。部署Java 1.8.0 JDK。下载Spark2.1.0版 http://spark.apache.org/downloads.html 。下载Hadoop2.7.3版 http://hadoop.apache.org/#Download+Hadoop 。0.12.1版本支持较好。修改配置文件,设置环境变量,启动Hadoop:$HADOOP_HOME/sbin/start-all.sh。检出TensorFlowOnSpark源代码: git clone --recurse-submodules https://github.com/yahoo/TensorFlowOnSpark.git cd TensorFlowOnSpark git submodule init git submodule update --force git submodule foreach --recursive git clean -dfx 源代码打包,提交任务使用: cd TensorflowOnSpark/src zip -r ../tfspark.zip * 设置TensorFlowOnSpark根目录环境变量: cd TensorFlowOnSpark export TFoS_HOME=$(pwd) 启动Spark主节点(master): $(SPARK_HOME)/sbin/start-master.sh 配置两个工作节点(worker)实例,master-spark-URL连接主节点: export MASTER=spark://$(hostname):7077 export SPARK_WORKER_INSTANCES=2 export CORES_PER_WORKER=1 export TOTAL_CORES=$(($(CORES_PER_WORKER)*$(SPARK_WORKER_INSTANCES))) $(SPARK_HOME)/sbin/start-slave.sh -c $CORES_PER_WORKER -m 3G $(MASTER) 提交任务,MNIST zip文件转换为HDFS RDD 数据集: $(SPARK_HOME)/bin/spark-submit \ --master $(MASTER) --conf spark.ui.port=4048 --verbose \ $(TFoS_HOME)/examples/mnist/mnist_data_setup.py \ --output examples/mnist/csv \ --format csv 查看处理过的数据集: hadoop fs -ls hdfs://localhost:9000/user/libinggen/examples/mnist/csv 查看保存图片、标记向量: hadoop fs -ls hdfs://localhost:9000/user/libinggen/examples/mnist/csv/train/labels 把训练集、测试集分别保存RDD数据。https://github.com/yahoo/TensorFlowOnSpark/blob/master/examples/mnist/mnist_data_setup.py 。 from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy import tensorflow as tf from array import array from tensorflow.contrib.learn.python.learn.datasets import mnist def toTFExample(image, label): """Serializes an image/label as a TFExample byte string""" example = tf.train.Example( features = tf.train.Features( feature = { 'label': tf.train.Feature(int64_list=tf.train.Int64List(value=label.astype("int64"))), 'image': tf.train.Feature(int64_list=tf.train.Int64List(value=image.astype("int64"))) } ) ) return example.SerializeToString() def fromTFExample(bytestr): """Deserializes a TFExample from a byte string""" example = tf.train.Example() example.ParseFromString(bytestr) return example def toCSV(vec): """Converts a vector/array into a CSV string""" return ','.join([str(i) for i in vec]) def fromCSV(s): """Converts a CSV string to a vector/array""" return [float(x) for x in s.split(',') if len(s) > 0] def writeMNIST(sc, input_images, input_labels, output, format, num_partitions): """Writes MNIST image/label vectors into parallelized files on HDFS""" # load MNIST gzip into memory # MNIST图像、标记向量写入HDFS with open(input_images, 'rb') as f: images = numpy.array(mnist.extract_images(f)) with open(input_labels, 'rb') as f: if format == "csv2": labels = numpy.array(mnist.extract_labels(f, one_hot=False)) else: labels = numpy.array(mnist.extract_labels(f, one_hot=True)) shape = images.shape print("images.shape: {0}".format(shape)) # 60000 x 28 x 28 print("labels.shape: {0}".format(labels.shape)) # 60000 x 10 # create RDDs of vectors imageRDD = sc.parallelize(images.reshape(shape[0], shape[1] * shape[2]), num_partitions) labelRDD = sc.parallelize(labels, num_partitions) output_images = output + "/images" output_labels = output + "/labels" # save RDDs as specific format # RDDs保存特定格式 if format == "pickle": imageRDD.saveAsPickleFile(output_images) labelRDD.saveAsPickleFile(output_labels) elif format == "csv": imageRDD.map(toCSV).saveAsTextFile(output_images) labelRDD.map(toCSV).saveAsTextFile(output_labels) elif format == "csv2": imageRDD.map(toCSV).zip(labelRDD).map(lambda x: str(x[1]) + "|" + x[0]).saveAsTextFile(output) else: # format == "tfr": tfRDD = imageRDD.zip(labelRDD).map(lambda x: (bytearray(toTFExample(x[0], x[1])), None)) # requires: --jars tensorflow-hadoop-1.0-SNAPSHOT.jar tfRDD.saveAsNewAPIHadoopFile(output, "org.tensorflow.hadoop.io.TFRecordFileOutputFormat", keyClass="org.apache.hadoop.io.BytesWritable", valueClass="org.apache.hadoop.io.NullWritable") # Note: this creates TFRecord files w/o requiring a custom Input/Output format # else: # format == "tfr": # def writeTFRecords(index, iter): # output_path = "{0}/part-{1:05d}".format(output, index) # writer = tf.python_io.TFRecordWriter(output_path) # for example in iter: # writer.write(example) # return [output_path] # tfRDD = imageRDD.zip(labelRDD).map(lambda x: toTFExample(x[0], x[1])) # tfRDD.mapPartitionsWithIndex(writeTFRecords).collect() def readMNIST(sc, output, format): """Reads/verifies previously created output""" output_images = output + "/images" output_labels = output + "/labels" imageRDD = None labelRDD = None if format == "pickle": imageRDD = sc.pickleFile(output_images) labelRDD = sc.pickleFile(output_labels) elif format == "csv": imageRDD = sc.textFile(output_images).map(fromCSV) labelRDD = sc.textFile(output_labels).map(fromCSV) else: # format.startswith("tf"): # requires: --jars tensorflow-hadoop-1.0-SNAPSHOT.jar tfRDD = sc.newAPIHadoopFile(output, "org.tensorflow.hadoop.io.TFRecordFileInputFormat", keyClass="org.apache.hadoop.io.BytesWritable", valueClass="org.apache.hadoop.io.NullWritable") imageRDD = tfRDD.map(lambda x: fromTFExample(str(x[0]))) num_images = imageRDD.count() num_labels = labelRDD.count() if labelRDD is not None else num_images samples = imageRDD.take(10) print("num_images: ", num_images) print("num_labels: ", num_labels) print("samples: ", samples) if __name__ == "__main__": import argparse from pyspark.context import SparkContext from pyspark.conf import SparkConf parser = argparse.ArgumentParser() parser.add_argument("-f", "--format", help="output format", choices=["csv","csv2","pickle","tf","tfr"], default="csv") parser.add_argument("-n", "--num-partitions", help="Number of output partitions", type=int, default=10) parser.add_argument("-o", "--output", help="HDFS directory to save examples in parallelized format", default="mnist_data") parser.add_argument("-r", "--read", help="read previously saved examples", action="store_true") parser.add_argument("-v", "--verify", help="verify saved examples after writing", action="store_true") args = parser.parse_args() print("args:",args) sc = SparkContext(conf=SparkConf().setAppName("mnist_parallelize")) if not args.read: # Note: these files are inside the mnist.zip file writeMNIST(sc, "mnist/train-images-idx3-ubyte.gz", "mnist/train-labels-idx1-ubyte.gz", args.output + "/train", args.format, args.num_partitions) writeMNIST(sc, "mnist/t10k-images-idx3-ubyte.gz", "mnist/t10k-labels-idx1-ubyte.gz", args.output + "/test", args.format, args.num_partitions) if args.read or args.verify: readMNIST(sc, args.output + "/train", args.format) 提交训练任务,开始训练,在HDFS生成mnist_model,命令: ${SPARK_HOME}/bin/spark-submit \ --master ${MASTER} \ --py-files ${TFoS_HOME}/examples/mnist/spark/mnist_dist.py \ --conf spark.cores.max=${TOTAL_CORES} \ --conf spark.task.cpus=${CORES_PER_WORKER} \ --conf spark.executorEnv.JAVA_HOME="$JAVA_HOME" \ ${TFoS_HOME}/examples/mnist/spark/mnist_spark.py \ --cluster_size ${SPARK_WORKER_INSTANCES} \ --images examples/mnist/csv/train/images \ --labels examples/mnist/csv/train/labels \ --format csv \ --mode train \ --model mnist_model mnist_dist.py 构建TensorFlow 分布式任务,定义分布式任务主函数,启动TensorFlow主函数map_fun,数据获取方式Feeding。获取TensorFlow集群和服务器实例: cluster, server = TFNode.start_cluster_server(ctx, 1, args.rdma) TFNode调用tfspark.zip TFNode.py文件。 mnist_spark.py文件是训练主程序,TensorFlowOnSpark部署步骤: from __future__ import absolute_import from __future__ import division from __future__ import print_function from pyspark.context import SparkContext from pyspark.conf import SparkConf import argparse import os import numpy import sys import tensorflow as tf import threading import time from datetime import datetime from tensorflowonspark import TFCluster import mnist_dist sc = SparkContext(conf=SparkConf().setAppName("mnist_spark")) executors = sc._conf.get("spark.executor.instances") num_executors = int(executors) if executors is not None else 1 num_ps = 1 parser = argparse.ArgumentParser() parser.add_argument("-b", "--batch_size", help="number of records per batch", type=int, default=100) parser.add_argument("-e", "--epochs", help="number of epochs", type=int, default=1) parser.add_argument("-f", "--format", help="example format: (csv|pickle|tfr)", choices=["csv","pickle","tfr"], default="csv") parser.add_argument("-i", "--images", help="HDFS path to MNIST images in parallelized format") parser.add_argument("-l", "--labels", help="HDFS path to MNIST labels in parallelized format") parser.add_argument("-m", "--model", help="HDFS path to save/load model during train/inference", default="mnist_model") parser.add_argument("-n", "--cluster_size", help="number of nodes in the cluster", type=int, default=num_executors) parser.add_argument("-o", "--output", help="HDFS path to save test/inference output", default="predictions") parser.add_argument("-r", "--readers", help="number of reader/enqueue threads", type=int, default=1) parser.add_argument("-s", "--steps", help="maximum number of steps", type=int, default=1000) parser.add_argument("-tb", "--tensorboard", help="launch tensorboard process", action="store_true") parser.add_argument("-X", "--mode", help="train|inference", default="train") parser.add_argument("-c", "--rdma", help="use rdma connection", default=False) args = parser.parse_args() print("args:",args) print("{0} ===== Start".format(datetime.now().isoformat())) if args.format == "tfr": images = sc.newAPIHadoopFile(args.images, "org.tensorflow.hadoop.io.TFRecordFileInputFormat", keyClass="org.apache.hadoop.io.BytesWritable", valueClass="org.apache.hadoop.io.NullWritable") def toNumpy(bytestr): example = tf.train.Example() example.ParseFromString(bytestr) features = example.features.feature image = numpy.array(features['image'].int64_list.value) label = numpy.array(features['label'].int64_list.value) return (image, label) dataRDD = images.map(lambda x: toNumpy(str(x[0]))) else: if args.format == "csv": images = sc.textFile(args.images).map(lambda ln: [int(x) for x in ln.split(',')]) labels = sc.textFile(args.labels).map(lambda ln: [float(x) for x in ln.split(',')]) else: # args.format == "pickle": images = sc.pickleFile(args.images) labels = sc.pickleFile(args.labels) print("zipping images and labels") dataRDD = images.zip(labels) #1.为在Executor执行每个TensorFlow进程保留一个端口 cluster = TFCluster.run(sc, mnist_dist.map_fun, args, args.cluster_size, num_ps, args.tensorboard, TFCluster.InputMode.SPARK) #2.启动Tensorflow主函数 cluster.start(mnist_dist.map_fun, args) if args.mode == "train": #3.训练 cluster.train(dataRDD, args.epochs) else: #3.预测 labelRDD = cluster.inference(dataRDD) labelRDD.saveAsTextFile(args.output) #4.关闭Executor TensorFlow计算节点、参数服务节点 cluster.shutdown() print("{0} ===== Stop".format(datetime.now().isoformat())) 预测命令: ${SPARK_HOME}/bin/spark-submit \ --master ${MASTER} \ --py-files ${TFoS_HOME}/examples/mnist/spark/mnist_dist.py \ --conf spark.cores.max=${TOTAL_CORES} \ --conf spark.task.cpus=${CORES_PER_WORKER} \ --conf spark.executorEnv.JAVA_HOME="$JAVA_HOME" \ ${TFoS_HOME}/examples/mnist/spark/mnist_spark.py \ --cluster_size ${SPARK_WORKER_INSTANCES} \ --images examples/mnist/csv/test/images \ --labels examples/mnist/csv/test/labels \ --mode inference \ --format csv \ --model mnist_model \ --output predictions 还可以Amazon EC2运行及在Hadoop集群采用YARN模式运行。 参考资料:《TensorFlow技术解析与实战》 欢迎推荐上海机器学习工作机会,我的微信:qingxingfengzi

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

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

Sublime Text

Sublime Text

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

用户登录
用户注册
修改密码
忘记密码