• Programming by 白影를 방문하신 여러분을 환영합니다 :)

여러 파일로 이루어진 세트형태의 경우 용량 구하기를 할때 확장자별로 전부 확인을 해야하는데 이런 경우

네이밍이 포함된 파일 경로를 검색하여 합계를 구하면 쉽게 해결된다.

폴더별로 따로 구분하지 않은 경우 사용할 수 있다.

물론 파일의 수가 늘어나면 연산 시간을 늘어나는 구조이다.


1. 해당 폴더의 경로를 구하고

2. 해당 폴더의 파일들은 전부 검색하면서 원하는 문자열이 포함되어있는지 여부를 체크하여

3. 해당 파일의 용량을 합산한다.


for (path, dirs, files) in os.walk(folderPath):
    if files :
        for filename in files :
            if filename.count(“FileName”) >= 1 :
                filename = os.path.join(path, filename)
                print filename + ' : ' + str(os.path.getsize(filename))
                folder_size += os.path.getsize(filename)
print "Folder = %0.1f KB" % (folder_size/(1024.0))


'Programming > Python' 카테고리의 다른 글

Python + Oracle Connect  (0) 2015.10.30

Python + Oracle Connect

Programming/Python 白影 2015. 10. 30. 14:44

Python에 Oracle DataBase에 접속할 일이 생겨서 약간의 검색과 삽질을 해보았다.


일단 cx_Oracle을 설치하는 부분이 많이 보이는데 자신이 64비트라고 64비트 파일을 받으면 안된다.

