2018/07/25

[DB] New Features of Oracle 12c

New Features of Oracle 12c Summarized

01. Pluggable Databases Through Database Consolidation:

Oracle is doing every thing to jump into the cloud bandwagon. With 12C, Oracle is trying to address the problem of Multitenancy through this feature. There is a radical change and a major change in the core database architecture through the introduction of Container Databases also called CBD and Pluggable Databases (PDB). The memory and process is owned by the Container Database. The container holds the metadata where the PDBs hold the user data. You can create upto 253 PDBs including the seed PDB.
In a large setup, it is common to see 20 or 30 different instances running in production environment. With these many instances, it is a maintenance nightmare as all these instances have to be separately
•Upgraded
•Patched
•Monitored
•Tuned
•RAC Enabled
•Adjusted
•Backed up and
•Data Guarded.
With Pluggable Databases feature, you just have to do all this for ONE single instance. Without this feature, prior to 12C, you would have to create separate schemas and there is always a thread of security how much ever the isolation we build into it. There are problems with namespace conflicts, there is always going to be one public synonym that you can create. With PDBs you can have a separate HR or Scott schema for each PDB, separate Emp, Dept Tables and separate public synonyms. Additionally, 2 PDBs can talk to each other through the regular DB Link feature. There is no high startup cost of creating a database any more. Instead of one instance per day, the shift is into one instance per many databases. For the developer community, you can be oblivious of all this and still continue to use the PDBs as if it were a traditional database, but for the DBAs the world would look like it has changed a lot.
Another cool feature is, you can allocate a CPU percentage for each PDB.
Another initiative being, it has announced a strategic tieup with salesforce.com during the first week of July 2013.

02. Redaction Policy:

This is one of the top features in Oracle 12C. Data Redaction in simple terms means, masking of data. You can setup a Data Redaction policy, for example SSN field in a Employee table can be masked. This is called redaction. From Sql Develop you can do this by going to the table: Employee->Right click on Security Policy->click on New->click on Redaction Policy->Enter SSN.
When you do a select * from employee, it will show that the SSN is masked.
The new data masking will use a package called DBMS_REDACT. It is the extension to the FGAC and VPD present in earlier versions.
By doing this, whoever needs to view the data will be able to see it where as the other users will not be able to view it.

03. Top N Query and Fetch and offset Replacement to Rownum:

With the release of Oracle Database 12c, Oracle has introduced this new SQL syntax to simplify fetching the first few rows. The new sql syntax "Fetch First X Rows only" can be used.

04. Adaptive Query Optimization and Online Stats Gathering:

With this feature, it helps the optimizer to make runtime adjustments to execution plan which leads to better stats. For statements like CTAS (Create Table As Select) and IAS (Insert As Select), the stats is gathered online so that it is available immediately.

05. Restore a Table easily through RMAN:

Earlier if you had to restore a particular table, you had to do all sorts of things like restoring a tablespace and or do Export and Import. The new restore command in RMAN simplifies this task.

06. Size Limit on Varchar2, NVarchar2, Raw Data Types increased:

The previous limit on these data types was 4K. In 12C, it has been increased to 32,767 bytes. Upto 4K, the data is stored inline. I am sure everyone will be happy with this small and cute enhancement.

07. Inline PL/SQL Functions and Procedures:

The in line feature is extended in Oracle 12C. In addition to Views, we can now have PL/SQL Procedures and Functions as in line constructs. The query can be written as if it is calling a real stored procedure, but however the functions do not actually exist in the database. You will not be able to find them in ALL_OBJECTS. I think this will be a very good feature for the developers to explore as there is no code that needs to be compiled.

08. Generated as Identity/Sequence Replacement:

You can now create a col with 'generated as identity' clause. Thats it. Doing this is equivalent to creating a separate sequence and doing a sequence.nextval for each row. This is another handy and a neat feature which will help developer community. This is also called No Sequence Auto Increment Primary Key.

09. Multiple Indexes on a Single Column:

Prior to 12C, a column cant be in more than one index. In 12C, you can include a column in B-tree index as well as a Bit Map index. But, please note that only one index is usable at a given time.

