2020. március 10., kedd

ODI + jPython

Az ODI (Oracle Data Integrator) és python kapcsolata a JPython kiterjesztett funkció.

Alavetően SQL, PL-SQL szelven kommunikál a töltő MAP fejlesztés és a hozzájuk kapcsolódó procedurákban,  knowledge modul-oknál.


Hogyan is néz ez ki az ODI-ban?










Mi is a Jpython?

Javahoz javaban fedjlesztett python értelmezőről van szó. Lényegében egy JAR állomány, amelybe a 2.7.1 verziójú (hát nem a legfrissebb) python elhelyezkedik. 

Használatakor a JAVA classpath-ba szerepeltetni kell a jpython jart.

set CLASSPATH=C:\path\to\my\app\myapp.jar;jython.jar;%CLASSPATH%

Hogyan néz ki egy egyszerű kalkulátor ebben:

Futtatás szintaktikája: 

java -jar jython.jar {minta.py}

kl1.py tartalma:


# hello world
print("Hello world!")


# eljárás definició method
def add(a, b):
    print("call add()")
    return a + b
# eljárás meghívása
print(add(1, 2))


# két string összefüzése
print("abcdefghijklmnopqrstuvexyz" + '1234567890')

Futtatás CMD ablakban:

java -jar jython-standalone-2.7.1.jar kl1.py



2. Példa

kl3.py tartalma:


#coding=utf-8
def section_1():
    p = (4, 5)
    x, y = p
    print(x)
    print(y)

    data = ['ACME', 50, 19.1, (2012, 12, 21)]
    name, shares, price, date = data
    print(name)
    print(date)
    name, shares, price, (year, mon, day) = data
    print(year)
    print(mon)

    # ????????????
    s = "Hello"
    a,b,c,d,e = s
    print(a)
    print(e)

    # ?????????????
    _, shares, price, _ = data
    print(shares)
    print(price)

def section_2():
    '''
    # ??*????????
    record = ('Dave', 'dave@example.com', '777-555-1123', '888-444-2342')
    name, email, *phone_numbers = record
    print(name)
    print(phone_numbers)
    def do_foo(x, y):
        print('foo', x, y)
    def do_bar(s):
        print('bar', s)
    
    records = [('foo', 1, 2), ('bar', 'hello'), ('foo', 3, 4)]
    for tag, *args in records:
        if tag == 'fooo':
            do_foo(*args)
        elif tag == 'bar':
            do_bar(*args)
    
    # ??_???????????
    data = ('ACME', 50, 123.45, (12, 18, 2012))
    name, *_, (*_, year) = data
    print(name)
    print(year)
    '''

from collections import deque
def section_3():
    def search(lines, pattern, history=5):
        previous_lines = deque(maxlen=history)
        for line in lines:
            if pattern in line:
                yield line, previous_lines
            previous_lines.append(line)
    
    with open('/Users/liuqiang/code/Python/Python-cookbook/???:???????/somefile.txt') as f:
        for line, prevlines in search(f, 'python', 5):
            for pline in prevlines:
                print(pline)
            print(line)
            print('-' * 20)

import heapq
def section_4():
    nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
    print(heapq.nlargest(3, nums))
    print(heapq.nsmallest(3, nums))

    portfolio = [
    {'name': 'IBM', 'shares': 100, 'price': 91.1},
    {'name': 'AAPL', 'shares': 50, 'price': 543.22},
    {'name': 'FB', 'shares': 200, 'price': 21.09},
    {'name': 'HPQ', 'shares': 35, 'price': 31.75},
    {'name': 'YHOO', 'shares': 45, 'price': 16.35},
    {'name': 'ACME', 'shares': 75, 'price': 115.65}
    ]
    cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
    expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
    print(cheap)
    print(expensive)