(URL : https://pypi.python.org/pypi/cx_Oracle)


해당 설치가 된 비트를 확인하고 32비트로 설치를 진행하였다.


이때 해당 환경사항은 Oracle 11g, 32bit, Python 2.7이였다.


2.7이 설치가 안되었다고 뜨는 사람들은 환경변수에 가서 Python 설치한 폴더경로를 Path에 추가해주면 된다.


import 하는 부분에서 에러가 나지 않고 connect 설정하는 부분에서 에러가 나더라...


맞다... 내가 접속할 Database 버전을 따라간다... 다시 10g 버전을 찾다보니 cx_Oracle 버전이 5.0.4까지 내려갔다.

(최신버전은 11g, 12c만 지원한다. URL : http://sourceforge.net/projects/cx-oracle/files/)


위 링크에서 예전버전을 찾을 수 있으니 자신에게 해당되는 버전을 찾아서 설치하면 된다.


나는 Oracle 10g, 32bit, Python 2.7을 찾아서 설치하였다.


환경설정 후에는 매우 쉽다.


아래 간단하게 적었다. (사실 소스 부분은 별 문제가 없다.. 환경설정하는 부분이 문제지)


import cx_Oracle

connector = cx_Oracle.connect(ID, PW , TNS_INFO(IP:Port/SID))
cursorP = connector .cursor()
cursorP.execute(Query Text)


이 글에서는 저 위에 환경설정하는 부분이 도움이 될 것이라 생각된다.


매우 간단하다...

shp 파일의 경로로 파일을 열고

객체를 호출한 다음에

해당 sde의 layer에 집어넣는다...

여기서 객체가 1개인 경우는 상관없지만 여러개가 있는 경우 아래와 같이 while문을 이용해서 넣어주는 것이 좋다.

몇개인지 굳이 셀 필요는 없으니까...

Arcobject를 만져본 사람이라면 대략 변수가 뭘 의미하는지는 아실거라 생각하고

아래 소스만 올립니다. (아래소스만으로는 안되고... 위에 기본적인 설정 및 접속 세팅은 필요합니다...)



            IFeatureClass pFClass = pWorkspace.openFeatureClass(layerName);             

            FeatureClass shpFClass = null;    

            ShapefileWorkspaceFactory shapefileWorkspaceFactory = new ShapefileWorkspaceFactory();

            Workspace workspace = new Workspace(shapefileWorkspaceFactory.openFromFile(shpPath, 0));

            shpFClass = new FeatureClass(workspace.openFeatureClass(shpNm));

            

            String shapeFieldName = shpFClass.getShapeFieldName();

            Fields shpFields = (Fields) shpFClass.getFields();

              

            int lngIndex = shpFields.findField(shapeFieldName);

            Field field = (Field) shpFields.getField(lngIndex);

            

            int shpFieldCount = shpFields.getFieldCount();

            FeatureCursor featureCursor = new FeatureCursor(shpFClass.search(null, true));            

            IFeature shpFeature = (IFeature) featureCursor.nextFeature();

              

            while (shpFeature != null) {

                StringBuffer row = new StringBuffer();

                IFeature pFeature = pFClass.createFeature();                


                for (int index = 0; index < shpFieldCount; index++) {

                    int fieldType = shpFeature.getFields().getField(index).getType();

                    if(pFeature.getFields().findField(shpFeature.getFields().getField(index).getName())==-1){

                        if(shpFeature.getFields().getField(index).getName().equals("FID"))

                            strError=shpFeature.getValue(index).toString();

                        continue;

                    }

                switch (fieldType) {

                    case esriFieldType.esriFieldTypeDouble:

                        if(!shpFeature.getFields().getField(index).getName().equals("AREA") && !shpFeature.getFields().getField(index).getName().equals("LEN")){         

                            row.append(shpFeature.getValue(index) + "\t");

                          }

                        break;

                    case esriFieldType.esriFieldTypeInteger:      

                        break;

                    case esriFieldType.esriFieldTypeSingle:

                        row.append(shpFeature.getValue(index) + "\t");

                        break;

                    case esriFieldType.esriFieldTypeSmallInteger:

                        row.append(shpFeature.getValue(index) + "\t");

                        break;

                    case esriFieldType.esriFieldTypeString:

                      row.append(shpFeature.getValue(index) + "\t");

                    break;

                    case esriFieldType.esriFieldTypeGeometry:

                      row.append("(geometry)" + "\t");

                      

                    IGeometry Geometry = shpFeature.getShape();

                    Geometry.setSpatialReferenceByRef(FromProjection);

                    Geometry.project(ToProjection);

                  

                    IEnvelope shpExtent = Geometry.getEnvelope();

                    pFeature.setShapeByRef(Geometry);

                    break;

                }

              }

                  

                pFeature.setValue(pFeature.getFields().findField("FieldNm"), FieldValue);

                pFeature.store(); 

                shpFeature = (IFeature) featureCursor.nextFeature();     

            }


'Programming > Arcgis' 카테고리의 다른 글

ArcObject API Local 설치  (0) 2015.03.27

JqGrid로 구현된 테이블에서 특정 Column을 선택하면 기능을 작동시키고 싶은 경우

onCellSelect을 사용하면 된다.

아래는 그 예제다. (그대로 사용해도 되는지 모르겠지만... 원소스에서 내용만 수정하였다.)

예제에서는 나이에 해당하는 컬럼을 클릭할 경우 그 Row에 해당하는 사람의 이름을 출력한다.



var selectUrl = "/selectTable";

var colNames = ['이름', '나이', '학년'];

    var colModel = [

{name:'Name'    ,index:'reqstSn' ,width:0},

{name:'Age'    ,index:'jobPrgstatClcdNm' ,width:100},

{name:'Grade'    ,index:'jobSecdNm' ,width:60}

         ];

    jQuery("#grid").jqGrid({

url:selectUrl,

postData: {

        },

        mtype: 'POST',

datatype: "json",

  colNames:colNames,

  colModel:colModel,

  shrinkToFit:false,

  autowidth:true,

            height: 137,

       rowNum: 5,

            rownumbers: true,

       pagination: true,

             scroll: false,

       pager: '#ptypeGrid', 

            sortname: 'default',

  viewrecords: true,

        sortorder: "desc",

     

    loadError : function(xhr,st,err) {

    alert("Error");

        },

     onCellSelect: function(rowid, index, contents, event) 

    {    

    var cm = $(this).jqGrid('getGridParam','colModel');    

    if(cm[index].name == "Age")

    {

         alert($(this).jqGrid('getCell', rowid, 'Name'));

   

    }

});


Arcobject API를 Local에 설치하기


대부분 회사들이 망분리를 하고 있기 때문에 외부 API를 끌어다 쓸수 없는 경우가 많다.

그런경우 Local에 API를 설치하여 사용해야 하는데 Arcobject도 마찬가지이다.


본인도 갑작스런 망분리에.... 로컬로 바꾸는 법을 몰라서 조금 헤매였다...

처음 받았던 소스에 API도 제대로 다 안 들어있는 것도 문제였고 세팅도 제대로 되어있지 않았다.


먼저 설치할 API를 다운로드 받는다. (로그인 필수... 가입이 안되어있다면 가입부터 하자.)

https://developers.arcgis.com/en/downloads/

필자는 Javascrip로 개발을 하였기때문에 빨간 네모칸의 자료를 다운 받았다.

물론 구버전도 받을수 있다. (옵션 선택)



다운로드를 받은 후 압축을 푼다.



압축을 풀면 아래와 같은 내용물이 보일거다.

그중에 arcgis_js_api 부분만 필요하므로 프로젝트에 js들을 모아둔 폴더로 카피한다.

그리고 install.html 파일을 열어서 설명서를 읽어보면



위와 같은 설명이 적혀있는데 말 그대로 init.js와 dojo.js 파일을 찾아서 [HOSTNAME_AND_PATH_TO_JSAPI] 이부분을 자신이 해당 시스템의 ip 주소를 입력해주면 된다. 예를 들면 10.20.30.40이 접속 주소라면 저 부분에 적어주면 된다. Local에서 테스트 용도로 사용하려면 "http://localhost:포트번호"를 적어주면 된다.

그리고 물론 GIS에서 API 링크를 로컬 주소로 바꿔주는것도 잊어먹으면 안된다.


<script type="text/javascript" src="${Ctx}/js//arcgis_js_api/library/3.8/3.8/init.js"></script>

위와 같이 적어주면 된다. 뒤쪽의 init.js는 안 적어도 되지만 간혹 안되는 경우가 있으면 지정해주면 잘 작동한다.



'Programming > Arcgis' 카테고리의 다른 글

Arcobject shp파일을 sde의 layer에 import하기  (0) 2015.03.27

CLOB 구문 검색방법

Programming/SQL 白影 2015. 2. 19. 00:07

WHERE DBMS_LOB.INSTR(lob_column, '검색어') > 0

반올림 : Math.round

제곱함수 : Math.pow 


FIle Copy 방식

Programming/Java / Flex 白影 2015. 1. 8. 22:20

출처  : http://examples.javacodegeeks.com/core-java/io/file/4-ways-to-copy-file-in-java/


1. Copy File Using FileStreams

This is the most classic way to copy the content of a file to another. You simply read a number of bytes from File A using FileInputStream and write them to File B using FileOutputStream.

Here is the code of the first method:

01private static void copyFileUsingFileStreams(File source, File dest)
02        throws IOException {
03    InputStream input = null;
04    OutputStream output = null;
05    try {
06        input = new FileInputStream(source);
07        output = new FileOutputStream(dest);
08        byte[] buf = new byte[1024];
09        int bytesRead;
10        while ((bytesRead = input.read(buf)) > 0) {
11            output.write(buf, 0, bytesRead);
12        }
13    } finally {
14        input.close();
15        output.close();
16    }
17}

As you can see we perform several read and write operations on big chucks of data, so this ought to be a less efficient compared to the next methods we will see.

2. Copy File using java.nio.channels.FileChannel

Java NIO includes a transferFrom method that according to the documentation is supposed to do faster copying operations than FileStreams.

Here is the code of the second method:

01private static void copyFileUsingFileChannels(File source, File dest)
02        throws IOException {
03    FileChannel inputChannel = null;
04    FileChannel outputChannel = null;
05    try {
06        inputChannel = new FileInputStream(source).getChannel();
07        outputChannel = new FileOutputStream(dest).getChannel();
08        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
09    } finally {
10        inputChannel.close();
11        outputChannel.close();
12    }
13}

3. Copy File using Apache Commons IO

Apache Commons IO offers a copyFile(File srcFile, File destFile) method in its FileUtils class that can be used to copy a file to another. It’s very convenient to work with Apache Commons FileUtils class when you already using it to your project. Basically, this class uses Java NIO FileChannel internally.

Here is the code of the third method:

1private static void copyFileUsingApacheCommonsIO(File source, File dest)
2        throws IOException {
3    FileUtils.copyFile(source, dest);
4}

4. Copy File using Java 7 Files class

If you have some experience in Java 7 you will probably know that you can use the copy mehtod of the class Files in order to copy a file to another.

Here is the code of the fourth method:

1private static void copyFileUsingJava7Files(File source, File dest)
2        throws IOException {
3    Files.copy(source.toPath(), dest.toPath());
4}


Table 권한 주기

Programming/SQL 白影 2015. 1. 8. 22:17

GRANT SELECT, INSERT, DELETE, UPDATE ON 테이블명 TO 주려는계정명;

주려는 권한 항목을 SELECT, INSERT, DELETE, UPDATE로 선언하고 

테이블명 뒤에 주려는 계정명을 입력한다.

Ant + ibatis2mybatis

Programming 白影 2014. 10. 10. 13:47

ibatis2mybatis를 사용하려면 먼저 ant가 설치 되어야한다.

Ant 는 http://ant.apache.org에서 받으면 된다.

원하는 경로에 다운받은 파일의 압축을 푼 후에 환경설정에서 path 설정을 해준다.

(;압축을 푼 경로)를 끝에 추가하면 끝이다.

(ANT_HOME을 만들고 PATH에 ANT_HOME을 추가해도 된다.)

console창에서 ant라고 입력하였을때 버전이 출력되면 성공.

 

자 이제 ibatis2mybatis를 사용해보자.

spring 2.5에서 3.0으로 업그레이드시에 xml 파일을 일괄 변환해주는 프로그램이다.

www.mybatis.org 에서 다운 받을 수 있다. (product 메뉴 제일 하단에 있다.)

받아서 압축을 풀면 폴더3개와 기타 파일들이 보인다.

변환할 xml 파일들을 source 폴더에 넣고 console창을 연다.

해당 콘솔창에서 ant -buildfile build.xml을 입력하면 변환된 xml 파일들이 destination 폴더에 생성된다.

100% 완벽한 것은 아니니 실제 사용시 테스트가 필요하다. (대부분 작동이 잘 되는 편이다..)

1 2 3 4