10. Online Migration of Table Partition or Sub Partition:

You can very easily migrate a partition or sub partition from one tablespace to another. Similar to how the online migration was achieved for a non-partitioned table in prior releases, a table partition or sub partition can be moved to another tablespace online or offline. When an ONLINE clause is specified, all DML operations can be performed without any interruption on the partition|sub-partition which is involved in the procedure. In contrast, no DML operations are allowed if the partition|sub-partition is moved offline.

11. Temporary UNDO:

Prior to 12C, undo records generated by TEMP Tablespace is stored in the undo tablespace. With Temp undo feature in 12C, temp undo records can be stored in temporary table instead of UNDO TS. The benefit is - reduced undo tablespace and reduced redo log space used.
SQL> ALTER SYSTEM SET PGA_AGGREGATE_LIMIT=2G;
SQL> ALTER SYSTEM SET PGA_AGGREGATE_LIMIT=0; --disables the hard limit

12. In Database Archiving:

This feature enables archiving rows within a table by marking them as inactive. These inactive rows are in the database and can be optimized using compression but are not visible to the application. These records are skipped during FTS (Full Table Scan).

Other Features:

Advanced Replication and Streams are Dead. It is being replaced with Oracle Golden Gate.
Invisible Columns. You can now have a invisible column in a table. When a column is defined as invisible, the column won’t appear in generic queries
PGA Aggregate Limit setting:
In 12c, you can set a hard limit on PGA by enabling the automatic PGA management, which requires PGA_AGGREGATE_LIMIT parameter settings. Therefore, you can now set the hard limit on PGA by setting the new parameter to avoid excessive PGA usage.
DDL Logging:
The DDL statements will automatically get recorded in xml/log file if ENABLE_DDL_LOGGING is set to True. ALTER SYSTEM|SESSION SET ENABLE_DDL_LOGGING=TRUE

2018/07/20

[명언] 군자삼계(君子三戒), 군자삼외(君子三畏), 군자삼락(君子三樂)

군자삼계(君子三戒) - 《논어》〈계씨편(季氏篇)〉


      원 문 해 설

子曰 君子有三戒 군자에게는 경계해야 할 일이 세 가지 있으니

少之時 血氣未定 戒之在色 젊을때는 혈기가 잡히지 않은지라 경계할 것이 여색이고

及其長也 血氣方剛 戒之在鬪 장성하여 혈기가 강해지면 경계할 것이 싸움이며

及其老也 血氣旣衰 戒之在得 나이가 들어 혈기가 쇠진하면 경계할 것이 물욕이다.

군자삼외(君子三畏) - 《논어》〈계씨편(季氏篇)〉


       원 문 해 설

子曰 君子有三畏 군자에게는 두려운 것이 세 가지 있으니

畏天命 하늘의 명을 두려워하고,

畏大人 대인(자신보다 학덕이 높은 사람)을 두려워하고,

畏聖人之言 성인의 말씀을 두려워한다.

군자삼락(君子三樂) - 《맹자(孟子)》〈진심편(盡心篇)〉


       원 문 해 설

君子有三樂 군자에게는 세 가지 즐거움이 있으니,

而王天下不與存焉 천하의 왕이 되는것은 여기에 넣지 않는다.

父母俱存 兄弟無故 一樂也 부모님이 모두 살아계시고 형제들이 무고한 것이 첫째 즐거움이요,

仰不愧於天 俯不怍於人 二樂也 하늘을 우러러 부끄럽지 않고, 사람들을 굽어보아 부끄럽지 않은것이 두 번째 즐거움이며,

得天下英才 而敎育之 三樂也 천하의 영재를 얻어 가르치는 것이 세 번째 즐거움이다.

2018/07/17

[python] 한글 wordcloud

%matplotlib inline
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import numpy as np
from PIL import Image

cloud_mask = np.array(Image.open("cloud.png"))