from collections import defaultdict
def section_5():
    d = defaultdict(list)
    d['a'].append(1)
    d['a'].append(2)
    d['b'].append(4)
    print(d)
    d = defaultdict(set)
    d['a'].add(1)
    d['a'].add(2)
    d['b'].add(4)
    print(d)

    pairs = {'a' : [1, 2, 3], 'b' : [4, 5]}
    d = {}
    for key, value in pairs.items():
        if key not in d:
            d[key] = []
        d[key].append(value)
    print(d)

    # ??defaultdict????key???????if????
    d = defaultdict(list)
    for key, value in pairs.items():
        d[key].append(value)
    print(d)

from collections import OrderedDict
import json
def section_7():
    # OrderedDict????????????
    d = OrderedDict()
    d['foo'] = 1
    d['bar'] = 2
    d['spam'] = 3
    d['grok'] = 4
    for key in d:
        print(key, d[key])
    
    str = json.dumps(d)
    print(str)

def section_8():
    prices = {
    'ACME': 45.23,
    'AAPL': 612.78,
    'IBM': 205.55,
    'HPQ': 37.20,
    'FB': 10.75
    }
    # zip()????????(key,value)????
    min_price = min(zip(prices.values(), prices.keys()))
    print(min_price)
    max_price = max(zip(prices.values(), prices.keys()))
    print(max_price)
    prices_sorted = sorted(zip(prices.values(), prices.keys()))
    print(prices_sorted)

    prices_and_names = zip(prices.values(), prices.keys())
    print(min(prices_and_names))
    # error:zip()??????????????????
    # print(max(prices_and_names)) 

    # ???????????
    min_price_value = min(prices.values())
    max_price_value = max(prices.values())
    print(min_price_value)
    print(max_price_value)

    # ??????????key
    min_price_key = min(prices, key=lambda k: prices[k])
    max_price_key = max(prices, key=lambda k: prices[k])
    print(min_price_key)
    print(max_price_key)

def section_9():
    a = {
        'x' : 1,
        'y' : 2,
        'z' : 3,
    }

    b = {
        'w' : 10,
        'x' : 11,
        'y' : 2
    }
    #dict?????????????
    common_keys = a.keys() & b.keys()
    different_keys = a.keys() - b.keys()
    union_keys = a.keys() | b.keys()
    common_keys_and_values = a.items() & b.items()
    print(common_keys)
    print(different_keys)
    print(union_keys)
    print(common_keys_and_values)

    filter_dict = {key:a[key] for key in a.keys() - {'z', 'w'}}
    print(filter_dict)

#??????
def section_10():
    def dedupe(items):
        seen = set()
        for item in items:
            if item not in seen:
                yield item
                seen.add(item)
    
    a = [1, 5, 2, 1, 9, 1, 5, 10]
    l = list(dedupe(a))
    print(l)

    def dedupe_not_hashable(items, key=None):
        seen = set()
        for item in items:
            val = item if key is None else key(item)
            if val not in seen:
                yield item
                seen.add(val)
    
    a = [ {'x':1, 'y':2}, {'x':1, 'y':3}, {'x':1, 'y':2}, {'x':2, 'y':4}]
    l = list(dedupe_not_hashable(a, key=lambda d: (d['x'], d['y'])))
    print(l)

def section_11():
    record = '....................100 .......513.25 ..........'
    cost = int(record[20:23]) * float(record[31:37])
    print(cost)
    #?????????
    SHARES = slice(20, 23)
    PRICE = slice(31, 37)
    cost = int(record[SHARES]) * float(record[PRICE])
    print(cost)

    items = [0, 1, 2, 3, 4, 5, 6]
    a = slice(2, 4)
    print(items[2:4])
    print(items[a])
    items[a] = [10,11]
    print(items)
    del items[a]
    print(items)

    #????start,stop?step????
    a = slice(5, 50, 2)
    print(a.start)

from collections import Counter
def section_12():
    words = [
        'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
        'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
        'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
        'my', 'eyes', "you're", 'under'
    ]

    word_counts = Counter(words)
    top_three = word_counts.most_common(3)
    print(top_three)
    # Counter???????????
    morewords = ['why','are','you','not','looking','in','my','eyes']
    a = Counter(words)
    b = Counter(morewords)
    c = a + b 
    print(c)
    d = a - b
    print(d)