text = """내 피 땀 눈물 내 마지막 춤을
다 가져가 가
내 피 땀 눈물 내 차가운 숨을
다 가져가 가
내 피 땀 눈물
내 피 땀 눈물도
내 몸 마음 영혼도
너의 것인 걸 잘 알고 있어
이건 나를 벌받게 할 주문
Peaches and cream
Sweeter than sweet
Chocolate cheeks
and chocolate wings
But 너의 날개는 악마의 것
너의 그 sweet
앞엔 bitter bitter
Kiss me 아파도 돼
어서 날 조여줘
더 이상 아플 수도 없게
Baby 취해도 돼 이제 널 들이켜
목 깊숙이 너란 위스키
내 피 땀 눈물 내 마지막 춤을
다 가져가 가
내 피 땀 눈물 내 차가운 숨을
다 가져가 가
원해 많이 많이 많이 많이
원해 많이 많이 많이 많이
많이 많이
원해 많이 많이 많이 많이
원해 많이 많이 많이 많이
많이 많이
아파도 돼 날 묶어줘
내가 도망칠 수 없게
꽉 쥐고 날 흔들어줘
내가 정신 못 차리게
Kiss me on the lips lips
둘만의 비밀
너란 감옥에 중독돼 깊이
니가 아닌 다른 사람 섬기지 못해
알면서도 삼켜버린 독이 든 성배
내 피 땀 눈물 내 마지막 춤을
다 가져가 가
내 피 땀 눈물 내 차가운 숨을
다 가져가 가
원해 많이 많이 많이 많이
원해 많이 많이 많이 많이
많이 많이
원해 많이 많이 많이 많이
많이 많이
나를 부드럽게 죽여줘
너의 손길로 눈 감겨줘
어차피 거부할 수조차 없어
더는 도망갈 수조차 없어
니가 너무 달콤해 너무 달콤해
너무 달콤해서
내 피 땀 눈물
내 피 땀 눈물"""

wordcloud = WordCloud(font_path="/Library/Fonts/AppleGothic.ttf", 
                                        background_color="white", 
                                        relative_scaling=0.2,
                                        mask=cloud_mask )
wordcloud.generate(text)

print("\t피땀눈물 - 방탄소년단\n")

plt.figure(figsize=(12,12))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()
피땀눈물 - 방탄소년단
masking image
 

2018/07/16

[python] binary search tree

오름차순으로 정렬된 리스트에서 특정한 값의 위치를 찾는 알고리즘이다. 처음 중간의 값을 임의의 값으로 선택하여, 그 값과 찾고자 하는 값의 크고 작음을 비교하는 방식을 채택하고 있다. 처음 선택한 중앙값이 만약 찾는 값보다 크면 그 값은 새로운 최댓값이 되며, 작으면 그 값은 새로운 최솟값이 된다. 검색 원리상 정렬된 리스트에만 사용할 수 있다는 단점이 있지만, 검색이 반복될 때마다 목표값을 찾을 확률은 두 배가 되므로 속도가 빠르다는 장점이 있다.
def bsearch(items, key):
    # recursive function을 독립 시키기 위한 adapter function
    return bs_helper(items, key, -1, len(items))

def bs_helper(items, key, lower, upper):
    # Base condition : 값을 못 찾았을 경우
    if lower + 1 == upper:
        return None
    mid = (lower + upper) // 2
    # 값을 찾았을 경우 return
    if key == items[mid]:
        return mid
    # 아래 쪽에 위치할 경우 lower range 를 검색
    if key < items[mid]:
        return bs_helper(items, key, lower, mid)
    else:
        return bs_helper(items, key, mid, upper)


a = [1, 2, 4, 5, 7, 9, 10, 34, 45, 89, 345]
print(bsearch(a, 5))

[python] check parenthesis matching

import queue

class PaMatch():
    def __init__(self):
        super(PaMatch, self).__init__()
        self.lst = queue.LifoQueue()
        self.check = 0
    
    def push(self, a):
        self.lst.put(a)
        
    def pop(self):
        return self.lst.get()
    
    def checkMatch(self, string):
        for i in range(len(string)):
            if string[i] == "(":
                self.push(i)
            elif string[i] == ")":
                if self.lst.qsize() >= 1:
                    # 첫번째 출력이 아닐 경우 "," 추
                    if self.check > 0:
                        print(",", end="")
                    print("({},{})".format(self.pop(),i), end="")
                    self.check += 1
                # parenthsis가 맞지 않을 경우 남은 자리를 보여주고 종료
                else:
                    print("\nNot matched : {}".format(i), end="")
        # parenthsis가 맞지 않을 경우 남은 자리를 보여주고 종료
        for i in range(self.lst.qsize()):
            print("\nNot matched : {}".format(self.lst.get()), end="")

        print("")
   
#  Good Matching Case
string = "((((A+B)-C)*D)/S*A)"
A = PaMatch()
A.checkMatch(string)

# Not Good Matching Case 1
string2 = "(((((((A+B)-C)*D)/S*A"
B = PaMatch()
B.checkMatch(string2)

# Not Good Matching Case 2
string3 = "((((A+B)-C)*D)))/S*A))))"
C = PaMatch()
C.checkMatch(string3)

(3,7),(2,10),(1,13),(0,18)
(6,10),(5,13),(4,16)
Not matched : 3
Not matched : 2
Not matched : 1
Not matched : 0
(3,7),(2,10),(1,13),(0,14)
Not matched : 15
Not matched : 20
Not matched : 21
Not matched : 22
Not matched : 23

2018/07/14

[python] 공공 Data를 이용한 동네 예보 처리

공공 Data 활용을 위한 service_key 신청은 Link를 참조.

# -*- coding: utf-8 -*-
import datetime as dt
import requests as req
from bs4 import BeautifulSoup

w_items = {"POP":["강수확률", "%"], "PTY":["강수형태", ""], "R06":["6시간 강수량", "mm"], "REH":["습도", "%"], "S06":["6시간 신적설", "cm"], 
           "SKY":["하늘상태", ""], "T3H":["3시간 기온", "°C"], "TMN":["아침 최저 기온", "°C"], "TMX":["낮 최고 기온", "°C"], 
           "UUU":["풍속(동서성분)","m/s"], "VVV":["풍속(남북성분)","m/s"], "WAV":["파고", "m"], "VEC":["풍향", ""], "WSD":["풍속", "m/s"]}
wind_dict = {0:"N",1:"NNE",2:"NE",3:"ENE",4:"E",5:"ESE",6:"SE",7:"SSE",8:"S",9:"SSW",10:"SW",11:"WSW",12:"W",13:"WNW",14:"NW",15:"NNW",16:"N"}
rain_dict = {0:"없음", 1:"비", 2:"진눈깨비", 3:"눈"}