from operator import itemgetter
def section_13():
    rows = [
        {'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
        {'fname': 'David', 'lname': 'Beazley', 'uid': 1002},
        {'fname': 'John', 'lname': 'Cleese', 'uid': 1001},
        {'fname': 'Big', 'lname': 'Jones', 'uid': 1004}
    ]
    rows_by_fname = sorted(rows, key=itemgetter('fname'))
    rows_by_uid = sorted(rows, key=itemgetter('uid'))
    rows_by_lfname = sorted(rows, key=itemgetter('lname','fname'))
    print(rows_by_fname)
    print(rows_by_uid)
    print(rows_by_lfname)

class User:
    def __init__(self, user_id):
        self.user_id = user_id
    def __repr__(self):
        return 'User({})'.format(self.user_id)
    
from operator import attrgetter
def section_14():
    users = [User(23), User(3), User(99)]
    print(users)
    print(sorted(users, key=lambda u: u.user_id))
    print(sorted(users, key=attrgetter('user_id')))

def main():
    section_1()    
    section_11()
    section_12()
    section_13()
    section_14()


Futtatás CMD ablakban:

java -jar jython-standalone-2.7.1.jar kl3.py





Példa3:


from javax.swing import JFrame, JMenuBar, JMenu, JMenuItem, JTextField
from java.awt import BorderLayout
from javax.swing import JOptionPane
frame = JFrame("Dialog example")
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setLocation(100,100)
frame.setSize(400,300)
frame.setLayout(BorderLayout())

def OnClick(event):
   str = event.getActionCommand()
   if str == 'Message':
      JOptionPane.showMessageDialog(frame,"this is a sample message dialog")
   if str == "Input":
      x = JOptionPane.showInputDialog(frame,"Enter your name")
      txt.setText(x)
   if str == "Confirm":
      s = JOptionPane.showConfirmDialog (frame, "Do you want to continue?")
      if s == JOptionPane.YES_OPTION:
         txt.setText("YES")
      if s == JOptionPane.NO_OPTION:
         txt.setText("NO")
      if s == JOptionPane.CANCEL_OPTION:
         txt.setText("CANCEL")

bar = JMenuBar()
frame.setJMenuBar(bar)

file = JMenu("File")
msgbtn = JMenuItem("Message",actionPerformed = OnClick)
conbtn = JMenuItem("Confirm",actionPerformed = OnClick)
inputbtn = JMenuItem("Input",actionPerformed = OnClick)
file.add(msgbtn)
file.add(conbtn)
file.add(inputbtn)
bar.add(file)
txt = JTextField(10)
frame.add(txt, BorderLayout.SOUTH)

frame.setVisible(True)






Hogyan néz ki egy ODI-s JPyton hibaüzenet?


at org.python.core.Py.IndexError(Py.java:210)
at org.python.core.SequenceIndexDelegate.checkIdxAndGetItem(SequenceIndexDelegate.java:63)
at org.python.core.PySequence.seq___getitem__(PySequence.java:305)
at org.python.core.PySequence.__getitem__(PySequence.java:301)
at org.python.pycode._pyx0.f$0(<string>:42)
at org.python.pycode._pyx0.call_function(<string>)
at org.python.core.PyTableCode.call(PyTableCode.java:165)
at org.python.core.PyCode.call(PyCode.java:18)
at org.python.core.Py.runCode(Py.java:1204)
at org.python.core.Py.exec(Py.java:1248)
at org.python.util.PythonInterpreter.exec(PythonInterpreter.java:172)
at org.apache.bsf.engines.jython.JythonEngine.exec(JythonEngine.java:144)



KNIME-nek is van ilyene  : link


További info linkek:  jython.org 



Nincsenek megjegyzések:

Megjegyzés küldése

Labirintus generálás ás megoldás python

 A labirintus generálás és megoldás módszerek: Kruskal féle Prim féle rekurzív Backtracker Aldous-Broder növekvő fa Hunt és ölő Wil...