# 가장 최근의 기상청 예보 시간(02:10 이후 3시간 단위) get
def get_rpt_time():
    base_time = dt.datetime.now() - dt.timedelta(hours=2) - dt.timedelta(minutes=10)
    hour = int(base_time.strftime("%H"))
    rehour = str(hour//3*3 + 2).zfill(2)
    return [base_time.strftime("%Y%m%d"), rehour + "00"]

# 풍향 계산용
def get_wind_type(i):
    return wind_dict[(i + 22.5 * 0.5)//22.5]

def get_sky_status(i):
    if i >= 0 and i <= 2: return "맑음"
    elif i >= 3 and i <= 5: return "구름조금"
    elif i >= 6 and i <= 8: return "구름많음"
    elif i >= 9 and i <= 10: return "흐림"

def get_real_value(c, s):
    if c.string == "VEC":
        return get_wind_type(int(s.string))
    elif c.string == "SKY":
        return get_sky_status(int(s.string))
    elif c.string == "PTY":
        return rain_dict[int(s.string)]
    return s.string

# have to change with your service_key
service_key = "MJqwsP2VlmHlaRh0BMwMAtDvhfFu6k59h%2B1Svp2A%......."
nx = 60    # 서울 기준
ny = 127   # 서울 기준

date = get_rpt_time()

base_url = "http://newsky2.kma.go.kr/service/SecndSrtpdFrcstInfoService2/ForecastSpaceData?ServiceKey={}&base_date={}&base_time={}&nx={}&ny={}"
url = base_url.format(service_key, date[0], date[1], nx, ny)

contents = req.get(url)
weather = BeautifulSoup(contents.content, 'lxml-xml')

print("\t **************************************")
print("\t Report Time :", date[0], date[1])
print("\t **************************************")
for item in weather.find_all("item"):
    print("\t", w_items[item.category.string][0], " : ", get_real_value(item.category, item.fcstValue), end = "")
    if w_items[item.category.string][1] != "":
        print(w_items[item.category.string][1])
    else:
        print()
<결과>
         **************************************
         Report Time : 20180715 1100
         **************************************
         강수확률  :  10%
         강수형태  :  없음
         습도  :  50%
         하늘상태  :  맑음
         3시간 기온  :  31°C
         낮 최고 기온  :  33.0°C
         풍속(동서성분)  :  3.1m/s
         풍향  :  WSW
         풍속(남북성분)  :  1.3m/s
         풍속  :  3.4m/s

[python] get current datetime

from datetime import datetime
datetime.today()                # get current date
datetime.today().year        # get current year
datetime.today().month    # get current month
datetime.today().day         # get current day
datetime.today().hour        # get current hour
datetime.today().strftime("%Y/%m/%d %H:%M:%S")  # get current date with format yyyy/mm/dd hh24:mm:ss

[python] all markers in matplotlib.pypolot.scatter

import matplotlib.pyplot as plt
import numpy as np
import matplotlib

markers = {'.': 'point', ',': 'pixel', 'o': 'circle', 'v': 'triangle_down', '^': 'triangle_up', '<': 'triangle_left', '>': 'triangle_right', 
                    '1': 'tri_down', '2': 'tri_up', '3': 'tri_left', '4': 'tri_right', '8': 'octagon', 's': 'square', 'p': 'pentagon', '*': 'star', 
                    'h': 'hexagon1', 'H': 'hexagon2', '+': 'plus', 'x': 'x', 'D': 'diamond', 'd': 'thin_diamond', '|': 'vline', '_': 'hline', 
                    'P': 'plus_filled', 'X': 'x_filled', 0: 'tickleft', 1: 'tickright', 2: 'tickup', 3: 'tickdown', 4: 'caretleft', 5: 'caretright', 
                    6: 'caretup', 7: 'caretdown', 8: 'caretleftbase', 9: 'caretrightbase', 10: 'caretupbase', 11: 'caretdownbase', 
                    'None': 'nothing', None: 'nothing', ' ': 'nothing', '': 'nothing'}

N = 50
x = np.random.rand(N)
y = np.random.rand(N)
area = (30 * np.random.rand(N))**2 

for key, value in markers.items():
    plt.scatter(x, y, s=area, c="g", alpha=0.5, marker=key, label=value)
    plt.legend(loc=1)
    plt.show()







































[art] 백남준 작품 in Korea

어렸을 적 백남준은 매우 유복한 환경에서 자랐다. 집에는 피아노나 전축은 물론 당시에 서울에 딱 두 대 밖에 없었던 캐딜락도 있었고, 해방 전에 유치원(애국유치원)에 다녔으며 한국 전쟁의 그 아비규환 속에서도 파인애플을 먹을 정도의 부잣집이었다. 그의 어머니는 '돈은 물 쓰듯 쓰는 거다'라고 했다고 한다. 조부 백윤수는 청나라 비단을 독점 판매했던 거부로, 종로5가와 동대문시장 일대의 포목상 절반이 그의 것이었고, 국상 때 만조백관의 상복과 제복을 일체 도맡았을 정도로 섬유업계의 막강한 실력자였다. 후에 그는 직물, 대부업, 제약회사 등을 세웠고, 재산은 한성은행 자본금의 3배에 달했다.
백남준은 당시 상류층만 다니던 수송국민학교경기공립중학교를 다녔는데, 해방 전 그 시절에 학교에는 풀장과 영사기가 있어서, 당시 학부모였던 대한극장 사장이 학교에서 직접 영화를 상영하기도 했다고 한다. 또한 경기중학교 음악교사로, 후에 이대 음대학장을 지냈던 신재덕에게 피아노를, 작곡가 이건우에게 작곡을 배웠다. 1949년에는 이승만 대통령의 부탁으로 무기구입을 위해 홍콩으로 갔다는 설이 있는 부친 백낙승씨의 통역으로 따라가 홍콩의 로이덴 스쿨로 전학한다. 백남준은 이때 영어와 중국어를 배우게 된다.  - 나무위키

1. 단군


3. 거북선 


2018/07/13

[bash] while in one line

while true;do ls -l; echo "---------------------------"; sleep 5;done

useful links


Visual Studio Code - python
https://code.visualstudio.com/docs/python/python-tutorial


운영체제 - 경성대학교 양희재 교수

컴퓨터 구조 - 숭실대학교 김병기 교수

소프트웨어 공학 - 동국대학교 최은만 교수

알고리즘 - 명지대학교 이충기 교수

데이터베이스 - 이화여자대학교 용환승 교수

수리 통계학 - 국민대학교 강주성 교수

선형 대수 - 국민대학교 이옥연 교수

선형 대수 한양대학교 이상화 교수

확률 및 통계 - 한양대학교 이상화 교수

Deep Learning 정리 Blog

DataScience School

Python 연습 Site

Python Data Science Handbook

수학 관련 정리

Thinker with a Neutal Network

2018/07/08

docker Oracle 12c

Oracle Standard Edition 12c Release 1


Oracle Standard Edition 12c Release 1 on Ubuntu
This Dockerfile is a trusted build of Docker Registry.

Installation

docker pull sath89/oracle-12c
Run with 8080 and 1521 ports opened:
docker run -d -p 8080:8080 -p 1521:1521 sath89/oracle-12c
Run with data on host and reuse it:
docker run -d -p 8080:8080 -p 1521:1521 -v /my/oracle/data:/u01/app/oracle sath89/oracle-12c
Run with Custom DBCA_TOTAL_MEMORY (in Mb):
docker run -d -p 8080:8080 -p 1521:1521 -v /my/oracle/data:/u01/app/oracle -e DBCA_TOTAL_MEMORY=1024 sath89/oracle-12c
Connect database with following setting:
hostname: localhost
port: 1521
sid: xe
service name: xe
username: system
password: oracle
To connect using sqlplus:
sqlplus system/oracle@//localhost:1521/xe

Password for SYS & SYSTEM:
oracle
Connect to Oracle Application Express web management console with following settings:
http://localhost:8080/apex
workspace: INTERNAL
user: ADMIN
password: 0Racle$
Apex upgrade up to v 5.*
docker run -it --rm --volumes-from ${DB_CONTAINER_NAME} --link ${DB_CONTAINER_NAME}:oracle-database -e PASS=YourSYSPASS sath89/apex install
Details could be found here: https://github.com/MaksymBilenko/docker-oracle-apex
Connect to Oracle Enterprise Management console with following settings:
http://localhost:8080/em
user: sys
password: oracle
connect as sysdba: true
By Default web management console is enabled. To disable add env variable:
docker run -d -e WEB_CONSOLE=false -p 1521:1521 -v /my/oracle/data:/u01/app/oracle sath89/oracle-12c
#You can Enable/Disable it on any time
Start with additional init scripts or dumps:
docker run -d -p 1521:1521 -v /my/oracle/data:/u01/app/oracle -v /my/oracle/init/SCRIPTSorSQL:/docker-entrypoint-initdb.d sath89/oracle-12c
By default Import from docker-entrypoint-initdb.d is enabled only if you are initializing database (1st run).
To customize dump import use IMPDP_OPTIONS env variable like -e IMPDP_OPTION="REMAP_TABLESPACE=FOO:BAR"
To run import at any case add -e IMPORT_FROM_VOLUME=true
In case of using DMP imports dump file should be named like ${IMPORT_SCHEME_NAME}.dmp
User credentials for imports are ${IMPORT_SCHEME_NAME}/${IMPORT_SCHEME_NAME}
If you have an issue with database init like DBCA operation failed, please reffer to this issue
TODO LIST
  • Web management console HTTPS port
  • Add functionality to run custom scripts on startup, for example User creation
  • Add Parameter that would setup processes amount for database (Currently by default processes=300)
  • Spike with clustering support
  • Spike with DB migration from 11g
In case of any issues please post it here.

[c] Fibonacci

#include 

int main(){
    unsigned long a,b,cnt,i,n1,n2,n;

    scanf("%ld %ld",&a, &b);

    n2=1;
    n1=2;
    cnt=0;

    for(i=3;i=a && n<=b)
        {   
            cnt++;
            printf("cnt %ld : %ld\n", cnt, n );
        }   
        n2 = n1; 
        n1 = n;
    }   

    printf("%ld\n", cnt);
}

[c] Mine Sweep

#include 
#include 
#include 
#include 

#define debug_

char mine[100][100];
int nmax = 0, mmax = 0;

int getMin(int a, int b){ 
    if(a>b)   
        return b;
    else    
        return a;
}

int getMax(int a, int b){ 
    if(a>b)
        return a;
    else
        return b;
}

int getCnt(int x, int y){ 
    int i = 0, j = 0, cnt = 0;

    for(i=getMax(x-1, 0);i<=getMin(x+1, nmax);i++){
        for(j=getMax(y-1, 0);j<=getMin(y+1, mmax);j++){
            if(mine[i][j] == '*'){
                cnt ++; 
            }   
#ifdef debug
            printf("---- getCnt : i:%d, j:%d, cnt:%d\n", i, j, cnt); 
#endif
        }   
    }   
    return cnt;
}

int main(){
    char buf[101];
    int s, i, j, n, m;

    s = 1; /* Set counter */
    n = 0; /* Row counter in set */
    m = 0; /* Column counter in row */
    while(gets(buf)){

        if(strlen(buf) < 1)
            break;

        if(n == 0){ 
            nmax = buf[0] - '0';
            mmax = buf[2] - '0';
#ifdef debug
            printf("---- nmax : %d, mmax : %d\n", nmax, mmax);
#endif
            if(nmax == 0 && mmax == 0)
                break;
        }
        else{
            for(j=0;j < mmax;j++){
                mine[n-1][j] = buf[j];
#ifdef debug
                printf("---- n : %d, m : %d, char : %c\n", n, j, mine[n-1][j]);
#endif
            }
        }

        if(n == nmax){
            printf("Field #%d\n", s);
            for(i=0;i < nmax;i++){
                for(j=0;j< mmax;j++){
                    if(mine[i][j] == '*')
                        printf("%c",'*');
                    else
                        printf("%d",getCnt(i, j));

                    if(j == (mmax - 1))
                        printf("\n");
                }
            }
            s++;
            n = 0;
            memset(mine,'\0',sizeof(mine));
        }
        else{
            n++;
        }
    }

    return 0;
}

[c] Stack


#include 
#include 
#define MAXSIZE 100 

typedef struct stack{
    int stk[MAXSIZE];
    int top;
} STACK;


void Push(int x, STACK *s){
    int num;
    s->top ++; 
    printf("Push %d\n", s->top);
    s->stk[s->top] = x;
    return;
}

int Pop(STACK *s){
    int num;
    printf("Pop %d\n", s->top);
    num = s->stk[s->top];
    s->top --; 
    return num;
}

void Init(STACK *s){
    s->top = -1; 
    printf("Init %d\n", s->top);
    return;
}

int main(){

    STACK *s = (STACK *)malloc(sizeof(STACK));

    Init(s);

    Push(1, s); 
    Push(2, s); 
    Push(3, s); 

    printf("%d\n", Pop(s));
    printf("%d\n", Pop(s));
    printf("%d\n", Pop(s));

}

2018/07/07

[c] learn-c.org


Welcome

Welcome to the learn-c.org free interactive C tutorial.
Whether you are an experienced programmer or not, this website is intended for everyone who wishes to learn the C programming language.
There is no need to download anything - Just click on the chapter you wish to begin from, and follow the instructions. Good luck!


http://www.learn-c.org