hexsha stringlengths 40 40 | size int64 4 996k | ext stringclasses 8
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 4 996k | avg_line_length float64 1.33 58.2k | max_line_length int64 2 323k | alphanum_fraction float64 0 0.97 | content_no_comment stringlengths 0 946k | is_comment_constant_removed bool 2
classes | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f7f8929f165d4850ccdc7506ff2809e277e3476a | 1,496 | py | Python | thinc/layers/with_flatten.py | TheVinhLuong102/thinc | 7b54f728ddec7765a1d8a5e553d4b4b90b9edaec | [
"MIT"
] | 2,542 | 2016-10-20T07:02:59.000Z | 2022-03-30T20:18:35.000Z | thinc/layers/with_flatten.py | TheVinhLuong102/thinc | 7b54f728ddec7765a1d8a5e553d4b4b90b9edaec | [
"MIT"
] | 453 | 2016-10-19T21:09:35.000Z | 2022-03-31T11:01:15.000Z | thinc/layers/with_flatten.py | TheVinhLuong102/thinc | 7b54f728ddec7765a1d8a5e553d4b4b90b9edaec | [
"MIT"
] | 265 | 2016-11-14T14:53:58.000Z | 2022-03-31T02:25:24.000Z | from typing import Tuple, Callable, Sequence, Any, List, TypeVar
from ..model import Model
from ..config import registry
from ..types import Array2d, List2d
ItemT = TypeVar("ItemT")
InT = Sequence[Sequence[ItemT]]
OutT = List2d
@registry.layers("with_flatten.v1")
def with_flatten(layer: Model) -> Model[InT, OutT]:
return Model(f"with_flatten({layer.name})", forward, layers=[layer], init=init)
def forward(
model: Model[InT, OutT], Xnest: InT, is_train: bool
) -> Tuple[OutT, Callable]:
layer: Model[Sequence[Any], Array2d] = model.layers[0]
Xflat: Sequence[Any] = _flatten(Xnest)
Yflat, backprop_layer = layer(Xflat, is_train)
# Get the split points. We want n-1 splits for n items.
arr = layer.ops.asarray1i([len(x) for x in Xnest[:-1]])
splits = arr.cumsum()
Ynest = layer.ops.xp.split(Yflat, splits, axis=0)
def backprop(dYnest: OutT) -> InT:
# I think the input/output types might be wrong here?
dYflat = model.ops.flatten(dYnest) # type: ignore
dXflat = backprop_layer(dYflat)
dXnest = layer.ops.xp.split(dXflat, splits, axis=-1)
return dXnest
return Ynest, backprop
def _flatten(nested: InT) -> List[ItemT]:
flat: List[ItemT] = []
for item in nested:
flat.extend(item)
return flat
def init(model, X=None, Y=None):
model.layers[0].initialize(
_flatten(X) if X is not None else None,
model.layers[0].ops.xp.hstack(Y) if Y is not None else None,
)
| 29.333333 | 83 | 0.661765 | from typing import Tuple, Callable, Sequence, Any, List, TypeVar
from ..model import Model
from ..config import registry
from ..types import Array2d, List2d
ItemT = TypeVar("ItemT")
InT = Sequence[Sequence[ItemT]]
OutT = List2d
@registry.layers("with_flatten.v1")
def with_flatten(layer: Model) -> Model[InT, OutT]:
return Model(f"with_flatten({layer.name})", forward, layers=[layer], init=init)
def forward(
model: Model[InT, OutT], Xnest: InT, is_train: bool
) -> Tuple[OutT, Callable]:
layer: Model[Sequence[Any], Array2d] = model.layers[0]
Xflat: Sequence[Any] = _flatten(Xnest)
Yflat, backprop_layer = layer(Xflat, is_train)
arr = layer.ops.asarray1i([len(x) for x in Xnest[:-1]])
splits = arr.cumsum()
Ynest = layer.ops.xp.split(Yflat, splits, axis=0)
def backprop(dYnest: OutT) -> InT:
dYflat = model.ops.flatten(dYnest)
dXflat = backprop_layer(dYflat)
dXnest = layer.ops.xp.split(dXflat, splits, axis=-1)
return dXnest
return Ynest, backprop
def _flatten(nested: InT) -> List[ItemT]:
flat: List[ItemT] = []
for item in nested:
flat.extend(item)
return flat
def init(model, X=None, Y=None):
model.layers[0].initialize(
_flatten(X) if X is not None else None,
model.layers[0].ops.xp.hstack(Y) if Y is not None else None,
)
| true | true |
f7f89382bedd64a68b7bd7ea27882511d8eab867 | 3,192 | py | Python | pset4/dist/dnaseq.py | GaryLai91/mit-ocw-6006 | 0e8b69b08c7b54a83fcb90ea11bf2d7cfd87d2d7 | [
"MIT"
] | null | null | null | pset4/dist/dnaseq.py | GaryLai91/mit-ocw-6006 | 0e8b69b08c7b54a83fcb90ea11bf2d7cfd87d2d7 | [
"MIT"
] | null | null | null | pset4/dist/dnaseq.py | GaryLai91/mit-ocw-6006 | 0e8b69b08c7b54a83fcb90ea11bf2d7cfd87d2d7 | [
"MIT"
] | null | null | null | #!/usr/bin/env python2.7
import unittest
from dnaseqlib import *
### Utility classes ###
# Maps integer keys to a set of arbitrary values.
class Multidict:
# Initializes a new multi-value dictionary, and adds any key-value
# 2-tuples in the iterable sequence pairs to the data structure.
def __init__(self, pairs=[]):
self.dic = {}
for i in pairs:
self.put(i[0], i[1])
# Associates the value v with the key k.
def put(self, k, v):
try:
self.dic[k].append(v)
except KeyError:
self.dic[k] = [v,]
# Gets any values that have been associated with the key k; or, if
# none have been, returns an empty sequence.
def get(self, k):
if k in self.dic:
return self.dic[k]
return []
# Given a sequence of nucleotides, return all k-length subsequences
# and their hashes. (What else do you need to know about each
# subsequence?)
def subsequenceHashes(seq, k):
try:
assert k > 0
pos = 0
subseq = ''
for i in range(k):
subseq += seq.next()
roll = RollingHash(subseq)
while True:
yield (roll.current_hash(), (pos, subseq))
previtem = subseq[0]
subseq = subseq[1:] + seq.next()
roll.slide(previtem, subseq[-1])
pos += 1
except StopIteration:
return
# Similar to subsequenceHashes(), but returns one k-length subsequence
# every m nucleotides. (This will be useful when you try to use two
# whole data files.)
def intervalSubsequenceHashes(seq, k, m):
assert m >= k
try:
pos = 0
while True:
subseq = ''
for i in range(k):
subseq += seq.next()
roll = RollingHash(subseq)
yield (roll.current_hash(), (pos, subseq))
for i in range(m-k):
seq.next()
pos += m
except StopIteration:
return
# Searches for commonalities between sequences a and b by comparing
# subsequences of length k. The sequences a and b should be iterators
# that return nucleotides. The table is built by computing one hash
# every m nucleotides (for m >= k).
def getExactSubmatches(a, b, k, m):
#table = Multidict(subsequenceHashes(a, k))
table = Multidict(intervalSubsequenceHashes(a, k, m))
for hashval, (bpos, bsubseq) in subsequenceHashes(b, k):
for apos, asubseq in table.get(hashval):
if asubseq != bsubseq:
continue
yield (apos, bpos)
return
if __name__ == '__main__':
if len(sys.argv) != 4:
print 'Usage: {0} [file_a.fa] [file_b.fa] [output.png]'.format(sys.argv[0])
sys.exit(1)
# The arguments are, in order: 1) Your getExactSubmatches
# function, 2) the filename to which the image should be written,
# 3) a tuple giving the width and height of the image, 4) the
# filename of sequence A, 5) the filename of sequence B, 6) k, the
# subsequence size, and 7) m, the sampling interval for sequence
# A.
compareSequences(getExactSubmatches, sys.argv[3], (500,500), sys.argv[1], sys.argv[2], 8, 100)
| 31.92 | 98 | 0.600251 |
import unittest
from dnaseqlib import *
lf, pairs=[]):
self.dic = {}
for i in pairs:
self.put(i[0], i[1])
def put(self, k, v):
try:
self.dic[k].append(v)
except KeyError:
self.dic[k] = [v,]
def get(self, k):
if k in self.dic:
return self.dic[k]
return []
def subsequenceHashes(seq, k):
try:
assert k > 0
pos = 0
subseq = ''
for i in range(k):
subseq += seq.next()
roll = RollingHash(subseq)
while True:
yield (roll.current_hash(), (pos, subseq))
previtem = subseq[0]
subseq = subseq[1:] + seq.next()
roll.slide(previtem, subseq[-1])
pos += 1
except StopIteration:
return
def intervalSubsequenceHashes(seq, k, m):
assert m >= k
try:
pos = 0
while True:
subseq = ''
for i in range(k):
subseq += seq.next()
roll = RollingHash(subseq)
yield (roll.current_hash(), (pos, subseq))
for i in range(m-k):
seq.next()
pos += m
except StopIteration:
return
def getExactSubmatches(a, b, k, m):
table = Multidict(intervalSubsequenceHashes(a, k, m))
for hashval, (bpos, bsubseq) in subsequenceHashes(b, k):
for apos, asubseq in table.get(hashval):
if asubseq != bsubseq:
continue
yield (apos, bpos)
return
if __name__ == '__main__':
if len(sys.argv) != 4:
print 'Usage: {0} [file_a.fa] [file_b.fa] [output.png]'.format(sys.argv[0])
sys.exit(1)
compareSequences(getExactSubmatches, sys.argv[3], (500,500), sys.argv[1], sys.argv[2], 8, 100)
| false | true |
f7f8963e1c14290a0de48e6e2f977bec8f04fd1b | 4,364 | py | Python | script/main.py | zzzzls/BeijingSubwayAppointmentSystem | 68cd3fec1b75574da02014c7e8e16b1d812e1418 | [
"MIT"
] | 1 | 2021-06-30T09:36:44.000Z | 2021-06-30T09:36:44.000Z | script/main.py | zzzzls/BeijingSubwayAppointmentSystem | 68cd3fec1b75574da02014c7e8e16b1d812e1418 | [
"MIT"
] | 1 | 2021-07-01T06:40:33.000Z | 2021-09-23T07:53:44.000Z | script/main.py | zzzzls/BeijingSubwayAppointmentSystem | 68cd3fec1b75574da02014c7e8e16b1d812e1418 | [
"MIT"
] | null | null | null | """
北京地铁预约进站 (沙河,天通苑,草房) 辅助抢票系统
@author: zzzzls
@create: 2021-06-17
@version: 0.0.1
"""
import sys
from os.path import abspath,dirname
sys.path.append(dirname(dirname(abspath(__file__))))
import json
from script.settings import *
from datetime import date, timedelta
import httpx
import asyncio
class TicketSecKill:
def __init__(self):
param = sys.argv[1:]
# authorization = input('请输入您的authorization:')
ts = param[0]
authorization = param[1]
# authorization = 'NWYzZWE4MWYtMDk1MS00Njc3LThlZDAtNzk4MDM3ZTMwM2VkLDE2MjQ2NDMyNTA2MjUsTSthNEJqQVhzUWQ1YUdBc0M0bHo4KzBKaXBBPQ=='
self.headers = DEFAULT_HEADERS.copy()
self.headers['authorization'] = authorization
self.client = httpx.Client(headers=self.headers)
self.station, self.route_line = self.choice_station()
self.seckill_date = self.choice_date()
self.time_slot = self._get_time_solt(ts)
def __del__(self):
self.client.close()
def choice_station(self):
"""选择预约站点"""
# station_num = input('请输入站点编号 ==> 1、沙河站 2、天通苑站 3、草房站 : ')
station_num = '1'
station = STATION_MAP.get(station_num)['station_name']
line = STATION_MAP.get(station_num)['line_name']
print(f'==== {station} 选择成功!')
return station, line
def choice_date(self):
"""选择抢票的日期"""
# seckill_date_str = input('请输入要抢票的日期[YYYY-mm-dd]:')
seckill_date_str = (date.today() + timedelta(days=1)).strftime('%Y-%m-%d') # 获取明天日期
year, month, day = seckill_date_str.split('-')
seckill_date = date(int(year), int(month), int(day))
if 0 <= seckill_date.weekday() <= 4:
return seckill_date.strftime('%Y%m%d')
else:
raise ValueError(f'{seckill_date_str} 不是工作日')
def _get_system_time(self):
"""
获取系统时间
"""
res = self.client.get(
url=URL_MAP['GetSystemTime']
)
return res
def _get_balance(self):
"""
查询余票
"""
data = {"timeSlot": "0630-0930", "stationName": self.station,
"enterDates": [self.seckill_date]}
res = self.client.post(URL_MAP['GetBalance'], json=data)
return res
def _get_appointmentList(self):
"""
查询预约到的票
"""
res = self.client.post(URL_MAP['GetAppointmentList'])
return res
def _get_time_solt(self, u_time, t_buffer=10):
"""
生成抢票时间段
@u_time: str, 订票时间
@t_buffer: int, 缓冲时间
"""
res = []
time_delta_lst = [630, 640, 650, 700, 710, 720, 730, 740,
750, 800, 810, 820, 830, 840, 850, 900, 910, 920, 930]
n = int(u_time.lstrip('0').replace(':', ''))
time_delta_lst.append(n)
time_delta_lst.sort()
index = time_delta_lst.index(n)
for i in (-2, -1, 1, 2):
try:
assert index+i >= 0
item = time_delta_lst[index+i]
res.append(f'0{str(item)[0]}{str(item)[1:]}')
except (IndexError, AssertionError):
continue
# TODO 此处暂返回一个时段
return [f'{res[i]}-{res[i+1]}' for i in range(len(res)-1)][0]
def gen_data(self):
"""
生成请求的参数
"""
for _ in range(420):
data = {"lineName": self.route_line, "snapshotWeekOffset": 0, "stationName": self.station,
"enterDate": self.seckill_date, "snapshotTimeSlot": "0630-0930", "timeSlot": self.time_slot}
yield data
async def _create_appointment(self):
"""
开始抢票
"""
gd = self.gen_data()
async with httpx.AsyncClient(headers=self.headers) as async_client:
for data in gd:
print(json.dumps(data))
r = await async_client.post(URL_MAP['CreateAppointment'], json=data)
if r and r.status_code == httpx.codes.ok:
response = r.json()
if response.get('appointmentId'):
print('===抢票成功===', response)
break
print(response)
print('next....')
else:
print('===抢票失败===')
t = TicketSecKill()
asyncio.get_event_loop().run_until_complete(t._create_appointment())
| 31.395683 | 136 | 0.559349 | import sys
from os.path import abspath,dirname
sys.path.append(dirname(dirname(abspath(__file__))))
import json
from script.settings import *
from datetime import date, timedelta
import httpx
import asyncio
class TicketSecKill:
def __init__(self):
param = sys.argv[1:]
ts = param[0]
authorization = param[1]
self.headers = DEFAULT_HEADERS.copy()
self.headers['authorization'] = authorization
self.client = httpx.Client(headers=self.headers)
self.station, self.route_line = self.choice_station()
self.seckill_date = self.choice_date()
self.time_slot = self._get_time_solt(ts)
def __del__(self):
self.client.close()
def choice_station(self):
station_num = '1'
station = STATION_MAP.get(station_num)['station_name']
line = STATION_MAP.get(station_num)['line_name']
print(f'==== {station} 选择成功!')
return station, line
def choice_date(self):
seckill_date_str = (date.today() + timedelta(days=1)).strftime('%Y-%m-%d')
year, month, day = seckill_date_str.split('-')
seckill_date = date(int(year), int(month), int(day))
if 0 <= seckill_date.weekday() <= 4:
return seckill_date.strftime('%Y%m%d')
else:
raise ValueError(f'{seckill_date_str} 不是工作日')
def _get_system_time(self):
res = self.client.get(
url=URL_MAP['GetSystemTime']
)
return res
def _get_balance(self):
data = {"timeSlot": "0630-0930", "stationName": self.station,
"enterDates": [self.seckill_date]}
res = self.client.post(URL_MAP['GetBalance'], json=data)
return res
def _get_appointmentList(self):
res = self.client.post(URL_MAP['GetAppointmentList'])
return res
def _get_time_solt(self, u_time, t_buffer=10):
res = []
time_delta_lst = [630, 640, 650, 700, 710, 720, 730, 740,
750, 800, 810, 820, 830, 840, 850, 900, 910, 920, 930]
n = int(u_time.lstrip('0').replace(':', ''))
time_delta_lst.append(n)
time_delta_lst.sort()
index = time_delta_lst.index(n)
for i in (-2, -1, 1, 2):
try:
assert index+i >= 0
item = time_delta_lst[index+i]
res.append(f'0{str(item)[0]}{str(item)[1:]}')
except (IndexError, AssertionError):
continue
return [f'{res[i]}-{res[i+1]}' for i in range(len(res)-1)][0]
def gen_data(self):
for _ in range(420):
data = {"lineName": self.route_line, "snapshotWeekOffset": 0, "stationName": self.station,
"enterDate": self.seckill_date, "snapshotTimeSlot": "0630-0930", "timeSlot": self.time_slot}
yield data
async def _create_appointment(self):
gd = self.gen_data()
async with httpx.AsyncClient(headers=self.headers) as async_client:
for data in gd:
print(json.dumps(data))
r = await async_client.post(URL_MAP['CreateAppointment'], json=data)
if r and r.status_code == httpx.codes.ok:
response = r.json()
if response.get('appointmentId'):
print('===抢票成功===', response)
break
print(response)
print('next....')
else:
print('===抢票失败===')
t = TicketSecKill()
asyncio.get_event_loop().run_until_complete(t._create_appointment())
| true | true |
f7f896ce2ac9c7932c0b8309018597282e0a1f76 | 12,506 | py | Python | jpn/transliterate.py | huzerD/jpn | a73ce3b7297aa912019d2ee067634d8b4f590c46 | [
"MIT"
] | null | null | null | jpn/transliterate.py | huzerD/jpn | a73ce3b7297aa912019d2ee067634d8b4f590c46 | [
"MIT"
] | null | null | null | jpn/transliterate.py | huzerD/jpn | a73ce3b7297aa912019d2ee067634d8b4f590c46 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set ts=2 expandtab:
'''
Module: transliterate.py
Desc: Transliterate using (modified)kunrei-shiki romanizations
Author: john.oneil
Email: oneil.john@gmail.com
DATE: Wed May 7th 2014
Writing this module because of current defficiencies in the romkan and jTransliterate packages.
'''
import os
import argparse
import re
from jpn.exceptions import NonUnicodeInputException
#based on http://en.wikipedia.org/wiki/Kunrei-shiki_romanization
TRANSLITERATION_TABLE = {
u'a' :[u'あ',u'ア'], u'i':[u'い', u'イ'],u'u':[u'う',u'ウ'], u'e':[u'え',u'エ'], u'o':[u'お',u'オ'],
u'ka':[u'か',u'カ'], u'ki':[u'き',u'キ'], u'ku':[u'く',u'ク'], u'ke':[u'け',u'ケ'], u'ko':[u'こ',u'コ'], u'kya':[u'きゃ',u'キャ'], u'kyu':[u'きゅ',u'キュ'], u'kyo':[u'きょ',u'キョ'],
u'ca':[u'か',u'カ'], u'ci':[u'き',u'キ'], u'cu':[u'く',u'ク'], u'ce':[u'け',u'ケ'], u'co':[u'こ',u'コ'], u'cya':[u'きゃ',u'キャ'], u'cyu':[u'きゅ',u'キュ'], u'cyo':[u'きょ',u'キョ'],
u'sa':[u'さ',u'サ'], u'si':[u'し',u'シ'], u'su':[u'す',u'ス'], u'se':[u'せ',u'セ'], u'so':[u'そ',u'ソ'], u'sya':[u'しゃ',u'シャ'], u'syu':[u'しゅ',u'シュ'], u'syo':[u'しょ',u'ショ'],
u'ta':[u'た',u'タ'], u'ti':[u'ち',u'チ'], u'tu':[u'つ',u'ツ'], u'te':[u'て',u'テ'], u'to':[u'と',u'ト'], u'tya':[u'ちゃ',u'チャ'], u'tyu':[u'ちゅ',u'チュ'], u'tyo':[u'ちょ',u'チョ'],
u'na':[u'な',u'ナ'], u'ni':[u'に',u'ニ'], u'nu':[u'ぬ',u'ヌ'], u'ne':[u'ね',u'ネ'], u'no':[u'の',u'ノ'], u'nya':[u'にゃ',u'ニャ'], u'nyu':[u'にゅ',u'ニュ'], u'nyo':[u'にょ',u'ニョ'],
u'ha':[u'は',u'ハ'], u'hi':[u'ひ',u'ヒ'], u'hu':[u'ふ',u'フ'], u'he':[u'へ',u'ヘ'], u'ho':[u'ほ',u'ホ'], u'hya':[u'ひゃ',u'ヒャ'], u'hyu':[u'ひゅ',u'ヒュ'], u'hyo':[u'ひょ',u'ヒョ'],
u'fa':[u'は',u'ハ'], u'fi':[u'ひ',u'ヒ'], u'fu':[u'ふ',u'フ'], u'fe':[u'へ',u'ヘ'], u'fo':[u'ほ',u'ホ'], u'fya':[u'ひゃ',u'ヒャ'], u'fyu':[u'ひゅ',u'ヒュ'], u'fyo':[u'ひょ',u'ヒョ'],
u'ma':[u'ま',u'マ'], u'mi':[u'み',u'ミ'], u'mu':[u'む',u'ム'], u'me':[u'め',u'メ'], u'mo':[u'も',u'モ'], u'mya':[u'みゃ',u'ミャ'], u'myu':[u'みゅ',u'ミュ'], u'myo':[u'みょ',u'ミョ'],
u'ya':[u'や',u'ヤ'], u'yu':[u'ゆ',u'ユ'], u'yo':[u'よ',u'ヨ'],
u'ra':[u'ら',u'ラ'], u'ri':[u'り', u'リ'], u'ru':[u'る',u'ル'], u're':[u'れ',u'レ'], u'ro':[u'ろ',u'ロ'], u'rya':[u'りゃ',u'リャ'], u'ryu':[u'りゅ',u'リュ'], u'ryo':[u'りょ',u'リョ'],
u'la':[u'ら',u'ラ'], u'li':[u'り', u'りリ'], u'lu':[u'る',u'ル'], u'le':[u'れ',u'レ'], u'lo':[u'ろ',u'ロ'], u'lya':[u'りゃ',u'リャ'], u'lyu':[u'りゅ',u'リュ'], u'lyo':[u'りょ',u'リョ'],
u'wa':[u'わ',u'ワ'], #u'o':[u'を',u'ヲ'], #u'i':[u'ヰ', u'ゐ '], u'e':[u'ゑ',u'ヱ']
u'n' :[u'ん',u'ン'],
u'ga':[u'が',u'ガ'], u'gi':[u'ぎ',u'ギ'], u'gu':[u'ぐ',u'グ'], u'ge':[u'げ',u'ゲ'], u'go':[u'ご',u'ゴ'], u'gya':[u'ぎゃ', u'ギャ'], u'gyu':[u'ぎゅ',u'ギュ'] ,u'gyo':[u'ぎょ',u'ギョ'],
u'za':[u'ざ',u'ザ'], u'zi':[u'じ',u'ジ'], u'zu':[u'ず',u'ズ'], u'ze':[u'ぜ',u'ゼ'], u'zo':[u'ぞ',u'ゾ'], u'zya':[u'じゃ', u'ジャ'], u'zyu':[u'じゅ',u'ジュ'] ,u'zyo':[u'じょ',u'ジョ'],
u'ja':[u'じゃ',u'ジャ'], u'ji':[u'じ',u'ジ'], u'ju':[u'じゅ',u'ジュ'], u'je':[u'ぜ',u'ゼ'], u'jo':[u'じょ',u'ジョ'], u'jya':[u'じゃ', u'ジャ'], u'jyu':[u'じゅ',u'ジュ'] ,u'jyo':[u'じょ',u'ジョ'],
u'da':[u'だ',u'ダ'], u'zi':[u'ぢ',u'ヂ'], u'zu':[u'づ',u'ヅ'], u'de':[u'で',u'デ'], u'do':[u'ど',u'ド'], u'zya':[u'ぢゃ', u'ヂャ'], u'zyu':[u'ぢゅ',u'ヂュ'] ,u'zyo':[u'ぢょ',u'ヂョ'],
u'ba':[u'ば',u'バ'], u'bi':[u'び',u'ビ'], u'bu':[u'ぶ',u'ブ'], u'be':[u'べ',u'ベ'], u'bo':[u'ぼ',u'ボ'], u'bya':[u'びゃ', u'ビャ'], u'byu':[u'びゅ',u'ビュ'] ,u'byo':[u'びょ',u'ビョ'],
u'pa':[u'ぱ',u'パ'], u'pi':[u'ぴ',u'ピ'], u'pu':[u'ぷ',u'プ'], u'pe':[u'ぺ',u'ペ'], u'po':[u'ぽ',u'ポ'], u'pya':[u'ぴゃ', u'ピャ'], u'pyu':[u'ぴゅ',u'ピュ'] ,u'pyo':[u'ぴょ',u'ピョ'],
#doubled consonants
u'kka':[u'っか',u'ッカ'], u'kki':[u'っき', u'ッキ'], u'kku':[u'っく',u'ック'], u'kke':[u'っけ',u'ッケ'], u'kko':[u'っこ',u'ッコ'], u'kkya':[u'っきゃ',u'ッキャ'], u'kkyu':[u'っきゅ',u'ッキュ'], u'kkyo':[u'っきょ',u'ッキョ'],
u'cca':[u'っか',u'ッカ'], u'cci':[u'っき', u'ッキ'], u'ccu':[u'っく',u'ック'], u'cce':[u'っけ',u'ッケ'], u'cco':[u'っこ',u'ッコ'], u'ccya':[u'っきゃ',u'ッキャ'], u'ccyu':[u'っきゅ',u'ッキュ'], u'ccyo':[u'っきょ',u'ッキョ'],
u'ssa':[u'っさ',u'ッサ'], u'ssi':[u'っし', u'ッシ'], u'ssu':[u'っす',u'ッス'], u'sse':[u'っせ',u'ッセ'], u'sso':[u'っそ',u'ッソ'], u'ssya':[u'っしゃ',u'ッシャ'], u'ssyu':[u'っしゅ',u'ッシュ'], u'ssyo':[u'っしょ',u'ッショ'],
u'tta':[u'った',u'ッタ'], u'tti':[u'っち', u'ッチ'], u'ttu':[u'っつ',u'ッツ'], u'tte':[u'って',u'ッテ'], u'tto':[u'っと',u'ット'], u'ttya':[u'っちゃ',u'ッチャ'], u'ttyu':[u'っちゅ',u'ッチュ'], u'ttyo':[u'っちょ',u'ッチョ'],
u'nna':[u'っな',u'ッナ'], u'nni':[u'っに', u'ッニ'], u'nnu':[u'っぬ',u'ッヌ'], u'nne':[u'っね',u'ッネ'], u'nno':[u'っの',u'ッノ'], u'nnya':[u'っにゃ',u'ッニャ'], u'nnyu':[u'っにゅ',u'ッニュ'], u'nyo':[u'っにょ',u'ッニョ'],
u'hha':[u'っは',u'ッハ'], u'hhi':[u'っひ', u'ッヒ'], u'hhu':[u'っふ',u'ッフ'], u'hhe':[u'っへ',u'ッヘ'], u'hho':[u'っほ',u'ッホ'], u'hhya':[u'っひゃ',u'ッヒャ'], u'hhyu':[u'っひゅ',u'ッヒュ'], u'hhyo':[u'っひょ',u'ッヒョ'],
u'mma':[u'っま',u'ッマ'], u'mmi':[u'っみ', u'ッミ'], u'mmu':[u'っむ',u'ッム'], u'mme':[u'っめ',u'ッメ'], u'mmo':[u'っも',u'ッモ'], u'mmya':[u'っみゃ',u'ッミャ'], u'mmyu':[u'っみゅ',u'ッミュ'], u'mmyo':[u'っみょ',u'ッミョ'],
u'rra':[u'っら',u'ッラ'], u'rri':[u'っり', u'ッリ'], u'rru':[u'っる',u'ッル'], u'rre':[u'っれ',u'ッレ'], u'rro':[u'っろ',u'ッロ'], u'rrya':[u'っりゃ',u'ッリャ'], u'rryu':[u'っりゅ',u'ッリュ'], u'rryo':[u'っりょ',u'ッリョ'],
u'lla':[u'っら',u'ッラ'], u'lli':[u'っり', u'ッリ'], u'llu':[u'っる',u'ッル'], u'lle':[u'っれ',u'ッレ'], u'llo':[u'っろ',u'ッロ'], u'llya':[u'っりゃ',u'ッリャ'], u'llyu':[u'っりゅ',u'ッリュ'], u'llyo':[u'っりょ',u'ッリョ'],
u'nn' :[u'っん',u'ン'],
u'gga':[u'っが',u'ッガ'], u'ggi':[u'っぎ',u'ッギ'], u'ggu':[u'っぐ',u'ッグ'], u'gge':[u'っげ',u'ッゲ'], u'ggo':[u'っご',u'ッゴ'], u'ggya':[u'っぎゃ', u'ッギャ'], u'ggyu':[u'っぎゅ',u'ッギュ'] ,u'ggyo':[u'っぎょ',u'ッギョ'],
u'zza':[u'っざ',u'ッザ'], u'zzi':[u'っじ',u'ッジ'], u'zzu':[u'っず',u'ッズ'], u'zze':[u'っぜ',u'ッゼ'], u'zzo':[u'っぞ',u'ッゾ'], u'zzya':[u'っじゃ', u'ッジャ'], u'zzyu':[u'っじゅ',u'ッジュ'] ,u'zzyo':[u'っじょ',u'ッジョ'],
u'dda':[u'っだ',u'ッダ'], u'zzi':[u'っぢ',u'ッヂ'], u'zzu':[u'っづ',u'ッヅ'], u'dde':[u'っで',u'ッデ'], u'ddo':[u'っど',u'ッド'], u'zzya':[u'っぢゃ', u'ッヂャ'], u'zzyu':[u'っぢゅ',u'ッヂュ'] ,u'zzyo':[u'っぢょ',u'ッヂョ'],
u'bba':[u'っば',u'ッバ'], u'bbi':[u'っび',u'ッビ'], u'bbu':[u'っぶ',u'ッブ'], u'bbe':[u'っべ',u'ッベ'], u'bbo':[u'っぼ',u'ッボ'], u'bbya':[u'っびゃ', u'ッビャ'], u'bbyu':[u'っびゅ',u'ッビュ'] ,u'bbyo':[u'っびょ',u'ッビョ'],
u'ppa':[u'っぱ',u'ッパ'], u'ppi':[u'っぴ',u'ッピ'], u'ppu':[u'っぷ',u'ップ'], u'ppe':[u'っぺ',u'ッペ'], u'ppo':[u'っぽ',u'ッポ'], u'ppya':[u'っぴゃ', u'ッピャ'], u'ppyu':[u'っぴゅ',u'ッピュ'] ,u'ppyo':[u'っぴょ',u'ッピョ'],
#doubled vowels
u'aa' :[u'ああ',u'アー'], u'ii':[u'いい', u'イー'],u'uu':[u'うう',u'ウー'], u'ee':[u'ええ',u'エー'], u'oo':[u'おお',u'オー'],
u'kaa':[u'かあ',u'カー'], u'kii':[u'きい',u'キー'], u'kuu':[u'くう',u'クー'], u'kee':[u'けえ',u'ケー'], u'koo':[u'こお',u'コー'], u'kyaa':[u'きゃあ',u'キャー'], u'うkyuu':[u'きゅう',u'キュー'], u'kyoo':[u'きょお',u'キョー'],
u'caa':[u'かあ',u'カー'], u'cii':[u'きい',u'キー'], u'cuu':[u'くう',u'クー'], u'cee':[u'けえ',u'ケー'], u'coo':[u'こお',u'コー'], u'cyaa':[u'きゃあ',u'キャー'], u'うcyuu':[u'きゅう',u'キュー'], u'cyoo':[u'きょお',u'キョー'],
u'saa':[u'さあ',u'サー'], u'sii':[u'しい',u'シー'], u'suu':[u'すう',u'スー'], u'see':[u'せえ',u'セー'], u'soo':[u'そお',u'ソー'], u'syaa':[u'しゃあ',u'シャー'], u'うsyuu':[u'しゅう',u'シュー'], u'syoo':[u'しょお',u'ショー'],
u'taa':[u'たあ',u'ター'], u'tii':[u'ちい',u'チー'], u'tuu':[u'つう',u'ツー'], u'tee':[u'てえ',u'テー'], u'too':[u'とお',u'トー'], u'tyaa':[u'ちゃあ',u'チャー'], u'うtyuu':[u'ちゅう',u'チュー'], u'tyoo':[u'ちょお',u'チョー'],
u'naa':[u'なあ',u'ナー'], u'nii':[u'にい',u'ニー'], u'nuu':[u'ぬう',u'ヌー'], u'nee':[u'ねえ',u'ネー'], u'noo':[u'のお',u'ノー'], u'nyaa':[u'にゃあ',u'ニャー'], u'うnyuu':[u'にゅう',u'ニュー'], u'nyoo':[u'にょお',u'ニョー'],
u'haa':[u'はあ',u'ハー'], u'hii':[u'ひい',u'ヒー'], u'huu':[u'ふう',u'フー'], u'hee':[u'へえ',u'ヘー'], u'hoo':[u'ほお',u'ホー'], u'hyaa':[u'ひゃあ',u'ヒャー'], u'うhyuu':[u'ひゅう',u'ヒュー'], u'hyoo':[u'ひょお',u'ヒョー'],
u'faa':[u'はあ',u'ハー'], u'fii':[u'ひい',u'ヒー'], u'fuu':[u'ふう',u'フー'], u'fee':[u'へえ',u'ヘー'], u'foo':[u'ほお',u'ホー'], u'fyaa':[u'ひゃあ',u'ヒャー'], u'うfyuu':[u'ひゅう',u'ヒュー'], u'fyoo':[u'ひょお',u'ヒョー'],
u'maa':[u'まあ',u'マー'], u'mii':[u'みい',u'ミー'], u'muu':[u'むう',u'ムー'], u'mee':[u'めえ',u'メー'], u'moo':[u'もお',u'モー'], u'myaa':[u'みゃあ',u'ミャー'], u'myuu':[u'みゅう',u'ミュー'], u'myoo':[u'みょお',u'ミョー'],
u'yaa':[u'やあ',u'ヤー'], u'yuu':[u'ゆう',u'ユー'], u'yoo':[u'よお',u'ヨー'],
u'raa':[u'らあ',u'ラー'], u'rii':[u'りい', u'リー'], u'ruu':[u'るう',u'ルー'], u'ree':[u'れえ',u'レー'], u'roo':[u'ろお',u'ロー'], u'ryaa':[u'りゃあ',u'リャー'], u'ryuu':[u'りゅう',u'リュー'], u'ryoo':[u'りょお',u'リョー'],
u'laa':[u'らあ',u'ラー'], u'lii':[u'りい', u'リー'], u'luu':[u'るう',u'ルー'], u'lee':[u'れえ',u'レー'], u'loo':[u'ろお',u'ロー'], u'lyaa':[u'りゃあ',u'リャー'], u'lyuu':[u'りゅう',u'リュー'], u'lyoo':[u'りょお',u'リョー'],
u'waa':[u'わあ',u'ワー'],
u'gaa':[u'があ',u'ガー'], u'gii':[u'ぎい',u'ギー'], u'guu':[u'ぐう',u'グー'], u'gee':[u'げえ',u'ゲー'], u'goo':[u'ごお',u'ゴー'], u'gyaa':[u'ぎゃあ', u'ギャー'], u'gyuu':[u'ぎゅう',u'ギュー'] ,u'gyoo':[u'ぎょお',u'ギョー'],
u'zaa':[u'ざあ',u'ザー'], u'zii':[u'じい',u'ジー'], u'zuu':[u'ずう',u'ズー'], u'zee':[u'ぜえ',u'ゼー'], u'zoo':[u'ぞお',u'ゾー'], u'zyaa':[u'じゃあ', u'ジャー'], u'zyuu':[u'じゅう',u'ジュー'] ,u'zyoo':[u'じょお',u'ジョー'],
u'jaa':[u'じゃあ',u'ジャー'], u'jii':[u'じい',u'ジー'], u'juu':[u'じゅう',u'ジュー'], u'jee':[u'ぜえ',u'ゼー'], u'joo':[u'じょお',u'ジョー'], u'jyaa':[u'じゃあ', u'ジャー'], u'jyu':[u'じゅう',u'ジュー'] ,u'jyo':[u'じょお',u'ジョー'],
u'daa':[u'だあ',u'ダー'], u'zii':[u'ぢい',u'ヂー'], u'zuu':[u'づう',u'ヅー'], u'dee':[u'でえ',u'デー'], u'doo':[u'どお',u'ドー'], u'zyaa':[u'ぢゃあ', u'ヂャー'], u'zyuu':[u'ぢゅう',u'ヂュー'] ,u'zyoo':[u'ぢょお',u'ヂョー'],
u'baa':[u'ばあ',u'バー'], u'bii':[u'びい',u'ビー'], u'buu':[u'ぶう',u'ブー'], u'bee':[u'べえ',u'ベー'], u'boo':[u'ぼお',u'ボー'], u'byaa':[u'びゃあ', u'ビャー'], u'byuu':[u'びゅう',u'ビュー'] ,u'byoo':[u'びょお',u'ビョー'],
u'paa':[u'ぱあ',u'パー'], u'pii':[u'ぴい',u'ピー'], u'puu':[u'ぷう',u'プー'], u'pee':[u'ぺえ',u'ペー'], u'poo':[u'ぽお',u'ポー'], u'pyaa':[u'ぴゃあ', u'ピャー'], u'pyuu':[u'ぴゅう',u'ピュー'] ,u'pyoo':[u'ぴょお',u'ピョー'],
#permitted exceptions
u'sha':[u'しゃ',u'シャ'], u'shi':[u'し',u'シ'], u'shu':[u'しゅ',u'シュ'], u'sho':[u'しょ',u'ショ'],
u'tsu':[u'つ', u'ツ'],
u'cha':[u'ちゃ',u'チャ'], u'chi':[u'ち',u'チ'], u'chu':[u'ちゅ',u'チュ'], u'cho': [u'ちょ',u'チョ'],
u'fu':[u'ふ',u'フ'],
#u'ja':[u'じゃ',u'ジャ'], u'ji':[u'じ',u'ジ'], u'ju':[u'じゅ',u'ジュ'], u'jo':[u'じょ',u'ジョ'],
u'di':[u'ぢ',u'ヂ'], u'du':[u'づ',u'ヅ'],
u'dya':[u'ぢゃ',u'ヂャ'], u'dyu':[u'ぢゅ',u'ヂュ'], u'dyo':[u'ぢょ',u'ヂョ'],
u'kwa':[u'くゎ',u'クァ'],
u'gwa':[u'ぐゎ',u'グァ'],
u'wo':[u'を',u'を'],
#Single consonants. Not strictly correct, but add robustness to general transliteration.
u'b':[u'ぶ',u'ブ'],
u'c':[u'く',u'ク'],
u'd':[u'ど',u'ド'],
u'f':[u'ふ',u'フ'],
u'g':[u'ぐ',u'グ'],
u'h':[u'ふ',u'フ'],
u'hn':[u'ん',u'ン'],
u'j':[u'る',u'ル'],
u'k':[u'く',u'ク'],
u'l':[u'る',u'ル'],
u'm':[u'む',u'ム'],
u'p':[u'ぷ',u'プ'],
u'q':[u'くぃ',u'クイ'],
u'qu':[u'くぃ',u'クイ'],
u'r':[u'る',u'ル'],
u's':[u'す',u'ス'],
u't':[u'と',u'ト'],
u'v':[u'ぶ',u'ブ'],
u'w':[u'わ',u'ワ'],
u'x':[u'ず',u'ズ'],
u'y':[u'ゆ',u'ユ'],
u'z':[u'ず',u'ズ'],
#simple punctuation handling?
u'a\'' :[u'ああ',u'アー'], u'i\'':[u'いい', u'イー'],u'u\'':[u'うう',u'ウー'], u'e\'':[u'ええ',u'エー'], u'o\'':[u'おお',u'オー'],
u'\'' :[u'',u''],
u'_' :[u'・',u'・'],
#TODO: match dipthongs? Better estimates for American english pronunciation?
#attempt to render 'th' better, without screwing up 'h'
u'tha':[u'ざ',u'ザ'], u'thi':[u'じ',u'ジ'], u'thu':[u'ず',u'ズ'], u'the':[u'ざ',u'ザ'], u'tho':[u'ぞ',u'ゾ'], u'thya':[u'つゃ',u'ツャ'], u'thyu':[u'つゅ',u'ツュ'], u'thyo':[u'つょ',u'ツョ'],
u'th':[u'つ',u'ツ'],
}
def romaji2hiragana(phrase):
'''Transliterate using kunrei-shiki
'''
#ensure input is a unicode string
if not isinstance(phrase, unicode):
raise NonUnicodeInputException('Input argument {phrase} is not unicode.'.format(phrase=phrase))
hiragana = u''
while phrase:
(h,p) = nibble(phrase)
#print 'returned phrase is ' + h[0]
hiragana += h[0]
phrase = p
return hiragana
def romaji2katakana(phrase):
'''Transliterate using kunrei-shiki
'''
#ensure input is a unicode string
if not isinstance(phrase, unicode):
raise NonUnicodeInputException('Input argument {phrase} is not unicode.'.format(phrase=phrase))
katakana = u''
while phrase:
(h,p) = nibble(phrase)
katakana += unicode(h[1])
phrase = p
return katakana
def nibble(phrase):
'''Nibble off longest phrase
'''
#longest possible key->kana is 4 characters, so search next four then three etc for key hit
for i in reversed(range(4)):
nib = phrase[:i]
if nib in TRANSLITERATION_TABLE:
return (TRANSLITERATION_TABLE[nib], phrase[i:])
return ([phrase[:1], phrase[:1]], phrase[1:])
def main():
parser = argparse.ArgumentParser(description='Transliterate romaji to hiragana.')
parser.add_argument('-k', '--katakana', help='Transliterate to katakana',action='store_true')
parser.add_argument('words', nargs='*', help='Words to transliterate')
args = parser.parse_args()
for word in args.words:
#best practice: decode early, encode late. Just handle unicode in libs.
word = word.decode('utf-8')
if args.katakana:
print(romaji2katakana(word).encode('utf-8'))
else:
print(romaji2hiragana(word).encode('utf-8'))
if __name__ == "__main__":
main()
| 66.521277 | 190 | 0.495842 |
import os
import argparse
import re
from jpn.exceptions import NonUnicodeInputException
TRANSLITERATION_TABLE = {
u'a' :[u'あ',u'ア'], u'i':[u'い', u'イ'],u'u':[u'う',u'ウ'], u'e':[u'え',u'エ'], u'o':[u'お',u'オ'],
u'ka':[u'か',u'カ'], u'ki':[u'き',u'キ'], u'ku':[u'く',u'ク'], u'ke':[u'け',u'ケ'], u'ko':[u'こ',u'コ'], u'kya':[u'きゃ',u'キャ'], u'kyu':[u'きゅ',u'キュ'], u'kyo':[u'きょ',u'キョ'],
u'ca':[u'か',u'カ'], u'ci':[u'き',u'キ'], u'cu':[u'く',u'ク'], u'ce':[u'け',u'ケ'], u'co':[u'こ',u'コ'], u'cya':[u'きゃ',u'キャ'], u'cyu':[u'きゅ',u'キュ'], u'cyo':[u'きょ',u'キョ'],
u'sa':[u'さ',u'サ'], u'si':[u'し',u'シ'], u'su':[u'す',u'ス'], u'se':[u'せ',u'セ'], u'so':[u'そ',u'ソ'], u'sya':[u'しゃ',u'シャ'], u'syu':[u'しゅ',u'シュ'], u'syo':[u'しょ',u'ショ'],
u'ta':[u'た',u'タ'], u'ti':[u'ち',u'チ'], u'tu':[u'つ',u'ツ'], u'te':[u'て',u'テ'], u'to':[u'と',u'ト'], u'tya':[u'ちゃ',u'チャ'], u'tyu':[u'ちゅ',u'チュ'], u'tyo':[u'ちょ',u'チョ'],
u'na':[u'な',u'ナ'], u'ni':[u'に',u'ニ'], u'nu':[u'ぬ',u'ヌ'], u'ne':[u'ね',u'ネ'], u'no':[u'の',u'ノ'], u'nya':[u'にゃ',u'ニャ'], u'nyu':[u'にゅ',u'ニュ'], u'nyo':[u'にょ',u'ニョ'],
u'ha':[u'は',u'ハ'], u'hi':[u'ひ',u'ヒ'], u'hu':[u'ふ',u'フ'], u'he':[u'へ',u'ヘ'], u'ho':[u'ほ',u'ホ'], u'hya':[u'ひゃ',u'ヒャ'], u'hyu':[u'ひゅ',u'ヒュ'], u'hyo':[u'ひょ',u'ヒョ'],
u'fa':[u'は',u'ハ'], u'fi':[u'ひ',u'ヒ'], u'fu':[u'ふ',u'フ'], u'fe':[u'へ',u'ヘ'], u'fo':[u'ほ',u'ホ'], u'fya':[u'ひゃ',u'ヒャ'], u'fyu':[u'ひゅ',u'ヒュ'], u'fyo':[u'ひょ',u'ヒョ'],
u'ma':[u'ま',u'マ'], u'mi':[u'み',u'ミ'], u'mu':[u'む',u'ム'], u'me':[u'め',u'メ'], u'mo':[u'も',u'モ'], u'mya':[u'みゃ',u'ミャ'], u'myu':[u'みゅ',u'ミュ'], u'myo':[u'みょ',u'ミョ'],
u'ya':[u'や',u'ヤ'], u'yu':[u'ゆ',u'ユ'], u'yo':[u'よ',u'ヨ'],
u'ra':[u'ら',u'ラ'], u'ri':[u'り', u'リ'], u'ru':[u'る',u'ル'], u're':[u'れ',u'レ'], u'ro':[u'ろ',u'ロ'], u'rya':[u'りゃ',u'リャ'], u'ryu':[u'りゅ',u'リュ'], u'ryo':[u'りょ',u'リョ'],
u'la':[u'ら',u'ラ'], u'li':[u'り', u'りリ'], u'lu':[u'る',u'ル'], u'le':[u'れ',u'レ'], u'lo':[u'ろ',u'ロ'], u'lya':[u'りゃ',u'リャ'], u'lyu':[u'りゅ',u'リュ'], u'lyo':[u'りょ',u'リョ'],
u'wa':[u'わ',u'ワ'], '], u'gi':[u'ぎ',u'ギ'], u'gu':[u'ぐ',u'グ'], u'ge':[u'げ',u'ゲ'], u'go':[u'ご',u'ゴ'], u'gya':[u'ぎゃ', u'ギャ'], u'gyu':[u'ぎゅ',u'ギュ'] ,u'gyo':[u'ぎょ',u'ギョ'],
u'za':[u'ざ',u'ザ'], u'zi':[u'じ',u'ジ'], u'zu':[u'ず',u'ズ'], u'ze':[u'ぜ',u'ゼ'], u'zo':[u'ぞ',u'ゾ'], u'zya':[u'じゃ', u'ジャ'], u'zyu':[u'じゅ',u'ジュ'] ,u'zyo':[u'じょ',u'ジョ'],
u'ja':[u'じゃ',u'ジャ'], u'ji':[u'じ',u'ジ'], u'ju':[u'じゅ',u'ジュ'], u'je':[u'ぜ',u'ゼ'], u'jo':[u'じょ',u'ジョ'], u'jya':[u'じゃ', u'ジャ'], u'jyu':[u'じゅ',u'ジュ'] ,u'jyo':[u'じょ',u'ジョ'],
u'da':[u'だ',u'ダ'], u'zi':[u'ぢ',u'ヂ'], u'zu':[u'づ',u'ヅ'], u'de':[u'で',u'デ'], u'do':[u'ど',u'ド'], u'zya':[u'ぢゃ', u'ヂャ'], u'zyu':[u'ぢゅ',u'ヂュ'] ,u'zyo':[u'ぢょ',u'ヂョ'],
u'ba':[u'ば',u'バ'], u'bi':[u'び',u'ビ'], u'bu':[u'ぶ',u'ブ'], u'be':[u'べ',u'ベ'], u'bo':[u'ぼ',u'ボ'], u'bya':[u'びゃ', u'ビャ'], u'byu':[u'びゅ',u'ビュ'] ,u'byo':[u'びょ',u'ビョ'],
u'pa':[u'ぱ',u'パ'], u'pi':[u'ぴ',u'ピ'], u'pu':[u'ぷ',u'プ'], u'pe':[u'ぺ',u'ペ'], u'po':[u'ぽ',u'ポ'], u'pya':[u'ぴゃ', u'ピャ'], u'pyu':[u'ぴゅ',u'ピュ'] ,u'pyo':[u'ぴょ',u'ピョ'],
u'kka':[u'っか',u'ッカ'], u'kki':[u'っき', u'ッキ'], u'kku':[u'っく',u'ック'], u'kke':[u'っけ',u'ッケ'], u'kko':[u'っこ',u'ッコ'], u'kkya':[u'っきゃ',u'ッキャ'], u'kkyu':[u'っきゅ',u'ッキュ'], u'kkyo':[u'っきょ',u'ッキョ'],
u'cca':[u'っか',u'ッカ'], u'cci':[u'っき', u'ッキ'], u'ccu':[u'っく',u'ック'], u'cce':[u'っけ',u'ッケ'], u'cco':[u'っこ',u'ッコ'], u'ccya':[u'っきゃ',u'ッキャ'], u'ccyu':[u'っきゅ',u'ッキュ'], u'ccyo':[u'っきょ',u'ッキョ'],
u'ssa':[u'っさ',u'ッサ'], u'ssi':[u'っし', u'ッシ'], u'ssu':[u'っす',u'ッス'], u'sse':[u'っせ',u'ッセ'], u'sso':[u'っそ',u'ッソ'], u'ssya':[u'っしゃ',u'ッシャ'], u'ssyu':[u'っしゅ',u'ッシュ'], u'ssyo':[u'っしょ',u'ッショ'],
u'tta':[u'った',u'ッタ'], u'tti':[u'っち', u'ッチ'], u'ttu':[u'っつ',u'ッツ'], u'tte':[u'って',u'ッテ'], u'tto':[u'っと',u'ット'], u'ttya':[u'っちゃ',u'ッチャ'], u'ttyu':[u'っちゅ',u'ッチュ'], u'ttyo':[u'っちょ',u'ッチョ'],
u'nna':[u'っな',u'ッナ'], u'nni':[u'っに', u'ッニ'], u'nnu':[u'っぬ',u'ッヌ'], u'nne':[u'っね',u'ッネ'], u'nno':[u'っの',u'ッノ'], u'nnya':[u'っにゃ',u'ッニャ'], u'nnyu':[u'っにゅ',u'ッニュ'], u'nyo':[u'っにょ',u'ッニョ'],
u'hha':[u'っは',u'ッハ'], u'hhi':[u'っひ', u'ッヒ'], u'hhu':[u'っふ',u'ッフ'], u'hhe':[u'っへ',u'ッヘ'], u'hho':[u'っほ',u'ッホ'], u'hhya':[u'っひゃ',u'ッヒャ'], u'hhyu':[u'っひゅ',u'ッヒュ'], u'hhyo':[u'っひょ',u'ッヒョ'],
u'mma':[u'っま',u'ッマ'], u'mmi':[u'っみ', u'ッミ'], u'mmu':[u'っむ',u'ッム'], u'mme':[u'っめ',u'ッメ'], u'mmo':[u'っも',u'ッモ'], u'mmya':[u'っみゃ',u'ッミャ'], u'mmyu':[u'っみゅ',u'ッミュ'], u'mmyo':[u'っみょ',u'ッミョ'],
u'rra':[u'っら',u'ッラ'], u'rri':[u'っり', u'ッリ'], u'rru':[u'っる',u'ッル'], u'rre':[u'っれ',u'ッレ'], u'rro':[u'っろ',u'ッロ'], u'rrya':[u'っりゃ',u'ッリャ'], u'rryu':[u'っりゅ',u'ッリュ'], u'rryo':[u'っりょ',u'ッリョ'],
u'lla':[u'っら',u'ッラ'], u'lli':[u'っり', u'ッリ'], u'llu':[u'っる',u'ッル'], u'lle':[u'っれ',u'ッレ'], u'llo':[u'っろ',u'ッロ'], u'llya':[u'っりゃ',u'ッリャ'], u'llyu':[u'っりゅ',u'ッリュ'], u'llyo':[u'っりょ',u'ッリョ'],
u'nn' :[u'っん',u'ン'],
u'gga':[u'っが',u'ッガ'], u'ggi':[u'っぎ',u'ッギ'], u'ggu':[u'っぐ',u'ッグ'], u'gge':[u'っげ',u'ッゲ'], u'ggo':[u'っご',u'ッゴ'], u'ggya':[u'っぎゃ', u'ッギャ'], u'ggyu':[u'っぎゅ',u'ッギュ'] ,u'ggyo':[u'っぎょ',u'ッギョ'],
u'zza':[u'っざ',u'ッザ'], u'zzi':[u'っじ',u'ッジ'], u'zzu':[u'っず',u'ッズ'], u'zze':[u'っぜ',u'ッゼ'], u'zzo':[u'っぞ',u'ッゾ'], u'zzya':[u'っじゃ', u'ッジャ'], u'zzyu':[u'っじゅ',u'ッジュ'] ,u'zzyo':[u'っじょ',u'ッジョ'],
u'dda':[u'っだ',u'ッダ'], u'zzi':[u'っぢ',u'ッヂ'], u'zzu':[u'っづ',u'ッヅ'], u'dde':[u'っで',u'ッデ'], u'ddo':[u'っど',u'ッド'], u'zzya':[u'っぢゃ', u'ッヂャ'], u'zzyu':[u'っぢゅ',u'ッヂュ'] ,u'zzyo':[u'っぢょ',u'ッヂョ'],
u'bba':[u'っば',u'ッバ'], u'bbi':[u'っび',u'ッビ'], u'bbu':[u'っぶ',u'ッブ'], u'bbe':[u'っべ',u'ッベ'], u'bbo':[u'っぼ',u'ッボ'], u'bbya':[u'っびゃ', u'ッビャ'], u'bbyu':[u'っびゅ',u'ッビュ'] ,u'bbyo':[u'っびょ',u'ッビョ'],
u'ppa':[u'っぱ',u'ッパ'], u'ppi':[u'っぴ',u'ッピ'], u'ppu':[u'っぷ',u'ップ'], u'ppe':[u'っぺ',u'ッペ'], u'ppo':[u'っぽ',u'ッポ'], u'ppya':[u'っぴゃ', u'ッピャ'], u'ppyu':[u'っぴゅ',u'ッピュ'] ,u'ppyo':[u'っぴょ',u'ッピョ'],
u'aa' :[u'ああ',u'アー'], u'ii':[u'いい', u'イー'],u'uu':[u'うう',u'ウー'], u'ee':[u'ええ',u'エー'], u'oo':[u'おお',u'オー'],
u'kaa':[u'かあ',u'カー'], u'kii':[u'きい',u'キー'], u'kuu':[u'くう',u'クー'], u'kee':[u'けえ',u'ケー'], u'koo':[u'こお',u'コー'], u'kyaa':[u'きゃあ',u'キャー'], u'うkyuu':[u'きゅう',u'キュー'], u'kyoo':[u'きょお',u'キョー'],
u'caa':[u'かあ',u'カー'], u'cii':[u'きい',u'キー'], u'cuu':[u'くう',u'クー'], u'cee':[u'けえ',u'ケー'], u'coo':[u'こお',u'コー'], u'cyaa':[u'きゃあ',u'キャー'], u'うcyuu':[u'きゅう',u'キュー'], u'cyoo':[u'きょお',u'キョー'],
u'saa':[u'さあ',u'サー'], u'sii':[u'しい',u'シー'], u'suu':[u'すう',u'スー'], u'see':[u'せえ',u'セー'], u'soo':[u'そお',u'ソー'], u'syaa':[u'しゃあ',u'シャー'], u'うsyuu':[u'しゅう',u'シュー'], u'syoo':[u'しょお',u'ショー'],
u'taa':[u'たあ',u'ター'], u'tii':[u'ちい',u'チー'], u'tuu':[u'つう',u'ツー'], u'tee':[u'てえ',u'テー'], u'too':[u'とお',u'トー'], u'tyaa':[u'ちゃあ',u'チャー'], u'うtyuu':[u'ちゅう',u'チュー'], u'tyoo':[u'ちょお',u'チョー'],
u'naa':[u'なあ',u'ナー'], u'nii':[u'にい',u'ニー'], u'nuu':[u'ぬう',u'ヌー'], u'nee':[u'ねえ',u'ネー'], u'noo':[u'のお',u'ノー'], u'nyaa':[u'にゃあ',u'ニャー'], u'うnyuu':[u'にゅう',u'ニュー'], u'nyoo':[u'にょお',u'ニョー'],
u'haa':[u'はあ',u'ハー'], u'hii':[u'ひい',u'ヒー'], u'huu':[u'ふう',u'フー'], u'hee':[u'へえ',u'ヘー'], u'hoo':[u'ほお',u'ホー'], u'hyaa':[u'ひゃあ',u'ヒャー'], u'うhyuu':[u'ひゅう',u'ヒュー'], u'hyoo':[u'ひょお',u'ヒョー'],
u'faa':[u'はあ',u'ハー'], u'fii':[u'ひい',u'ヒー'], u'fuu':[u'ふう',u'フー'], u'fee':[u'へえ',u'ヘー'], u'foo':[u'ほお',u'ホー'], u'fyaa':[u'ひゃあ',u'ヒャー'], u'うfyuu':[u'ひゅう',u'ヒュー'], u'fyoo':[u'ひょお',u'ヒョー'],
u'maa':[u'まあ',u'マー'], u'mii':[u'みい',u'ミー'], u'muu':[u'むう',u'ムー'], u'mee':[u'めえ',u'メー'], u'moo':[u'もお',u'モー'], u'myaa':[u'みゃあ',u'ミャー'], u'myuu':[u'みゅう',u'ミュー'], u'myoo':[u'みょお',u'ミョー'],
u'yaa':[u'やあ',u'ヤー'], u'yuu':[u'ゆう',u'ユー'], u'yoo':[u'よお',u'ヨー'],
u'raa':[u'らあ',u'ラー'], u'rii':[u'りい', u'リー'], u'ruu':[u'るう',u'ルー'], u'ree':[u'れえ',u'レー'], u'roo':[u'ろお',u'ロー'], u'ryaa':[u'りゃあ',u'リャー'], u'ryuu':[u'りゅう',u'リュー'], u'ryoo':[u'りょお',u'リョー'],
u'laa':[u'らあ',u'ラー'], u'lii':[u'りい', u'リー'], u'luu':[u'るう',u'ルー'], u'lee':[u'れえ',u'レー'], u'loo':[u'ろお',u'ロー'], u'lyaa':[u'りゃあ',u'リャー'], u'lyuu':[u'りゅう',u'リュー'], u'lyoo':[u'りょお',u'リョー'],
u'waa':[u'わあ',u'ワー'],
u'gaa':[u'があ',u'ガー'], u'gii':[u'ぎい',u'ギー'], u'guu':[u'ぐう',u'グー'], u'gee':[u'げえ',u'ゲー'], u'goo':[u'ごお',u'ゴー'], u'gyaa':[u'ぎゃあ', u'ギャー'], u'gyuu':[u'ぎゅう',u'ギュー'] ,u'gyoo':[u'ぎょお',u'ギョー'],
u'zaa':[u'ざあ',u'ザー'], u'zii':[u'じい',u'ジー'], u'zuu':[u'ずう',u'ズー'], u'zee':[u'ぜえ',u'ゼー'], u'zoo':[u'ぞお',u'ゾー'], u'zyaa':[u'じゃあ', u'ジャー'], u'zyuu':[u'じゅう',u'ジュー'] ,u'zyoo':[u'じょお',u'ジョー'],
u'jaa':[u'じゃあ',u'ジャー'], u'jii':[u'じい',u'ジー'], u'juu':[u'じゅう',u'ジュー'], u'jee':[u'ぜえ',u'ゼー'], u'joo':[u'じょお',u'ジョー'], u'jyaa':[u'じゃあ', u'ジャー'], u'jyu':[u'じゅう',u'ジュー'] ,u'jyo':[u'じょお',u'ジョー'],
u'daa':[u'だあ',u'ダー'], u'zii':[u'ぢい',u'ヂー'], u'zuu':[u'づう',u'ヅー'], u'dee':[u'でえ',u'デー'], u'doo':[u'どお',u'ドー'], u'zyaa':[u'ぢゃあ', u'ヂャー'], u'zyuu':[u'ぢゅう',u'ヂュー'] ,u'zyoo':[u'ぢょお',u'ヂョー'],
u'baa':[u'ばあ',u'バー'], u'bii':[u'びい',u'ビー'], u'buu':[u'ぶう',u'ブー'], u'bee':[u'べえ',u'ベー'], u'boo':[u'ぼお',u'ボー'], u'byaa':[u'びゃあ', u'ビャー'], u'byuu':[u'びゅう',u'ビュー'] ,u'byoo':[u'びょお',u'ビョー'],
u'paa':[u'ぱあ',u'パー'], u'pii':[u'ぴい',u'ピー'], u'puu':[u'ぷう',u'プー'], u'pee':[u'ぺえ',u'ペー'], u'poo':[u'ぽお',u'ポー'], u'pyaa':[u'ぴゃあ', u'ピャー'], u'pyuu':[u'ぴゅう',u'ピュー'] ,u'pyoo':[u'ぴょお',u'ピョー'],
u'sha':[u'しゃ',u'シャ'], u'shi':[u'し',u'シ'], u'shu':[u'しゅ',u'シュ'], u'sho':[u'しょ',u'ショ'],
u'tsu':[u'つ', u'ツ'],
u'cha':[u'ちゃ',u'チャ'], u'chi':[u'ち',u'チ'], u'chu':[u'ちゅ',u'チュ'], u'cho': [u'ちょ',u'チョ'],
u'fu':[u'ふ',u'フ'],
u'di':[u'ぢ',u'ヂ'], u'du':[u'づ',u'ヅ'],
u'dya':[u'ぢゃ',u'ヂャ'], u'dyu':[u'ぢゅ',u'ヂュ'], u'dyo':[u'ぢょ',u'ヂョ'],
u'kwa':[u'くゎ',u'クァ'],
u'gwa':[u'ぐゎ',u'グァ'],
u'wo':[u'を',u'を'],
u'b':[u'ぶ',u'ブ'],
u'c':[u'く',u'ク'],
u'd':[u'ど',u'ド'],
u'f':[u'ふ',u'フ'],
u'g':[u'ぐ',u'グ'],
u'h':[u'ふ',u'フ'],
u'hn':[u'ん',u'ン'],
u'j':[u'る',u'ル'],
u'k':[u'く',u'ク'],
u'l':[u'る',u'ル'],
u'm':[u'む',u'ム'],
u'p':[u'ぷ',u'プ'],
u'q':[u'くぃ',u'クイ'],
u'qu':[u'くぃ',u'クイ'],
u'r':[u'る',u'ル'],
u's':[u'す',u'ス'],
u't':[u'と',u'ト'],
u'v':[u'ぶ',u'ブ'],
u'w':[u'わ',u'ワ'],
u'x':[u'ず',u'ズ'],
u'y':[u'ゆ',u'ユ'],
u'z':[u'ず',u'ズ'],
u'a\'' :[u'ああ',u'アー'], u'i\'':[u'いい', u'イー'],u'u\'':[u'うう',u'ウー'], u'e\'':[u'ええ',u'エー'], u'o\'':[u'おお',u'オー'],
u'\'' :[u'',u''],
u'_' :[u'・',u'・'],
u'tha':[u'ざ',u'ザ'], u'thi':[u'じ',u'ジ'], u'thu':[u'ず',u'ズ'], u'the':[u'ざ',u'ザ'], u'tho':[u'ぞ',u'ゾ'], u'thya':[u'つゃ',u'ツャ'], u'thyu':[u'つゅ',u'ツュ'], u'thyo':[u'つょ',u'ツョ'],
u'th':[u'つ',u'ツ'],
}
def romaji2hiragana(phrase):
if not isinstance(phrase, unicode):
raise NonUnicodeInputException('Input argument {phrase} is not unicode.'.format(phrase=phrase))
hiragana = u''
while phrase:
(h,p) = nibble(phrase)
hiragana += h[0]
phrase = p
return hiragana
def romaji2katakana(phrase):
if not isinstance(phrase, unicode):
raise NonUnicodeInputException('Input argument {phrase} is not unicode.'.format(phrase=phrase))
katakana = u''
while phrase:
(h,p) = nibble(phrase)
katakana += unicode(h[1])
phrase = p
return katakana
def nibble(phrase):
for i in reversed(range(4)):
nib = phrase[:i]
if nib in TRANSLITERATION_TABLE:
return (TRANSLITERATION_TABLE[nib], phrase[i:])
return ([phrase[:1], phrase[:1]], phrase[1:])
def main():
parser = argparse.ArgumentParser(description='Transliterate romaji to hiragana.')
parser.add_argument('-k', '--katakana', help='Transliterate to katakana',action='store_true')
parser.add_argument('words', nargs='*', help='Words to transliterate')
args = parser.parse_args()
for word in args.words:
word = word.decode('utf-8')
if args.katakana:
print(romaji2katakana(word).encode('utf-8'))
else:
print(romaji2hiragana(word).encode('utf-8'))
if __name__ == "__main__":
main()
| true | true |
f7f896d55ea6eb4aa8b6ad3fba92d72de70b3d83 | 1,193 | py | Python | shibgreen/wallet/settings/user_settings.py | BTCgreen-Network/shibgreen-blockchain | b1e41e82ad849775543aa36fefc0c0d03e13f6e8 | [
"Apache-2.0"
] | 12 | 2021-11-10T02:52:38.000Z | 2022-03-22T10:19:45.000Z | shibgreen/wallet/settings/user_settings.py | BTCgreen-Network/shibgreen-blockchain | b1e41e82ad849775543aa36fefc0c0d03e13f6e8 | [
"Apache-2.0"
] | 13 | 2021-11-16T03:09:34.000Z | 2022-03-09T00:45:05.000Z | shibgreen/wallet/settings/user_settings.py | BTCgreen-Network/shibgreen-blockchain | b1e41e82ad849775543aa36fefc0c0d03e13f6e8 | [
"Apache-2.0"
] | 1 | 2022-03-15T08:25:06.000Z | 2022-03-15T08:25:06.000Z | from typing import Any, Dict
from shibgreen.wallet.key_val_store import KeyValStore
from shibgreen.wallet.settings.default_settings import default_settings
from shibgreen.wallet.settings.settings_objects import BackupInitialized
class UserSettings:
settings: Dict[str, Any]
basic_store: KeyValStore
@staticmethod
async def create(
store: KeyValStore,
name: str = None,
):
self = UserSettings()
self.basic_store = store
self.settings = {}
await self.load_store()
return self
def _keys(self):
all_keys = [BackupInitialized]
return all_keys
async def load_store(self):
keys = self._keys()
for setting in keys:
name = setting.__name__
object = await self.basic_store.get_object(name, BackupInitialized)
if object is None:
object = default_settings[name]
assert object is not None
self.settings[name] = object
async def setting_updated(self, setting: Any):
name = setting.__class__.__name__
await self.basic_store.set_object(name, setting)
self.settings[name] = setting
| 28.404762 | 79 | 0.653814 | from typing import Any, Dict
from shibgreen.wallet.key_val_store import KeyValStore
from shibgreen.wallet.settings.default_settings import default_settings
from shibgreen.wallet.settings.settings_objects import BackupInitialized
class UserSettings:
settings: Dict[str, Any]
basic_store: KeyValStore
@staticmethod
async def create(
store: KeyValStore,
name: str = None,
):
self = UserSettings()
self.basic_store = store
self.settings = {}
await self.load_store()
return self
def _keys(self):
all_keys = [BackupInitialized]
return all_keys
async def load_store(self):
keys = self._keys()
for setting in keys:
name = setting.__name__
object = await self.basic_store.get_object(name, BackupInitialized)
if object is None:
object = default_settings[name]
assert object is not None
self.settings[name] = object
async def setting_updated(self, setting: Any):
name = setting.__class__.__name__
await self.basic_store.set_object(name, setting)
self.settings[name] = setting
| true | true |
f7f89750415ccae8c71fb8819d310bab36d668d5 | 14,455 | py | Python | pymongo/ocsp_support.py | ldennis/mongo-python-driver | cc029a1e6208863eaab453777363d3935b927f32 | [
"Apache-2.0"
] | 22 | 2015-05-18T07:04:36.000Z | 2021-08-02T03:01:43.000Z | pymongo/ocsp_support.py | ldennis/mongo-python-driver | cc029a1e6208863eaab453777363d3935b927f32 | [
"Apache-2.0"
] | 16 | 2022-02-01T06:06:00.000Z | 2022-02-01T06:21:40.000Z | pymongo/ocsp_support.py | ldennis/mongo-python-driver | cc029a1e6208863eaab453777363d3935b927f32 | [
"Apache-2.0"
] | 7 | 2022-02-05T20:29:14.000Z | 2022-03-26T13:16:44.000Z | # Copyright 2020-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you
# may not use this file except in compliance with the License. You
# may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
"""Support for requesting and verifying OCSP responses."""
import logging as _logging
import re as _re
from datetime import datetime as _datetime
from cryptography.exceptions import InvalidSignature as _InvalidSignature
from cryptography.hazmat.backends import default_backend as _default_backend
from cryptography.hazmat.primitives.asymmetric.dsa import (
DSAPublicKey as _DSAPublicKey)
from cryptography.hazmat.primitives.asymmetric.ec import (
ECDSA as _ECDSA,
EllipticCurvePublicKey as _EllipticCurvePublicKey)
from cryptography.hazmat.primitives.asymmetric.padding import (
PKCS1v15 as _PKCS1v15)
from cryptography.hazmat.primitives.asymmetric.rsa import (
RSAPublicKey as _RSAPublicKey)
from cryptography.hazmat.primitives.hashes import (
Hash as _Hash,
SHA1 as _SHA1)
from cryptography.hazmat.primitives.serialization import (
Encoding as _Encoding,
PublicFormat as _PublicFormat)
from cryptography.x509 import (
AuthorityInformationAccess as _AuthorityInformationAccess,
ExtendedKeyUsage as _ExtendedKeyUsage,
ExtensionNotFound as _ExtensionNotFound,
load_pem_x509_certificate as _load_pem_x509_certificate,
TLSFeature as _TLSFeature,
TLSFeatureType as _TLSFeatureType)
from cryptography.x509.oid import (
AuthorityInformationAccessOID as _AuthorityInformationAccessOID,
ExtendedKeyUsageOID as _ExtendedKeyUsageOID)
from cryptography.x509.ocsp import (
load_der_ocsp_response as _load_der_ocsp_response,
OCSPCertStatus as _OCSPCertStatus,
OCSPRequestBuilder as _OCSPRequestBuilder,
OCSPResponseStatus as _OCSPResponseStatus)
from requests import post as _post
from requests.exceptions import RequestException as _RequestException
# Note: the functions in this module generally return 1 or 0. The reason
# is simple. The entry point, ocsp_callback, is registered as a callback
# with OpenSSL through PyOpenSSL. The callback must return 1 (success) or
# 0 (failure).
_LOGGER = _logging.getLogger(__name__)
_CERT_REGEX = _re.compile(
b'-----BEGIN CERTIFICATE[^\r\n]+.+?-----END CERTIFICATE[^\r\n]+',
_re.DOTALL)
def _load_trusted_ca_certs(cafile):
"""Parse the tlsCAFile into a list of certificates."""
with open(cafile, 'rb') as f:
data = f.read()
# Load all the certs in the file.
trusted_ca_certs = []
backend = _default_backend()
for cert_data in _re.findall(_CERT_REGEX, data):
trusted_ca_certs.append(
_load_pem_x509_certificate(cert_data, backend))
return trusted_ca_certs
def _get_issuer_cert(cert, chain, trusted_ca_certs):
issuer_name = cert.issuer
for candidate in chain:
if candidate.subject == issuer_name:
return candidate
# Depending on the server's TLS library, the peer's cert chain may not
# include the self signed root CA. In this case we check the user
# provided tlsCAFile (ssl_ca_certs) for the issuer.
# Remove once we use the verified peer cert chain in PYTHON-2147.
if trusted_ca_certs:
for candidate in trusted_ca_certs:
if candidate.subject == issuer_name:
return candidate
return None
def _verify_signature(key, signature, algorithm, data):
# See cryptography.x509.Certificate.public_key
# for the public key types.
try:
if isinstance(key, _RSAPublicKey):
key.verify(signature, data, _PKCS1v15(), algorithm)
elif isinstance(key, _DSAPublicKey):
key.verify(signature, data, algorithm)
elif isinstance(key, _EllipticCurvePublicKey):
key.verify(signature, data, _ECDSA(algorithm))
else:
key.verify(signature, data)
except _InvalidSignature:
return 0
return 1
def _get_extension(cert, klass):
try:
return cert.extensions.get_extension_for_class(klass)
except _ExtensionNotFound:
return None
def _public_key_hash(cert):
public_key = cert.public_key()
# https://tools.ietf.org/html/rfc2560#section-4.2.1
# "KeyHash ::= OCTET STRING -- SHA-1 hash of responder's public key
# (excluding the tag and length fields)"
# https://stackoverflow.com/a/46309453/600498
if isinstance(public_key, _RSAPublicKey):
pbytes = public_key.public_bytes(
_Encoding.DER, _PublicFormat.PKCS1)
elif isinstance(public_key, _EllipticCurvePublicKey):
pbytes = public_key.public_bytes(
_Encoding.X962, _PublicFormat.UncompressedPoint)
else:
pbytes = public_key.public_bytes(
_Encoding.DER, _PublicFormat.SubjectPublicKeyInfo)
digest = _Hash(_SHA1(), backend=_default_backend())
digest.update(pbytes)
return digest.finalize()
def _get_certs_by_key_hash(certificates, issuer, responder_key_hash):
return [
cert for cert in certificates
if _public_key_hash(cert) == responder_key_hash and
cert.issuer == issuer.subject]
def _get_certs_by_name(certificates, issuer, responder_name):
return [
cert for cert in certificates
if cert.subject == responder_name and
cert.issuer == issuer.subject]
def _verify_response_signature(issuer, response):
# Response object will have a responder_name or responder_key_hash
# not both.
name = response.responder_name
rkey_hash = response.responder_key_hash
ikey_hash = response.issuer_key_hash
if name is not None and name == issuer.subject or rkey_hash == ikey_hash:
_LOGGER.debug("Responder is issuer")
# Responder is the issuer
responder_cert = issuer
else:
_LOGGER.debug("Responder is a delegate")
# Responder is a delegate
# https://tools.ietf.org/html/rfc6960#section-2.6
# RFC6960, Section 3.2, Number 3
certs = response.certificates
if response.responder_name is not None:
responder_certs = _get_certs_by_name(certs, issuer, name)
_LOGGER.debug("Using responder name")
else:
responder_certs = _get_certs_by_key_hash(certs, issuer, rkey_hash)
_LOGGER.debug("Using key hash")
if not responder_certs:
_LOGGER.debug("No matching or valid responder certs.")
return 0
# XXX: Can there be more than one? If so, should we try each one
# until we find one that passes signature verification?
responder_cert = responder_certs[0]
# RFC6960, Section 3.2, Number 4
ext = _get_extension(responder_cert, _ExtendedKeyUsage)
if not ext or _ExtendedKeyUsageOID.OCSP_SIGNING not in ext.value:
_LOGGER.debug("Delegate not authorized for OCSP signing")
return 0
if not _verify_signature(
issuer.public_key(),
responder_cert.signature,
responder_cert.signature_hash_algorithm,
responder_cert.tbs_certificate_bytes):
_LOGGER.debug("Delegate signature verification failed")
return 0
# RFC6960, Section 3.2, Number 2
ret = _verify_signature(
responder_cert.public_key(),
response.signature,
response.signature_hash_algorithm,
response.tbs_response_bytes)
if not ret:
_LOGGER.debug("Response signature verification failed")
return ret
def _build_ocsp_request(cert, issuer):
# https://cryptography.io/en/latest/x509/ocsp/#creating-requests
builder = _OCSPRequestBuilder()
builder = builder.add_certificate(cert, issuer, _SHA1())
return builder.build()
def _verify_response(issuer, response):
_LOGGER.debug("Verifying response")
# RFC6960, Section 3.2, Number 2, 3 and 4 happen here.
res = _verify_response_signature(issuer, response)
if not res:
return 0
# Note that we are not using a "tolerence period" as discussed in
# https://tools.ietf.org/rfc/rfc5019.txt?
now = _datetime.utcnow()
# RFC6960, Section 3.2, Number 5
if response.this_update > now:
_LOGGER.debug("thisUpdate is in the future")
return 0
# RFC6960, Section 3.2, Number 6
if response.next_update and response.next_update < now:
_LOGGER.debug("nextUpdate is in the past")
return 0
return 1
def _get_ocsp_response(cert, issuer, uri, ocsp_response_cache):
ocsp_request = _build_ocsp_request(cert, issuer)
try:
ocsp_response = ocsp_response_cache[ocsp_request]
_LOGGER.debug("Using cached OCSP response.")
except KeyError:
try:
response = _post(
uri,
data=ocsp_request.public_bytes(_Encoding.DER),
headers={'Content-Type': 'application/ocsp-request'},
timeout=5)
except _RequestException as exc:
_LOGGER.debug("HTTP request failed: %s", exc)
return None
if response.status_code != 200:
_LOGGER.debug("HTTP request returned %d", response.status_code)
return None
ocsp_response = _load_der_ocsp_response(response.content)
_LOGGER.debug(
"OCSP response status: %r", ocsp_response.response_status)
if ocsp_response.response_status != _OCSPResponseStatus.SUCCESSFUL:
return None
# RFC6960, Section 3.2, Number 1. Only relevant if we need to
# talk to the responder directly.
# Accessing response.serial_number raises if response status is not
# SUCCESSFUL.
if ocsp_response.serial_number != ocsp_request.serial_number:
_LOGGER.debug("Response serial number does not match request")
return None
if not _verify_response(issuer, ocsp_response):
# The response failed verification.
return None
_LOGGER.debug("Caching OCSP response.")
ocsp_response_cache[ocsp_request] = ocsp_response
return ocsp_response
def _ocsp_callback(conn, ocsp_bytes, user_data):
"""Callback for use with OpenSSL.SSL.Context.set_ocsp_client_callback."""
cert = conn.get_peer_certificate()
if cert is None:
_LOGGER.debug("No peer cert?")
return 0
cert = cert.to_cryptography()
chain = conn.get_peer_cert_chain()
if not chain:
_LOGGER.debug("No peer cert chain?")
return 0
chain = [cer.to_cryptography() for cer in chain]
issuer = _get_issuer_cert(cert, chain, user_data.trusted_ca_certs)
must_staple = False
# https://tools.ietf.org/html/rfc7633#section-4.2.3.1
ext = _get_extension(cert, _TLSFeature)
if ext is not None:
for feature in ext.value:
if feature == _TLSFeatureType.status_request:
_LOGGER.debug("Peer presented a must-staple cert")
must_staple = True
break
ocsp_response_cache = user_data.ocsp_response_cache
# No stapled OCSP response
if ocsp_bytes == b'':
_LOGGER.debug("Peer did not staple an OCSP response")
if must_staple:
_LOGGER.debug("Must-staple cert with no stapled response, hard fail.")
return 0
if not user_data.check_ocsp_endpoint:
_LOGGER.debug("OCSP endpoint checking is disabled, soft fail.")
# No stapled OCSP response, checking responder URI diabled, soft fail.
return 1
# https://tools.ietf.org/html/rfc6960#section-3.1
ext = _get_extension(cert, _AuthorityInformationAccess)
if ext is None:
_LOGGER.debug("No authority access information, soft fail")
# No stapled OCSP response, no responder URI, soft fail.
return 1
uris = [desc.access_location.value
for desc in ext.value
if desc.access_method == _AuthorityInformationAccessOID.OCSP]
if not uris:
_LOGGER.debug("No OCSP URI, soft fail")
# No responder URI, soft fail.
return 1
if issuer is None:
_LOGGER.debug("No issuer cert?")
return 0
_LOGGER.debug("Requesting OCSP data")
# When requesting data from an OCSP endpoint we only fail on
# successful, valid responses with a certificate status of REVOKED.
for uri in uris:
_LOGGER.debug("Trying %s", uri)
response = _get_ocsp_response(
cert, issuer, uri, ocsp_response_cache)
if response is None:
# The endpoint didn't respond in time, or the response was
# unsuccessful or didn't match the request, or the response
# failed verification.
continue
_LOGGER.debug("OCSP cert status: %r", response.certificate_status)
if response.certificate_status == _OCSPCertStatus.GOOD:
return 1
if response.certificate_status == _OCSPCertStatus.REVOKED:
return 0
# Soft fail if we couldn't get a definitive status.
_LOGGER.debug("No definitive OCSP cert status, soft fail")
return 1
_LOGGER.debug("Peer stapled an OCSP response")
if issuer is None:
_LOGGER.debug("No issuer cert?")
return 0
response = _load_der_ocsp_response(ocsp_bytes)
_LOGGER.debug(
"OCSP response status: %r", response.response_status)
# This happens in _request_ocsp when there is no stapled response so
# we know if we can compare serial numbers for the request and response.
if response.response_status != _OCSPResponseStatus.SUCCESSFUL:
return 0
if not _verify_response(issuer, response):
return 0
# Cache the verified, stapled response.
ocsp_response_cache[_build_ocsp_request(cert, issuer)] = response
_LOGGER.debug("OCSP cert status: %r", response.certificate_status)
if response.certificate_status == _OCSPCertStatus.REVOKED:
return 0
return 1
| 39.386921 | 82 | 0.68184 |
import logging as _logging
import re as _re
from datetime import datetime as _datetime
from cryptography.exceptions import InvalidSignature as _InvalidSignature
from cryptography.hazmat.backends import default_backend as _default_backend
from cryptography.hazmat.primitives.asymmetric.dsa import (
DSAPublicKey as _DSAPublicKey)
from cryptography.hazmat.primitives.asymmetric.ec import (
ECDSA as _ECDSA,
EllipticCurvePublicKey as _EllipticCurvePublicKey)
from cryptography.hazmat.primitives.asymmetric.padding import (
PKCS1v15 as _PKCS1v15)
from cryptography.hazmat.primitives.asymmetric.rsa import (
RSAPublicKey as _RSAPublicKey)
from cryptography.hazmat.primitives.hashes import (
Hash as _Hash,
SHA1 as _SHA1)
from cryptography.hazmat.primitives.serialization import (
Encoding as _Encoding,
PublicFormat as _PublicFormat)
from cryptography.x509 import (
AuthorityInformationAccess as _AuthorityInformationAccess,
ExtendedKeyUsage as _ExtendedKeyUsage,
ExtensionNotFound as _ExtensionNotFound,
load_pem_x509_certificate as _load_pem_x509_certificate,
TLSFeature as _TLSFeature,
TLSFeatureType as _TLSFeatureType)
from cryptography.x509.oid import (
AuthorityInformationAccessOID as _AuthorityInformationAccessOID,
ExtendedKeyUsageOID as _ExtendedKeyUsageOID)
from cryptography.x509.ocsp import (
load_der_ocsp_response as _load_der_ocsp_response,
OCSPCertStatus as _OCSPCertStatus,
OCSPRequestBuilder as _OCSPRequestBuilder,
OCSPResponseStatus as _OCSPResponseStatus)
from requests import post as _post
from requests.exceptions import RequestException as _RequestException
_LOGGER = _logging.getLogger(__name__)
_CERT_REGEX = _re.compile(
b'-----BEGIN CERTIFICATE[^\r\n]+.+?-----END CERTIFICATE[^\r\n]+',
_re.DOTALL)
def _load_trusted_ca_certs(cafile):
with open(cafile, 'rb') as f:
data = f.read()
trusted_ca_certs = []
backend = _default_backend()
for cert_data in _re.findall(_CERT_REGEX, data):
trusted_ca_certs.append(
_load_pem_x509_certificate(cert_data, backend))
return trusted_ca_certs
def _get_issuer_cert(cert, chain, trusted_ca_certs):
issuer_name = cert.issuer
for candidate in chain:
if candidate.subject == issuer_name:
return candidate
if trusted_ca_certs:
for candidate in trusted_ca_certs:
if candidate.subject == issuer_name:
return candidate
return None
def _verify_signature(key, signature, algorithm, data):
try:
if isinstance(key, _RSAPublicKey):
key.verify(signature, data, _PKCS1v15(), algorithm)
elif isinstance(key, _DSAPublicKey):
key.verify(signature, data, algorithm)
elif isinstance(key, _EllipticCurvePublicKey):
key.verify(signature, data, _ECDSA(algorithm))
else:
key.verify(signature, data)
except _InvalidSignature:
return 0
return 1
def _get_extension(cert, klass):
try:
return cert.extensions.get_extension_for_class(klass)
except _ExtensionNotFound:
return None
def _public_key_hash(cert):
public_key = cert.public_key()
xcluding the tag and length fields)"
# https://stackoverflow.com/a/46309453/600498
if isinstance(public_key, _RSAPublicKey):
pbytes = public_key.public_bytes(
_Encoding.DER, _PublicFormat.PKCS1)
elif isinstance(public_key, _EllipticCurvePublicKey):
pbytes = public_key.public_bytes(
_Encoding.X962, _PublicFormat.UncompressedPoint)
else:
pbytes = public_key.public_bytes(
_Encoding.DER, _PublicFormat.SubjectPublicKeyInfo)
digest = _Hash(_SHA1(), backend=_default_backend())
digest.update(pbytes)
return digest.finalize()
def _get_certs_by_key_hash(certificates, issuer, responder_key_hash):
return [
cert for cert in certificates
if _public_key_hash(cert) == responder_key_hash and
cert.issuer == issuer.subject]
def _get_certs_by_name(certificates, issuer, responder_name):
return [
cert for cert in certificates
if cert.subject == responder_name and
cert.issuer == issuer.subject]
def _verify_response_signature(issuer, response):
# Response object will have a responder_name or responder_key_hash
# not both.
name = response.responder_name
rkey_hash = response.responder_key_hash
ikey_hash = response.issuer_key_hash
if name is not None and name == issuer.subject or rkey_hash == ikey_hash:
_LOGGER.debug("Responder is issuer")
# Responder is the issuer
responder_cert = issuer
else:
_LOGGER.debug("Responder is a delegate")
# Responder is a delegate
# https://tools.ietf.org/html/rfc6960#section-2.6
# RFC6960, Section 3.2, Number 3
certs = response.certificates
if response.responder_name is not None:
responder_certs = _get_certs_by_name(certs, issuer, name)
_LOGGER.debug("Using responder name")
else:
responder_certs = _get_certs_by_key_hash(certs, issuer, rkey_hash)
_LOGGER.debug("Using key hash")
if not responder_certs:
_LOGGER.debug("No matching or valid responder certs.")
return 0
# XXX: Can there be more than one? If so, should we try each one
# until we find one that passes signature verification?
responder_cert = responder_certs[0]
# RFC6960, Section 3.2, Number 4
ext = _get_extension(responder_cert, _ExtendedKeyUsage)
if not ext or _ExtendedKeyUsageOID.OCSP_SIGNING not in ext.value:
_LOGGER.debug("Delegate not authorized for OCSP signing")
return 0
if not _verify_signature(
issuer.public_key(),
responder_cert.signature,
responder_cert.signature_hash_algorithm,
responder_cert.tbs_certificate_bytes):
_LOGGER.debug("Delegate signature verification failed")
return 0
# RFC6960, Section 3.2, Number 2
ret = _verify_signature(
responder_cert.public_key(),
response.signature,
response.signature_hash_algorithm,
response.tbs_response_bytes)
if not ret:
_LOGGER.debug("Response signature verification failed")
return ret
def _build_ocsp_request(cert, issuer):
# https://cryptography.io/en/latest/x509/ocsp/#creating-requests
builder = _OCSPRequestBuilder()
builder = builder.add_certificate(cert, issuer, _SHA1())
return builder.build()
def _verify_response(issuer, response):
_LOGGER.debug("Verifying response")
# RFC6960, Section 3.2, Number 2, 3 and 4 happen here.
res = _verify_response_signature(issuer, response)
if not res:
return 0
# Note that we are not using a "tolerence period" as discussed in
# https://tools.ietf.org/rfc/rfc5019.txt?
now = _datetime.utcnow()
# RFC6960, Section 3.2, Number 5
if response.this_update > now:
_LOGGER.debug("thisUpdate is in the future")
return 0
# RFC6960, Section 3.2, Number 6
if response.next_update and response.next_update < now:
_LOGGER.debug("nextUpdate is in the past")
return 0
return 1
def _get_ocsp_response(cert, issuer, uri, ocsp_response_cache):
ocsp_request = _build_ocsp_request(cert, issuer)
try:
ocsp_response = ocsp_response_cache[ocsp_request]
_LOGGER.debug("Using cached OCSP response.")
except KeyError:
try:
response = _post(
uri,
data=ocsp_request.public_bytes(_Encoding.DER),
headers={'Content-Type': 'application/ocsp-request'},
timeout=5)
except _RequestException as exc:
_LOGGER.debug("HTTP request failed: %s", exc)
return None
if response.status_code != 200:
_LOGGER.debug("HTTP request returned %d", response.status_code)
return None
ocsp_response = _load_der_ocsp_response(response.content)
_LOGGER.debug(
"OCSP response status: %r", ocsp_response.response_status)
if ocsp_response.response_status != _OCSPResponseStatus.SUCCESSFUL:
return None
# RFC6960, Section 3.2, Number 1. Only relevant if we need to
# talk to the responder directly.
# Accessing response.serial_number raises if response status is not
# SUCCESSFUL.
if ocsp_response.serial_number != ocsp_request.serial_number:
_LOGGER.debug("Response serial number does not match request")
return None
if not _verify_response(issuer, ocsp_response):
# The response failed verification.
return None
_LOGGER.debug("Caching OCSP response.")
ocsp_response_cache[ocsp_request] = ocsp_response
return ocsp_response
def _ocsp_callback(conn, ocsp_bytes, user_data):
cert = conn.get_peer_certificate()
if cert is None:
_LOGGER.debug("No peer cert?")
return 0
cert = cert.to_cryptography()
chain = conn.get_peer_cert_chain()
if not chain:
_LOGGER.debug("No peer cert chain?")
return 0
chain = [cer.to_cryptography() for cer in chain]
issuer = _get_issuer_cert(cert, chain, user_data.trusted_ca_certs)
must_staple = False
# https://tools.ietf.org/html/rfc7633#section-4.2.3.1
ext = _get_extension(cert, _TLSFeature)
if ext is not None:
for feature in ext.value:
if feature == _TLSFeatureType.status_request:
_LOGGER.debug("Peer presented a must-staple cert")
must_staple = True
break
ocsp_response_cache = user_data.ocsp_response_cache
# No stapled OCSP response
if ocsp_bytes == b'':
_LOGGER.debug("Peer did not staple an OCSP response")
if must_staple:
_LOGGER.debug("Must-staple cert with no stapled response, hard fail.")
return 0
if not user_data.check_ocsp_endpoint:
_LOGGER.debug("OCSP endpoint checking is disabled, soft fail.")
# No stapled OCSP response, checking responder URI diabled, soft fail.
return 1
# https://tools.ietf.org/html/rfc6960#section-3.1
ext = _get_extension(cert, _AuthorityInformationAccess)
if ext is None:
_LOGGER.debug("No authority access information, soft fail")
# No stapled OCSP response, no responder URI, soft fail.
return 1
uris = [desc.access_location.value
for desc in ext.value
if desc.access_method == _AuthorityInformationAccessOID.OCSP]
if not uris:
_LOGGER.debug("No OCSP URI, soft fail")
# No responder URI, soft fail.
return 1
if issuer is None:
_LOGGER.debug("No issuer cert?")
return 0
_LOGGER.debug("Requesting OCSP data")
# When requesting data from an OCSP endpoint we only fail on
# successful, valid responses with a certificate status of REVOKED.
for uri in uris:
_LOGGER.debug("Trying %s", uri)
response = _get_ocsp_response(
cert, issuer, uri, ocsp_response_cache)
if response is None:
# The endpoint didn't respond in time, or the response was
# failed verification.
continue
_LOGGER.debug("OCSP cert status: %r", response.certificate_status)
if response.certificate_status == _OCSPCertStatus.GOOD:
return 1
if response.certificate_status == _OCSPCertStatus.REVOKED:
return 0
# Soft fail if we couldn't get a definitive status.
_LOGGER.debug("No definitive OCSP cert status, soft fail")
return 1
_LOGGER.debug("Peer stapled an OCSP response")
if issuer is None:
_LOGGER.debug("No issuer cert?")
return 0
response = _load_der_ocsp_response(ocsp_bytes)
_LOGGER.debug(
"OCSP response status: %r", response.response_status)
if response.response_status != _OCSPResponseStatus.SUCCESSFUL:
return 0
if not _verify_response(issuer, response):
return 0
ocsp_response_cache[_build_ocsp_request(cert, issuer)] = response
_LOGGER.debug("OCSP cert status: %r", response.certificate_status)
if response.certificate_status == _OCSPCertStatus.REVOKED:
return 0
return 1
| true | true |
f7f8984d50378b09bb47165eb745e2489a6bba31 | 175,370 | py | Python | Tag10kbytome.py | Fahsaiiii2608/tk | 44b4a14de11a328a9fa2ca6d0c23b1f52850adff | [
"MIT"
] | null | null | null | Tag10kbytome.py | Fahsaiiii2608/tk | 44b4a14de11a328a9fa2ca6d0c23b1f52850adff | [
"MIT"
] | null | null | null | Tag10kbytome.py | Fahsaiiii2608/tk | 44b4a14de11a328a9fa2ca6d0c23b1f52850adff | [
"MIT"
] | 2 | 2018-11-04T11:17:46.000Z | 2019-01-20T14:10:48.000Z | # -*- coding: utf-8 -*-
#SELFBOT_MAN_PC
import LINETCR
from LINETCR.lib.curve.ttypes import *
from datetime import datetime
from time import sleep
from bs4 import BeautifulSoup
from threading import Thread
from googletrans import Translator
from gtts import gTTS
import time,random,sys,json,codecs,threading,glob,urllib,urllib2,urllib3,re,string,ast,os,subprocess,six,ast,pytz,requests,tempfile
ka = LINETCR.LINE()
ka.login(token='Esi6ZiwdDw5gpjEU9Cv9.Um990fn/eZ7CJP/I34GAIq./PwWHpfnEuZGLqzlrLpgHw0ThH0QploYuYq6xQKUdZc=')
ka.loginResult()
#kb = LINETCR.LINE()
#kb.login(token='MAN')
#kb.loginResult()
#kc = LINETCR.LINE()
#kc.login(token='MAN')
#kc.loginResult()
#kd = LINETCR.LINE()
#kd.login(token='MAN')
#kd.loginResult()
#ke = LINETCR.LINE()
#ke.login(token='MAN')
#ke.loginResult()
#kf = LINETCR.LINE()
#kf.login(token='MAN')
#kf.loginResult()
#kg = LINETCR.LINE()
#kg.login(token='MAN')
#kg.loginResult()
#kh = LINETCR.LINE()
#kh.login(token='MAN')
#kh.loginResult()
#ki = LINETCR.LINE()
#ki.login(token='MAN')
#ki.loginResult()
#kj = LINETCR.LINE()
#kj.login(token='MAN')
#kj.loginResult()
backup = LINETCR.LINE()
backup.login(token='Esi6ZiwdDw5gpjEU9Cv9.Um990fn/eZ7CJP/I34GAIq./PwWHpfnEuZGLqzlrLpgHw0ThH0QploYuYq6xQKUdZc=')
backup.loginResult()
print "Login.. SELFBOT_MAN_PROTECT"
reload(sys)
sys.setdefaultencoding('utf-8')
helpMessage ="""Thailand : SELFBOT_MAN_PC
╭══════════════════╮
║ ♨️ SELFBOT_MAN_PC_HELP ♨️
║͜͡☆➣ คำสั่ง-> 「Tome1」
║͜͡☆➣ คำสั่ง-> 「Tome2」
║͜͡☆➣ คำสั่ง-> 「Tome3」
║͜͡☆➣ คำสั่ง-> 「Tome4」
╰══════════════════╯
╭══════════════════╮
║ ♨️ติดตั้งชุดระบบป้องกัน[Protect]♨️
║ ลงคำสั่ง ครั้งเดียว ระบบทำงานยกเชุด
║•คำสั่ง.. Allprotect on
║•คำสั่ง.. Allprotect off
║•คำสั่ง.. เปิดระบบป้องกัน
║•คำสั่ง.. ปิดระบบป้องกัน
╰══════════════════╯
╭══════════════════╮
║ ♨️รับทำเชลบอท [SELFBOT] กันรัน
║•รับทำ..[ชุดบอทป้องกัน+Protect+]
║•รับทำ..[ชุดบอทส่วนตัว+Kicker+]
║•รับทำ..[บอทแท๊ก,ทั้งกลุ่ม+Mention]
║•รับทำ..[ชุดบอทบิน] ☞มีครบทุกฟังชั่น
╰══════════════════╯
──────┅═ইई═┅──────
สอบถามรายละเอียดเพิ่มเติม.. Link⤵️
http://line.me/ti/p/~1ove..neverdie
──────┅═ইई═┅──────
"""
creatorMessage ="""HELP_creator
╭══════════════════╮
║ ♨️ SELFBOT_MAN_PC_HELP ♨️
╰══════════════════╯
╭══════════════════╮
║͜͡☆➣ steal
║͜͡☆➣ /invitemeto:
║͜͡☆➣ Clear/Cancel
║͜͡☆➣ Ourl/Curl
║͜͡☆➣ Link on/off
║͜͡☆➣ Status/Set
║͜͡☆➣ Lurking
║͜͡☆➣ Gurl/URL/ลิงก์กลุ่ม
║͜͡☆➣ เข้า = Staff in
║͜͡☆➣ ออก = Staff bye
║͜͡☆➣ ตัวหลักออก = @bye
║͜͡☆➣ Leave all group
║͜͡☆➣ Banlist/บัญชีดำ
║͜͡☆➣ Clear ban/Cb/ล้างดำ
║͜͡☆➣ Bot restart
║͜͡☆➣ Glist
║͜͡☆➣ Glistmid
║͜͡☆➣
║͜͡☆➣ Tagall/Mention all
╰══════════════════╯
"""
setMessage ="""HELP_settings
╭══════════════════╮
║ ♨️ SELFBOT_MAN_PC_HELP ♨️
╰══════════════════╯
╭══════════════════╮
║͜͡☆➣ Purge on/off
║͜͡☆➣ Cancel on/off
║͜͡☆➣ Qr on/off
║͜͡☆➣ Contact on/off
║͜͡☆➣ Join on/off
║͜͡☆➣ Leave on/off
║͜͡☆➣ Share on/off
║͜͡☆➣ Simisimi on/off
║͜͡☆➣ Sider on/off
║͜͡☆➣ Lurking on/off
║͜͡☆➣ Lurking reset
║͜͡☆➣ Admin add @
║͜͡☆➣ Admin remove @
║͜͡☆➣ Sambutan on/off
║͜͡☆➣ Cancelinvite on/off
╰══════╬💀╬══════╯
"""
publikMessage ="""HELP_selfbot
╭══════════════════╮
║ ♨️ SELFBOT_MAN_PC_HELP ♨️
╰══════════════════╯
╭══════════════════╮
║͜͡☆➣ Me
║͜͡☆➣ Creator
║͜͡☆➣ Ginfo
║͜͡☆➣ Adminlist
║͜͡☆➣ List group
║͜͡☆➣ Absen
║͜͡☆➣ Respon
╰══════════════════╯
"""
mediaMessage ="""HELP_media
╭══════════════════╮
║ ♨️ SELFBOT_MAN_PC_HELP ♨️
╰══════════════════╯
╭══════════════════╮
║͜͡☆➣ /music
║͜͡☆➣ /lirik
║͜͡☆➣ /ig Instagrams
║͜͡☆➣ /yt: Youtubelink:
║͜͡☆➣ Say-id
║͜͡☆➣ Say-en
║͜͡☆➣ Say welcome
║͜͡☆➣ Playstore
║͜͡☆➣ /apakah
║͜͡☆➣ /hari
║͜͡☆➣ /berapa
║͜͡☆➣ /berapakah
║͜͡☆➣ /kapan
║͜͡☆➣ Image
║͜͡☆➣ Runtime
║͜͡☆➣ Tr-en แปลภาษา
║͜͡☆➣ Tr-id แปลภาษา
║͜͡☆➣ En@id อังกฤษ-อินโด
║͜͡☆➣ Id@en อินโด-อังกฤษ
║͜͡☆➣ SearchID:ใส่ใอดีไลน์
║͜͡☆➣ LineID:ใส่ใอดีไลน์
║͜͡☆➣ /เพลสโตร์:
║͜͡☆➣ /รูปภาพ:
║͜͡☆➣ /เช็คเวลาบอท
╰═════════════════╯
🔴✦เปิด/ปิดข้อความต้อนรับ✦🔴
╭══════════════════╮
║͜͡☆🔴➣ Hhx1 on ➠เปิดต้อนรับ
║͜͡☆🔴➣ Hhx1 off ➠ปิดต้อนรับ
║͜͡☆🔴➣ Hhx2 on ➠เปิดออกกลุ่ม
║͜͡☆🔴➣ Hhx2 off ➠ปิดออกกลุ่ม
║͜͡☆🔴➣ Hhx3 on ➠เปิดพูดถึงคนลบ
║͜͡☆🔴➣ Hhx3 off ➠ปิดพูดถึงคนลบ
║͜͡☆🔴➣ Mbot on ➠เปิดเเจ้งเตือน
║͜͡☆🔴➣ Mbot off ➠ปิดเเจ้งเตือน
║͜͡☆🔴➣ M on ➠เปิดเเจ้งเตือนตนเอง
║͜͡☆🔴➣ M off ➠ปิดเเจ้งเตือนตนเอง
║͜͡☆🔴➣ Tag on ➠เปิดกล่าวถึงเเท็ค
║͜͡☆🔴➣ Tag off ➠ปิดกล่าวถึงเเท็ค
║͜͡☆🔴➣ Kicktag on ➠เปิดเตะคนเเท็ค
║͜͡☆🔴➣ Kicktag off ➠ปิดเตะคนเเท็ค
╰═════════════════╯
🔴✦โหมดตั้งค่าข้อความ✦🔴
╭═════════════════╮
║͜͡☆🔴➣Hhx1˓: ➠ไส่ข้อความต้อนรับ
║͜͡☆🔴➣Hhx2˓: ➠ไส่ข้อความออกจากกลุ่ม
║͜͡☆🔴➣Hhx3˓: ➠ไส่ข้อความเมื่อมีคนลบ
║͜͡☆🔴➣Tag1: ➠ใส่ข้อความแทค
║͜͡☆🔴➣Tag2: ➠ ใส่ข้อความแทค
╰═════════════════╯
🔴✦โหมดเช็คตั้งค่าข้อความ✦🔴
╭═════════════════╮
║͜͡☆🔴➣Hhx1 ➠เช็คข้อความต้อนรับ
║͜͡☆🔴➣Hhx2 ➠เช็คข้อความคนออก
║͜͡☆🔴➣Hhx3 ➠เช็คข้อความคนลบ
║͜͡☆🔴➣Tag1 ➠เช็ตข้อความแทค
║͜͡☆🔴➣Tag2 ➠เช็คข้อความแทค
╰═════════════════╯
╭═════════════════╮
║─┅═✥ᴛᴇᴀᴍᵀᴴᴬᴵᴸᴬᴺᴰʙᴏᴛLɪɴᴇ✥═┅
║•─✯͜͡✯TOME★BOTLINE✯͜͡✯─•
╰═════════════════╯
ลิ้ง:http://line.me/ti/p/~tomebotline
──┅═✥===========✥═┅──
"""
KAC = [ka]#,kb,kc,kd,ke,kf,kg,kh,ki,kj]
mid = ka.getProfile().mid
#Amid = kb.getProfile().mid
#Bmid = kc.getProfile().mid
#Cmid = kd.getProfile().mid
#Dmid = ke.getProfile().mid
#Emid = kf.getProfile().mid
#Fmid = kg.getProfile().mid
#Gmid = kh.getProfile().mid
#Hmid = ki.getProfile().mid
#Imid = kj.getProfile().mid
#Jmid = backup.getProfile().mid
Bots=["ub8cf7dd0537e133edc8e9fa2df881a89",mid]#,Amid,Bmid,Cmid,Dmid,Emid,Fmid,Gmid,Hmid,Imid,Jmid]
self = ["ub8cf7dd0537e133edc8e9fa2df881a89",mid]
admin = "ub8cf7dd0537e133edc8e9fa2df881a89"
admsa = "ub8cf7dd0537e133edc8e9fa2df881a89"
owner = "ub8cf7dd0537e133edc8e9fa2df881a89"
adminMID = "ub8cf7dd0537e133edc8e9fa2df881a89"
Creator="ub8cf7dd0537e133edc8e9fa2df881a89"
owner=["ub8cf7dd0537e133edc8e9fa2df881a89"]
admin=["ub8cf7dd0537e133edc8e9fa2df881a89"]
#=========BACKUP========#
contact = ka.getProfile()
backup1 = ka.getProfile()
backup1.displayName = contact.displayName
backup1.statusMessage = contact.statusMessage
backup1.pictureStatus = contact.pictureStatus
#contact = kb.getProfile()
#backup2 = kb.getProfile()
#backup2.displayName = contact.displayName
#backup2.statusMessage = contact.statusMessage
#backup2.pictureStatus = contact.pictureStatus
#contact = kc.getProfile()
#backup3 = kc.getProfile()
#backup3.displayName = contact.displayName
#backup3.statusMessage = contact.statusMessage
#backup3.pictureStatus = contact.pictureStatus
#contact = kd.getProfile()
#backup4 = kd.getProfile()
#backup4.displayName = contact.displayName
#backup4.statusMessage = contact.statusMessage
#backup4.pictureStatus = contact.pictureStatus
#contact = ke.getProfile()
#backup5 = ke.getProfile()
#backup5.displayName = contact.displayName
#backup5.statusMessage = contact.statusMessage
#backup5.pictureStatus = contact.pictureStatus
#contact = kf.getProfile()
#backup6 = kf.getProfile()
#backup6.displayName = contact.displayName
#backup6.statusMessage = contact.statusMessage
#backup6.pictureStatus = contact.pictureStatus
#contact = kg.getProfile()
#backup7 = kg.getProfile()
#backup7.displayName = contact.displayName
#backup7.statusMessage = contact.statusMessage
#backup7.pictureStatus = contact.pictureStatus
#contact = kh.getProfile()
#backup8 = kh.getProfile()
#backup8.displayName = contact.displayName
#backup8.statusMessage = contact.statusMessage
#backup8.pictureStatus = contact.pictureStatus
#contact = ki.getProfile()
#backup9 = ki.getProfile()
#backup9.displayName = contact.displayName
#backup9.statusMessage = contact.statusMessage
#backup9.pictureStatus = contact.pictureStatus
#contact = kj.getProfile()
#backup10 = kj.getProfile()
#backup10.displayName = contact.displayName
#backup10.statusMessage = contact.statusMessage
#backup10.pictureStatus = contact.pictureStatus
#===========================================#
responsename = ka.getProfile().displayName
#responsename2 = kb.getProfile().displayName
#responsename3 = kc.getProfile().displayName
#responsename4 = kd.getProfile().displayName
#responsename5 = ke.getProfile().displayName
#responsename6 = kf.getProfile().displayName
#responsename7 = kg.getProfile().displayName
#responsename8 = kh.getProfile().displayName
#responsename9 = ki.getProfile().displayName
#responsename10 = kj.getProfile().displayName
wait = {
"contact":False,
"Bot":{},
'autoAdd':False,
"autoJoin":True,
"detectMention":True,
"kickMention":False,
"steal":False,
"autoCancel":{"on":True,"members":1},
"leaveRoom":True,
"timeline":True,
"likeOn":True,
"Timeline":True,
"autoAdd":False,
"lang":"JP",
"commentOn":True,
"comment1":"""
[ AOTO LIKE ]
[ SELF BOT ]
[ รับติดตั้ง เชลบอท ราคาประหยัด ]
─┅═✥ᴛᴇᴀᴍᵀᴴᴬᴵᴸᴬᴺᴰʙᴏᴛLɪɴᴇ✥═┅─
•─✯͜͡✯TOME★BOTLINE✯͜͡✯─•
http://line.me/ti/p/~tomebotline
▀██──▄███▄─▀██─██▀██▀▀▀█
─██─███─███─██─██─██▄█
─██─▀██▄██▀─▀█▄█▀─██▀█
▄██▄▄█▀▀▀─────▀──▄██▄▄▄█
📲 โทรศัพท์ 0928081567
""",
"comment1":"""
_________มีเซลบอท________จำหน่าย
________88888888________8888888
______888888888888____88888888888
__888888822222222222888882222888888
_888888822222222222222882222222228888
▀██▀─▄███▄─▀██─██▀██▀▀█
▒██─███─███─██─██─██▄█
▒██─▀██▄██▀─▀█▄█▀─██▀█
▄██▄▄█▀▀▀─────▀──▄██▄▄█
_888882222222222222222_____88888888
___8888888882222______88888888888
______88888_TOMEBOTLINE_8888888
________88_TEAMBOTTHAILAND_88
__________88888888888888888
______________88888888888
________________8888
╔•═•-⊰⊱•══•⊰⊱•═•⊰⊱•══•⊰⊱•═•╗
〘•สนใจติดต่อที่ลิ้งด้านล่าง•〙
👇👇👇👇
™〖Ĵắ¢ҝҝїě〗🌷TOME🎀BOTLINE🌷
™〖Ĵắ¢ҝҝїě〗☞ᵀËÄMBOTTHAILAND
http://line.me/ti/p/~tomebotline
╚•══•-⊰⊱•═•⊰⊱•═•⊰⊱•══•⊰ ⊱•═•╝
""",
# "comment3":"👍Auto Like By SELFBOT_MAN_PC",
# "comment4":"👍Auto Like By SELFBOT_MAN_PC",
# "comment6":"👍Auto Like By SELFBOT_MAN_PC",
# "comment7":"👍Auto Like By SELFBOT_MAN_PC",
# "comment8":"👍Auto Like By SELFBOT_MAN_PC",
# "comment9":"👍Auto Like By SELFBOT_MAN_PC",
# "comment10":"👍Auto Like By SELFBOT_MAN_PC",
# "comment5":"👍Auto Like By SELFBOT_MAN_PC \n(รับทำเชลบอทกันรัน) บอทป้องกัน บอทแท๊ก",
"commentOn":True,
"acommentOn":False,
"bcommentOn":False,
"ccommentOn":False,
"commentBlack":{},
"wblack":False,
"dblack":False,
"wblacklist":False,
"dblacklist":False,
"Protectgr":False,
"Protectjoin":False,
"Protectcancl":False,
"Protectcancel":False,
"protectionOn":False,
"atjointicket":True,
"blacklist":{},
"steal":{},
"Hhx1":False,
"Hhx2":False,
"Hhx3":False,
"Notifed":False,
"Notifedbot":False,
"atjointicket":False,
"pnharfbot":{},
"pname":{},
"pro_name":{},
"tag1":"\n[🔯ยังไม่มีข้อความ ตอบกลับ🔯]",
"tag2":"\n[🔯ยังไม่มีข้อความ ตอบกลับ🔯]",
"posts":False,
"message":"Thank For Add Me.. \n\n คุยเรื่องบอทปรึกษาได้ครับ มีครบทุกฟังชั่น\nhttp://line.me/ti/p/~tomebotline \n(รับติดตั้งบอทSiri V10 และ รับทำเชลบอทกันรัน) \nเปิดสอนเขียนโปรแกรมบอท ชุดบอทป้องกัน บอทแท๊ก บอทแจ้งเตือนและต้อนรับสมาชิกเข้ากลุ่ม \n\nสนใจทักมาสอบถามได้ครับ \nLine ID. 1ove..neverdie",
"Sambutan":True,
"Sider":{},
}
cctv = {
"cyduk":{},
"point":{},
"sidermem":{}
}
read = {
"readPoint":{},
"readMember":{},
"readTime":{},
"ROM":{}
}
wait2 = {
"readPoint":{},
"readMember":{},
"setTime":{},
"ROM":{}
}
settings = {
"simiSimi":{}
}
setTime = {}
setTime = read['readTime']
mulai = time.time()
def download_page(url):
version = (3,0)
cur_version = sys.version_info
if cur_version >= version:
import urllib,request
try:
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
req = urllib,request.Request(url, headers = headers)
resp = urllib,request.urlopen(req)
respData = str(resp.read())
return respData
except Exception as e:
print(str(e))
else:
import urllib2
try:
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
req = urllib2.Request(url, headers = headers)
response = urllib2.urlopen(req)
page = response.read()
return page
except:
return"Page Not found"
def _images_get_next_item(s):
start_line = s.find('rg_di')
if start_line == -1:
end_quote = 0
link = "no_links"
return link, end_quote
else:
start_line = s.find('"class="rg_meta"')
start_content = s.find('"ou"',start_line+90)
end_content = s.find(',"ow"',start_content-90)
content_raw = str(s[start_content+6:end_content-1])
return content_raw, end_content
def _images_get_all_items(page):
items = []
while True:
item, end_content = _images_get_next_item(page)
if item == "no_links":
break
else:
items.append(item)
time.sleep(0.1)
page = page[end_content:]
return items
def waktu(secs):
mins, secs = divmod(secs,60)
hours, mins = divmod(mins,60)
return '%02d Jam %02d Menit %02d Detik' % (hours, mins, secs)
def cms(string, commands): #/XXX, >XXX, ;XXX, ^XXX, %XXX, $XXX...
tex = ["+","@","/",">",";","^","%","$","^","サテラ:","サテラ:","サテラ:","サテラ:"]
for texX in tex:
for command in commands:
if string ==command:
return True
return False
def upload_tempimage(client):
'''
Upload a picture of a kitten. We don't ship one, so get creative!
'''
config = {
'album': album,
'name': 'bot auto upload',
'title': 'bot auto upload',
'description': 'bot auto upload'
}
print("Uploading image... ")
image = client.upload_from_path(image_path, config=config, anon=False)
print("Done")
print()
return image
def summon(to, nama):
aa = ""
bb = ""
strt = int(14)
akh = int(14)
nm = nama
for mm in nm:
akh = akh + 2
aa += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M":"""+json.dumps(mm)+"},"""
strt = strt + 6
akh = akh + 4
bb += "\xe2\x95\xa0 @x \n"
aa = (aa[:int(len(aa)-1)])
msg = Message()
msg.to = to
msg.text = "\xe2\x95\x94\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\n"+bb+"\xe2\x95\x9a\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90"
msg.contentMetadata ={'MENTION':'{"MENTIONEES":['+aa+']}','EMTVER':'4'}
print "[Command] Tag All"
try:
ka.sendMessage(msg)
except Exception as error:
print error
def sendAudio(self, to_, path):
M = Message()
M.text = None
M.to = to_
M.contentMetadata = None
M.contentPreview = None
M.contentType = 3
M_id = self._client.sendMessage(0,M).id
files = {
'file': open(path, 'rb'),
}
def sendMessage(to, text, contentMetadata={}, contentType=0):
mes = Message()
mes.to, mes.from_ = to, profile.mid
mes.text = text
mes.contentType, mes.contentMetadata = contentType, contentMetadata
if to not in messageReq:
messageReq[to] = -1
messageReq[to] += 1
def sendImage(self, to_, path):
M = Message(to=to_, text=None, contentType = 1)
M.contentMetadata = None
M.contentPreview = None
M2 = self._client.sendMessage(0,M)
M_id = M2.id
files = {
'file': open(path, 'rb'),
}
params = {
'name': 'media',
'oid': M_id,
'size': len(open(path, 'rb').read()),
'type': 'image',
'ver': '1.0',
}
data = {
'params': json.dumps(params)
}
r = self.post_content('https://obs-sg.line-apps.com/talk/m/upload.nhn', data=data, files=files)
if r.status_code != 201:
raise Exception('Upload image failure.')
return True
def sendImageWithURL(self, to_, url):
path = '%s/pythonLine-%i.data' % (tempfile.gettempdir(), randint(0, 9))
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(path, 'w') as f:
shutil.copyfileobj(r.raw, f)
else:
raise Exception('Download image failure.')
try:
self.sendImage(to_, path)
except:
try:
self.sendImage(to_, path)
except Exception as e:
raise e
def sendAudio(self, to_, path):
M = Message()
M.text = None
M.to = to_
M.contentMetadata = None
M.contentPreview = None
M.contentType = 3
M_id = self._client.sendMessage(0,M).id
files = {
'file': open(path, 'rb'),
}
params = {
'name': 'media',
'oid': M_id,
'size': len(open(path, 'rb').read()),
'type': 'audio',
'ver': '1.0',
}
data = {
'params': json.dumps(params)
}
r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
if r.status_code != 201:
raise Exception('Upload audio failure.')
return True
def sendAudioWithURL(self, to_, url):
path = self.downloadFileWithURL(url)
try:
self.sendAudio(to_, path)
except Exception as e:
raise Exception(e)
def sendAudioWithUrl(self, to_, url):
path = '%s/pythonLine-%1.data' % (tempfile.gettempdir(), randint(0, 9))
r = requests.get(url, stream=True, verify=False)
if r.status_code == 200:
with open(path, 'w') as f:
shutil.copyfileobj(r.raw, f)
else:
raise Exception('Download audio failure.')
try:
self.sendAudio(to_, path)
except Exception as e:
raise e
def sendVideo(self, to_, path):
M = Message(to=to_,contentType = 2)
M.contentMetadata = {
'VIDLEN' : '0',
'DURATION' : '0'
}
M.contentPreview = None
M_id = self.Talk.client.sendMessage(0,M).id
files = {
'file': open(path, 'rb'),
}
params = {
'name': 'media',
'oid': M_id,
'size': len(open(path, 'rb').read()),
'type': 'video',
'ver': '1.0',
}
data = {
'params': json.dumps(params)
}
r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
if r.status_code != 201:
raise Exception('Upload image failure.')
return True
def sendVideoWithURL(self, to_, url):
path = 'pythonLines.data'
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(path, 'w') as f:
shutil.copyfileobj(r.raw, f)
else:
raise Exception('Download Audio failure.')
try:
self.sendVideo(to_, path)
except Exception as e:
raise e
def sendGif(self, to_, path):
M = Message(to=to_,contentType = 1)
M.contentMetadata = {
'VIDLEN' : '0',
'DURATION' : '0'
}
M.contentPreview = None
M_id = self.Talk.client.sendMessage(0,M).id
files = {
'file': open(path, 'rb'),
}
params = {
'name': 'media',
'oid': M_id,
'size': len(open(path, 'rb').read()),
'type': 'image',
'ver': '1.0',
}
data = {
'params': json.dumps(params)
}
r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
if r.status_code != 201:
raise Exception('Upload Gif failure.')
return True
def sendGifWithURL(self, to_, url):
path = 'pythonLiness.data'
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(path, 'w') as f:
shutil.copyfileobj(r.raw, f)
else:
raise Exception('Download Gif failure.')
try:
self.sendGif(to_, path)
except Exception as e:
raise e
def downloadFileWithURL(self, fileUrl):
saveAs = '%s/pythonLine-%i.data' % (tempfile.gettempdir(), randint(0, 9))
r = self.get_content(fileUrl)
if r.status_code == 200:
with open(saveAs, 'wb') as f:
shutil.copyfileobj(r.raw, f)
return saveAs
else:
raise Exception('Download file failure.')
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
def bot(op):
try:
if op.type == 0:
return
if op.type == 5:
if wait["autoAdd"] == True:
ka.findAndAddContactsByMid(op.param1)
if(wait["message"]in[""," ","\n",None]):
pass
else:
ka.sendText(op.param1,str(wait["message"]))
if op.type == 55:
try:
group_id = op.param1
user_id=op.param2
subprocess.Popen('echo "'+ user_id+'|'+str(op.createdTime)+'" >> dataSeen/%s.txt' % group_id, shell=True, stdout=subprocess.PIPE, )
except Exception as e:
print e
if op.type == 55:
try:
if cctv['cyduk'][op.param1]==True:
if op.param1 in cctv['point']:
Name = ka.getContact(op.param2).displayName
if Name in cctv['sidermem'][op.param1]:
pass
else:
cctv['sidermem'][op.param1] += "\n• " + Name
if " " in Name:
nick = Name.split(' ')
if len(nick) == 2:
ka.sendText(op.param1, "Hi " + "[ " + Name + " ]" + "\ndo not take a peek here to chat😁 ")
time.sleep(0.2)
summon(op.param1,[op.param2])
else:
ka.sendText(op.param1, "Hi " + "[ " + Name + " ]" + "\ndo not take a peek here to chat😁 ")
time.sleep(0.2)
summon(op.param1,[op.param2])
else:
ka.sendText(op.param1, "Hi " + "☞ " + Name + " ☜" + "\ndo not take a peek here to chat😁 ")
time.sleep(0.2)
summon(op.param1,[op.param2])
else:
pass
else:
pass
except:
pass
else:
pass
#==============================================================================#
if op.type == 22:
if wait["leaveRoom"] == True:
ka.leaveRoom(op.param1)
if op.type == 24:
if wait["leaveRoom"] == True:
ka.leaveRoom(op.param1)
if op.type == 26:
msg = op.message
#==============================================================================#
if op.type == 13:
if mid in op.param3:
if wait["autoJoin"] == True:
if op.param2 in owner:
ka.acceptGroupInvitation(op.param1)
G = ka.getGroup(op.param1)
G.preventJoinByTicket = False
ka.updateGroup(G)
Ticket = ka.reissueGroupTicket(op.param1)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
# kc.acceptGroupInvitationByTicket(op.param1,Ticket)
# kd.acceptGroupInvitationByTicket(op.param1,Ticket)
# ke.acceptGroupInvitationByTicket(op.param1,Ticket)
# kf.acceptGroupInvitationByTicket(op.param1,Ticket)
# kg.acceptGroupInvitationByTicket(op.param1,Ticket)
# kh.acceptGroupInvitationByTicket(op.param1,Ticket)
# ki.acceptGroupInvitationByTicket(op.param1,Ticket)
# kj.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ka.updateGroup(G)
else:
ka.rejectGroupInvitation(op.param1)
# if Amid in op.param3:
# if wait["autoJoin"] == True:
# if op.param2 in owner:
# kb.acceptGroupInvitation(op.param1)
# else:
# kb.rejectGroupInvitation(op.param1)
# else:
# print "autoJoin is Off"
# if Bmid in op.param3:
# if wait["autoJoin"] == True:
# if op.param2 in owner:
# kc.acceptGroupInvitation(op.param1)
# else:
# kc.rejectGroupInvitation(op.param1)
# else:
# print "autoJoin is Off"
#
# if Cmid in op.param3:
# if wait["autoJoin"] == True:
# if op.param2 in owner:
# kd.acceptGroupInvitation(op.param1)
# else:
# kd.rejectGroupInvitation(op.param1)
# else:
# print "autoJoin is Off"
#
# if Dmid in op.param3:
# if wait["autoJoin"] == True:
# if op.param2 in owner:
# ke.acceptGroupInvitation(op.param1)
# else:
# ke.rejectGroupInvitation(op.param1)
# else:
# print "autoJoin is Off"
#
# if Emid in op.param3:
# if wait["autoJoin"] == True:
# if op.param2 in owner:
# kf.acceptGroupInvitation(op.param1)
# else:
# kf.rejectGroupInvitation(op.param1)
# else:
# print "autoJoin is Off"
#
#if Fmid in op.param3:
# if wait["autoJoin"] == True:
# if op.param2 in owner:
# kg.acceptGroupInvitation(op.param1)
# else:
# kg.rejectGroupInvitation(op.param1)
# else:
# print "autoJoin is Off"
# if Gmid in op.param3:
# if wait["autoJoin"] == True:
# if op.param2 in owner:
# kh.acceptGroupInvitation(op.param1)
# else:
# kh.rejectGroupInvitation(op.param1)
# else:
# print "autoJoin is Off"
# if Hmid in op.param3:
# if wait["autoJoin"] == True:
# if op.param2 in owner:
# ki.acceptGroupInvitation(op.param1)
# else:
# ki.rejectGroupInvitation(op.param1)
# else:
# print "autoJoin is Off"
# if Imid in op.param3:
# if wait["autoJoin"] == True:
# if op.param2 in owner:
# kj.acceptGroupInvitation(op.param1)
# else:
# kj.rejectGroupInvitation(op.param1)
# else:
# print "autoJoin is Off"
if Jmid in op.param3:
if wait["autoJoin"] == True:
if op.param2 in owner:
ka.acceptGroupInvitation(op.param1)
else:
ka.rejectGroupInvitation(op.param1)
else:
print "autoJoin is Off"
#=========================================================================#
if op.type == 13:
if mid in op.param3:
G = ka.getGroup(op.param1)
if wait["autoJoin"] == True:
if wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
ka.rejectGroupInvitation(op.param1)
else:
ka.acceptGroupInvitation(op.param1)
ka.sendText(op.param1, "Your invitation was declined\n\n[SELF BOT\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]]\n\nhttp://line.me/ti/p/9r-uE5EU09")
else:
ka.acceptGroupInvitation(op.param1)
ka.sendText(op.param1, "Your invitation was declined\n\n[SEL FBOT\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]]\n\nhttp://line.me/ti/p/9r-uE5EU09")
elif wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
ka.rejectGroupInvitation(op.param1)
else:
Inviter = op.param3.replace("",',')
InviterX = Inviter.split(",")
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, InviterX)
if matched_list == []:
pass
else:
ka.cancelGroupInvitation(op.param1, matched_list)
if Amid1 in op.param3:
G = ka.getGroup(op.param1)
if wait["autoJoin"] == True:
if wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
kb.rejectGroupInvitation(op.param1)
else:
kb.acceptGroupInvitation(op.param1)
else:
kb.acceptGroupInvitation(op.param1)
elif wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
kb.rejectGroupInvitation(op.param1)
else:
Inviter = op.param3.replace("",',')
InviterX = Inviter.split(",")
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, InviterX)
if matched_list == []:
pass
else:
kb.cancelGroupInvitation(op.param1, matched_list)
if Amid2 in op.param3:
G = ka.getGroup(op.param1)
if wait["autoJoin"] == True:
if wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
kc.rejectGroupInvitation(op.param1)
else:
kc.acceptGroupInvitation(op.param1)
else:
kc.acceptGroupInvitation(op.param1)
elif wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
kc.rejectGroupInvitation(op.param1)
#==============================================================================#
if op.type == 13:
if wait["Protectcancl"] == True:
group = ka.getGroup(op.param1)
gMembMids = [contact.mid for contact in group.invitee]
if op.param2 not in Bots or admin:
if op.param2 in Bots:
pass
elif op.param2 in owner:
pass
elif op.param2 in admin:
pass
else:
try:
ka.cancelGroupInvitation(op.param1, gMembMids)
ka.sendText(op.param1,ka.getContact(op.param2).displayName + "\n" + "Who do you want to invite ??? \nYou Are Not Our Admin, So We Cancel it.\nPlease Contact Admin/Owner")
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
random.choice(KAC).cancelGroupInvitation(op.param1, gMembMids)
random.choice(KAC).sendText(op.param1,random.choice(KAC).getContact(op.param2).displayName + "\n" + "🔘Who do you want to invite ??? \n🔘You Are Not Our Admin, So We Cancel it.\n🔘Please Contact Admin/Owner\n\n[ระบบออโต้ถูกเปิดใช้งาน]\n🔘การเชิญสมาชิกเข้าร่วมกลุ่ม ควรแจ้งให้ทราบ..\n🔘โดยผ่าน.. Admin:bot-group หรือลงข้อมูลสมาชิกไว้\n(หากผิดพลาดยังใง รบกวนทักแชท)")
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
#==============================================================================#
if op.type == 13:
if wait["Protectcancl"] == True:
if wait["blacklist"][op.param3] == True:
ka.sendText(op.param1,ka.getContact(op.param3).displayName + " On Blacklist Boss Man\n•We Will Cancel Invitation\n•by : SELFBOT_MAN_PROTECT")
random.choice(KAC).cancelGroupInvitation(op.param1,[op.param3])
#==============================================================================#
if op.type == 11:
if wait["Protectgr"] == True:
if ka.getGroup(op.param1).preventJoinByTicket == False:
if op.param2 in Bots:
pass
elif op.param2 in owner:
pass
elif op.param2 in admin:
pass
else:
random.choice(KAC).sendText(op.param1,random.choice(KAC).getContact(op.param2).displayName + "Dont Playing Link Group Bro")
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
random.choice(KAC).preventJoinByTicket = True
random.choice(KAC).sendText(op.param1,random.choice(KAC).getContact(op.param2).displayName + "\n" + "🔘We Enter Into Blacklist Boss Man")
wait["blacklist"][op.param2] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
#==============================================================================#
if op.type == 17:
if wait["Sambutan"] == True:
if op.param2 in owner:
return
ginfo = ka.getGroup(op.param1)
contact = ka.getContact(op.param2)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
ka.sendText(op.param1,"•Hello ↪️" + ka.getContact(op.param2).displayName + "↩️\n•Welcome To 🔛 " + str(ginfo.name) + " " + "\n•by : SELFBOT_MAN_PROTECT")
c = Message(to=op.param1, from_=None, text=None, contentType=13)
c.contentMetadata={'mid':op.param2}
ka.sendMessage(c)
ka.sendImageWithURL(op.param1,image)
d = Message(to=op.param1, from_=None, text=None, contentType=7)
d.contentMetadata={
"STKID": "247",
"STKPKGID": "3",
"STKVER": "100" }
ka.sendMessage(d)
print "MEMBER JOIN TO GROUP"
#==============================================================================#
if op.type == 15:
if wait["Sambutan"] == True:
if op.param2 in admin:
return
ka.sendText(op.param1,"Good Bye " + ka.getContact(op.param2).displayName + "\nSee You Next Time . . . (p′︵‵。) 🤗")
c = Message(to=op.param1, from_=None, text=None, contentType=13)
c.contentMetadata={'mid':op.param2}
ka.sendMessage(c)
random.choice(KAC).inviteIntoGroup(op.param1,[op.param2])
print "MEMBER HAS LEFT THE GROUP"
#==============================================================================#
if op.type == 17: #Protect Join
if wait["Protectjoin"] == True:
if wait["blacklist"][op.param2] == True:
ka.sendText(op.param1,ka.getContact(op.param2).displayName + " On Blacklist Boss Man\n•We Will Kick 👀")
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
#==============================================================================#
if op.type == 17:
if wait["Notifed"] == True:
if op.param2 in owner:
return
ginfo = ka.getGroup(op.param1)
contact = ka.getContact(op.param2)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
ka.sendText(op.param1,"•สวัสดีจ้าคนมาใหม่ ↪" + ka.getContact(op.param2).displayName + "↩️\n•ยินดีต้อนรับสู่ห้อง\n 🔛 " + str(ginfo.name) + " " + "\n\n•by : SELFBOT TOME↔BOTLINE")
c = Message(to=op.param1, from_=None, text=None, contentType=13)
c.contentMetadata={'mid':op.param2}
ka.sendMessage(c)
ka.sendImageWithURL(op.param1,image)
d = Message(to=op.param1, from_=None, text=None, contentType=7)
d.contentMetadata={
"STKID": "247",
"STKPKGID": "3",
"STKVER": "100" }
ka.sendMessage(d)
print "MEMBER JOIN TO GROUP"
#==============================================================================#
if op.type == 15:
if wait["Notifed"] == True:
if op.param2 in admin:
return
ka.sendText(op.param1,"Good Bye " + ka.getContact(op.param2).displayName + "\nSee You Next Time . . . (p′︵‵。) 🤗")
c = Message(to=op.param1, from_=None, text=None, contentType=13)
c.contentMetadata={'mid':op.param2}
ka.sendMessage(c)
ka.sendImageWithURL(op.param1,image)
random.choice(KAC).inviteIntoGroup(op.param1,[op.param2])
print "MEMBER HAS LEFT THE GROUP"
#==============================================================================#
if op.type == 19:
if wait["Notifed"] == True:
if op.param2 in Bots:
return
ka.sendText(op.param1,cl.getContact(op.param2).displayName + "\n ไม่น่าจะจุกเท่าไหร่หรอก ")
print "MEMBER HAS KICKOUT FROM THE GROUP"
if op.type == 15:
if wait["Notifedbot"] == True:
if op.param2 in Bots:
return
ki1.sendText(op.param1,cl.getContact(op.param2).displayName + "\n\n Bye~bye ")
ki2.sendText(op.param1,cl.getContact(op.param2).displayName + "\n\n Bye~bye ")
print "MEMBER OUT GROUP"
if op.type == 17:
if wait["Notifedbot"] == True:
if op.param2 in Bots:
return
ginfo = cka.getGroup(op.param1)
contact = ka.getContact(op.param2)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
ka.sendImageWithURL(op.param1,image)
ka.sendText(op.param1,cl.getContact(op.param2).displayName + "\n\n[🙋ยินดี���อนรับ][By. ☬ധู้さန້ণق↔ധഖาໄฟ☬]")
print "MEMBER HAS JOIN THE GROUP"
if op.type == 19:
if wait["Notifedbot"] == True:
if op.param2 in Bots:
return
ki1.sendText(op.param1,cl.getContact(op.param2).displayName + "\n ไม่น่าจะจุกเท่าไหร่หรอก ")
ki2.sendText(op.param1,cl.getContact(op.param2).displayName + "\n ไม่น่าจะจุกเท่าไหร่หรอก ")
print "MEMBER HAS KICKOUT FROM THE GROUP"
# if op.type == 15:
# if wait["bcommentOn"] == True:
# if op.param2 in Bots:
# return
# cl.sendText(op.param1,cl.getContact(op.param2).displayName + "\n" + str(wait["bcomment"]))
# print "MEMBER OUT GROUP"
# if op.type == 17:
# if wait["acommentOn"] == True:
# if op.param2 in Bots:
# return
# cl.sendText(op.param1,cl.getContact(op.param2).displayName + "\n" + str(wait["acomment"]))
# print "MEMBER HAS JOIN THE GROUP"
#==============================================================================#
if op.type == 17:
if wait["acommentOn"] == True:
if op.param2 in Bots:
return
ginfo = ka.getGroup(op.param1)
contact = ka.getContact(op.param2)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
ka.sendText(op.param1,"•Hello ↪️" + ka.getContact(op.param2).displayName + "↩️\n•Welcome To 🔛 " + str(wait["acommentOn"]) + " " + "\n•by : SELFBOTTOME↔BOTLINE")
c = Message(to=op.param1, from_=None, text=None, contentType=13)
c.contentMetadata={'mid':op.param2}
ka.sendMessage(c)
ka.sendImageWithURL(op.param1,image)
d = Message(to=op.param1, from_=None, text=None, contentType=7)
d.contentMetadata={
"STKID": "247",
"STKPKGID": "3",
"STKVER": "100" }
ka.sendMessage(d)
print "MEMBER JOIN TO GROUP"
#==============================================================================#
if op.type == 15:
if wait["bcommentOn"] == True:
if op.param2 in Bots:
return
ka.sendText(op.param1,"Good Bye " + ka.getContact(op.param2).displayName + str(["bcommentOn"]))
c = Message(to=op.param1, from_=None, text=None, contentType=13)
c.contentMetadata={'mid':op.param2}
ka.sendMessage(c)
ka.sendImageWithURL(op.param1,image)
random.choice(KAC).inviteIntoGroup(op.param1,[op.param2])
print "MEMBER HAS LEFT THE GROUP"
#==============================================================================#
if op.type == 19:
if wait["ccommentOn"] == True:
if op.param2 in Bots:
return
ka.sendText(op.param1,cl.getContact(op.param2).displayName + "\n" + str(wait["ccomment"]))
print "MEMBER HAS KICKOUT FROM THE GROUP"
#==============================================================================#
if op.type == 19: #Member Ke Kick
if op.param2 in Bots:
pass
elif op.param2 in owner:
pass
elif op.param2 in admin:
pass
else:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
wait["blacklist"][op.param2] = True
#==============================================================================#
# if op.type == 26:
# msg = op.message
# if msg.contentType == 16:
# url = msg.contentMetadata['postEndUrl']
# ka.like(url[25:58], url[66:], likeType=1001)
# ka.comment(url[25:58], url[66:], wait["comment1"])
# ki1.like(url[25:58], url[66:], likeType=1001)
# ki1.comment(url[25:58], url[66:], wait["comment1"])
# ki2.like(url[25:58], url[66:], likeType=1001)
# ki2.comment(url[25:58], url[66:], wait["comment1"])
# ki3.like(url[25:58], url[66:], likeType=1001)
# ki3.comment(url[25:58], url[66:], wait["comment1"])
# ki4.like(url[25:58], url[66:], likeType=1001)
# ki4.comment(url[25:58], url[66:], wait["comment1"])
# ki5.like(url[25:58], url[66:], likeType=1001)
# ki5.comment(url[25:58], url[66:], wait["comment1"])
# ki6.like(url[25:58], url[66:], likeType=1001)
# ki6.comment(url[25:58], url[66:], wait["comment1"])
# ki7.like(url[25:58], url[66:], likeType=1001)
# ki7.comment(url[25:58], url[66:], wait["comment1"])
# ki8.like(url[25:58], url[66:], likeType=1001)
# ki8.comment(url[25:58], url[66:], wait["comment1"])
# ki9.like(url[25:58], url[66:], likeType=1001)
# ki9.comment(url[25:58], url[66:], wait["comment1"])
# ki10.like(url[25:58], url[66:], likeType=1001)
# ki10.comment(url[25:58], url[66:], wait["comment1"])
# print ("AUTO LIKE SELFBOT")
# print ("Auto Like By.☬ധู้さန້ণق↔ധഖาໄฟ☬")
#==============================================================================#
if op.type == 19:
if op.param2 in Bots:
pass
elif op.param2 in owner:
pass
elif op.param2 in admin:
pass
else:
if op.param3 in mid:
if op.param2 not in Bots or owner:
G = kj.getGroup(op.param1)
G.preventJoinByTicket = False
kj.updateGroup(G)
Ticket = kj.reissueGroupTicket(op.param1)
backup.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
backup.kickoutFromGroup(op.param1,[op.param2])
H = backup.getGroup(op.param1)
H.preventJoinByTicket = False
backup.updateGroup(H)
Ticket = backup.reissueGroupTicket(op.param1)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = kj.getGroup(op.param1)
G.preventJoinByTicket = True
kj.updateGroup(G)
backup.leaveGroup(op.param1)
wait["blacklist"][op.param2] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
#==============================================================================#
elif op.param3 in Amid:
if op.param2 not in Bots or owner:
G = kc.getGroup(op.param1)
kc.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
kc.updateGroup(G)
Ticket = kc.reissueGroupTicket(op.param1)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = kc.getGroup(op.param1)
G.preventJoinByTicket = True
kc.updateGroup(G)
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in Bmid:
if op.param2 not in Bots or owner:
G = kd.getGroup(op.param1)
kd.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
kd.updateGroup(G)
Ticket = kd.reissueGroupTicket(op.param1)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = kd.getGroup(op.param1)
G.preventJoinByTicket = True
kd.updateGroup(G)
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in Cmid:
if op.param2 not in Bots or owner:
G = ke.getGroup(op.param1)
ke.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
ke.updateGroup(G)
Ticket = ke.reissueGroupTicket(op.param1)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = ke.getGroup(op.param1)
G.preventJoinByTicket = True
ke.updateGroup(G)
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in Dmid:
if op.param2 not in Bots or owner:
G = kf.getGroup(op.param1)
kf.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
kf.updateGroup(G)
Ticket = kf.reissueGroupTicket(op.param1)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = kf.getGroup(op.param1)
G.preventJoinByTicket = True
kf.updateGroup(G)
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in Emid:
if op.param2 not in Bots or owner:
G = kg.getGroup(op.param1)
kg.kickoutFromGroup(op.param1,[op.param2])
G.reventJoinByTicket = False
kg.updateGroup(G)
Ticket = kg.reissueGroupTicket(op.param1)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = kg.getGroup(op.param1)
G.preventJoinByTicket = True
kg.updateGroup(G)
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in Fmid:
if op.param2 not in Bots or owner:
G = kh.getGroup(op.param1)
kh.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
kh.updateGroup(G)
Ticket = kh.reissueGroupTicket(op.param1)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = kh.getGroup(op.param1)
G.preventJoinByTicket = True
kh.updateGroup(G)
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in Gmid:
if op.param2 not in Bots or owner:
G = ki.getGroup(op.param1)
ki.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
ki.updateGroup(G)
Ticket = ki.reissueGroupTicket(op.param1)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = ki.getGroup(op.param1)
G.preventJoinByTicket = True
ki.updateGroup(G)
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in Hmid:
if op.param2 not in Bots or owner:
G = kj.getGroup(op.param1)
kj.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
kj.updateGroup(G)
Ticket = kj.reissueGroupTicket(op.param1)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = kj.getGroup(op.param1)
G.preventJoinByTicket = True
kj.updateGroup(G)
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in Imid:
if op.param2 not in Bots or owner:
G = kb.getGroup(op.param1)
kb.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
kb.updateGroup(G)
Ticket = kb.reissueGroupTicket(op.param1)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = kb.getGroup(op.param1)
G.preventJoinByTicket = True
kb.updateGroup(G)
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in Jmid:
if op.param2 not in Bots or owner:
G = ka.getGroup(op.param1)
ka.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
ka.updateGroup(G)
Ticket = ka.reissueGroupTicket(op.param1)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = ka.getGroup(op.param1)
G.preventJoinByTicket = True
ka.updateGroup(G)
wait["blacklist"][op.param2] = True
#===============================================================================#
if op.type == 19: #admin
if op.param2 in Bots:
pass
elif op.param2 in owner:
pass
elif op.param2 in admin:
pass
else:
try:
if op.param3 in admin:
if op.param2 not in Bots or owner:
if op.param2 in Bots:
pass
elif op.param2 in owner:
pass
else:
try:
ka.kickoutFromGroup(op.param1,[op.param2])
kb.kickoutFromGroup(op.param1,[op.param2])
kc.kickoutFromGroup(op.param1,[op.param2])
kd.kickoutFromGroup(op.param1,[op.param2])
ke.kickoutFromGroup(op.param1,[op.param2])
kf.kickoutFromGroup(op.param1,[op.param2])
kg.kickoutFromGroup(op.param1,[op.param2])
kh.kickoutFromGroup(op.param1,[op.param2])
ki.kickoutFromGroup(op.param1,[op.param2])
kj.kickoutFromGroup(op.param1,[op.param2])
ka.inviteIntoGroup(op.param1,[op.param3])
kb.inviteIntoGroup(op.param1,[op.param3])
kc.inviteIntoGroup(op.param1,[op.param3])
kd.inviteIntoGroup(op.param1,[op.param3])
ke.inviteIntoGroup(op.param1,[op.param3])
kf.inviteIntoGroup(op.param1,[op.param3])
kg.inviteIntoGroup(op.param1,[op.param3])
kh.inviteIntoGroup(op.param1,[op.param3])
ki.inviteIntoGroup(op.param1,[op.param3])
kj.inviteIntoGroup(op.param1,[op.param3])
wait["blacklist"][op.param2] = True
except:
random.choice(KAC).getGroup(op.param1)
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
random.choice(KAC).inviteIntoGroup(op.param1,[op.param3])
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in owner:
if op.param2 not in Bots or owner:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
#ka.inviteIntoGroup(op.param1,[op.param3])
wait["blacklist"][op.param2] = True
except:
random.choice(KAC).getGroup(op.param1)
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
#random.choice(KAC).inviteIntoGroup(op.param1,[op.param3])
wait["blacklist"][op.param2] = True
except:
try:
ka.kickoutFromGroup(op.param1,[op.param2])
wait["blacklist"][op.param2] = True
except:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
wait["blacklist"][op.param2] = True
#==============================================================================#
if op.type == 22:
if wait["leaveRoom"] == True:
ka.leaveRoom(op.param1)
if op.type == 24:
if wait["leaveRoom"] == True:
ka.leaveRoom(op.param1)
#==============================================================================#
if op.type == 25:
msg = op.message
if op.type == 19:
if op.param2 in Bots:
pass
elif op.param2 in admin:
pass
else:
msg = Message(to=op.param1, from_=None, text=None, contentType=13)
msg.contentMetadata={'mid':op.param2}
ka.sendMessage(msg)
ka.sendText(op.param1,ka.getContact(op.param2).displayName + " Kick 👀")
#==============================================================================#
if op.type == 11:
if op.param2 in Bots:
pass
elif op.param2 in admin:
pass
else:
msg = Message(to=op.param1, from_=None, text=None, contentType=13)
msg.contentMetadata={'mid':op.param2}
ka.sendMessage(msg)
#==============================================================================#
if op.type == 25:
msg = op.message
if msg.to in settings["simiSimi"]:
if settings["simiSimi"][msg.to] == True:
if msg.text is not None:
text = msg.text
r = requests.get("http://api.ntcorp.us/chatbot/v1/?text=" + text.replace(" ","+") + "&key=beta1.nt")
data = r.text
data = json.loads(data)
if data['status'] == 200:
if data['result']['result'] == 100:
ka.sendText(msg.to, "「MAN-auto-Chat」⤵️" + "\n" + data['result']['response'].encode('utf-8'))
#==============================================================================#
if 'MENTION' in msg.contentMetadata.keys() != None:
if wait["detectMention"] == True:
contact = ka.getContact(msg.from_)
cName = contact.displayName
balas = [cName + "\n" + str(wait["tag1"]) , cName + "\n" + str(wait["tag2"])]
ret_ = "[Auto Respond] " + random.choice(balas)
name = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata['MENTION'])
mentionees = mention['MENTIONEES']
for mention in mentionees:
if mention['M'] in Bots:
ka.sendText(msg.to,ret_)
break
# if 'MENTION' in msg.contentMetadata.keys() != None:
# if wait["detectMention"] == True:
# contact = cl.getContact(msg.from_)
# cName = contact.displayName
# balas = ["Dont Tag Me!! Im Busy",cName + ""]
# ret_ = "[Auto] " + random.choice(balas)
# name = re.findall(r'@(\w+)', msg.text)
# mention = ast.literal_eval(msg.contentMetadata['MENTION'])
# mentionees = mention['MENTIONEES']
# for mention in mentionees:
# if mention['M'] in Bots:
# cl.sendText(msg.to,ret_)
# msg.contentType = 7
# msg.text = ''
# msg.contentMetadata = {
# 'STKPKGID': '9662',
# 'STKTXT': '[]',
# 'STKVER': '16',
# 'STKID':'697'
# }
# cl.sendMessage(msg)
# break
if "MENTION" in msg.contentMetadata.keys() != None:
if wait['detectMention'] == True:
contact = ka.getContact(msg.from_)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
cName = contact.displayName
msg.text1 = "@"+cName+" "
balas = ["\n╭═════════════════╮\n║͜͡☆➣🔒มีเชลบอทลบรัน พร้อมคิกเก้อ💟\n║͜͡☆➣🔒ลบบินกลุ่ม ออโต้ไลค์\n║͜͡☆➣ 🔒และอื่นๆอีกมากมาย\n║͜͡☆➣🔒กันสมาชิกเปิดลิ้งห้อง\n║͜͡☆➣🔒กันรัน\n║͜͡☆➣🔒กันสมาชิกเชิญคนนอกเข้า\n║͜͡☆➣🔒กันสมาชิกเปลี่ยนชื่อกลุ่ม\n║͜͡☆➣🔒กันคนนอกเข้ามาลบคนในกลุ่ม\n║͜͡☆➣🔒และยังมีเซลกันรันอีกด้วย ราคา150บาท\n║͜͡☆➣👉สนใจติดต่อลิ้งด้านล่างเรยครับ👈\n║͜͡☆➣โอนเข้าบัญชี💲เทานั้น\n║͜͡☆➣สนใจ แอดมาคุยได้\n╰═════════════════╯\n╭═════════════════╮\n║͜͡☆➣http://line.me/ti/p/~dmc.072_tome\n║͜͡☆➣http://line.me/ti/p/~tomebotline\n╰═════════════════╯"]
ret_ = msg.text1 + random.choice(balas)
name = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata["MENTION"])
mentionees = mention['MENTIONEES']
for mention in mentionees:
if mention['M'] in Bots:
ka.sendText(msg.to,ret_)
msg.contentType = 7
msg.text = ''
msg.contentMetadata = {
'STKPKGID': '35485149',
'STKTXT': '[]',
'STKVER': '16',
'STKID':'3232633'
}
ka.sendImageWithURL(msg.to,image)
break
if 'MENTION' in msg.contentMetadata.keys() != None:
if wait["kickMention"] == True:
contact = ka.getContact(msg.from_)
cName = contact.displayName
balas = ["Dont Tag Me!! Im Busy",cName + " Ngapain Ngetag?",cName + " Nggak Usah Tag-Tag! Kalo Penting Langsung Pc Aja","-_-","Alin lagi off", cName + " Kenapa Tag saya?","SPAM PC aja " + cName, "Jangan Suka Tag gua " + cName, "Kamu siapa " + cName + "?", "Ada Perlu apa " + cName + "?","Tenggelamkan tuh yang suka tag pake BOT","Tersummon -_-"]
ret_ = "[Auto Respond] " + random.choice(balas)
name = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata['MENTION'])
mentionees = mention['MENTIONEES']
for mention in mentionees:
if mention['M'] in Bots:
ka.sendText(msg.to,ret_)
ka.kickoutFromGroup(msg.to,[msg.from_])
break
#=====================================================================#
if op.type == 32:
if wait["Protectcancel"] == True:
if op.param2 not in admin:
if op.param2 in Bots:
pass
elif op.param2 in admin:
pass
else:
random.choice(KAC).sendText(op.param1,random.choice(KAC).getContact(op.param2).displayName + " •Cancel Invitation 👀")
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
random.choice(KAC).inviteIntoGroup(op.param1,[op.param3])
wait["blacklist"][op.param2] = True
#==============================================================================#
if msg.toType == 1:
if wait["leaveRoom"] == True:
ka.leaveRoom(msg.to)
#==============================================================================#
if msg.contentType == 16:
url = msg.contentMetadata("line://home/post?userMid="+mid+"&postId="+"new_post")
ka.like(url[25:58], url[66:], likeType=1001)
#==============================================================================#
if op.type == 25:
msg = op.message
if op.type == 25:
msg = op.message
if msg.text in ["Bot on"]:
wait["Bot"] = True
ka.sendText(msg.to,"Bot Sudah on Kembali.")
if op.type == 25:
if wait["Bot"] == True:
msg = op.message
if op.type == 25:
msg = op.message
#==============================================================================#
if msg.contentType == 13:
if msg.from_ in owner:
if wait["steal"] == True:
_name = msg.contentMetadata["displayName"]
copy = msg.contentMetadata["mid"]
groups = ka.getGroup(msg.to)
pending = groups.invitee
targets = []
for s in groups.members:
if _name in s.displayName:
print "[Target] Stealed"
break
else:
targets.append(copy)
if targets == []:
pass
else:
for target in targets:
try:
ka.findAndAddContactsByMid(target)
contact = ka.getContact(target)
cu = ka.channel.getCover(target)
path = str(cu)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
ka.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nMid :\n" + msg.contentMetadata["mid"] + "\n\nBio :\n" + contact.statusMessage)
ka.sendText(msg.to,"Profile Picture " + contact.displayName)
ka.sendImageWithURL(msg.to,image)
ka.sendText(msg.to,"Cover " + contact.displayName)
ka.sendImageWithURL(msg.to,path)
wait["steal"] = False
break
except:
pass
#==============================================================================#
elif wait["wblack"] == True:
if msg.contentMetadata["mid"] in wait["commentBlack"]:
ka.sendText(msg.to,"already")
wait["wblack"] = False
else:
wait["commentBlack"][msg.contentMetadata["mid"]] = True
wait["wblack"] = False
ka.sendText(msg.to,"decided not to comment")
#==============================================================================#
elif wait["dblack"] == True:
if msg.contentMetadata["mid"] in wait["commentBlack"]:
del wait["commentBlack"][msg.contentMetadata["mid"]]
ka.sendText(msg.to,"deleted")
wait["dblack"] = False
else:
wait["dblack"] = False
ka.sendText(msg.to,"It is not in the black list")
#==============================================================================#
elif wait["wblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
ka.sendText(msg.to,"already")
wait["wblacklist"] = False
else:
wait["blacklist"][msg.contentMetadata["mid"]] = True
wait["wblacklist"] = False
ka.sendText(msg.to,"aded")
#==============================================================================#
elif wait["dblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
del wait["blacklist"][msg.contentMetadata["mid"]]
ka.sendText(msg.to,"deleted")
wait["dblacklist"] = False
else:
wait["dblacklist"] = False
ka.sendText(msg.to,"It is not in the black list")
#==============================================================================#
elif wait["contact"] == True:
msg.contentType = 0
ka.sendText(msg.to,msg.contentMetadata["mid"])
if 'displayName' in msg.contentMetadata:
contact = ka.getContact(msg.contentMetadata["mid"])
try:
cu = ka.channel.getCover(msg.contentMetadata["mid"])
except:
cu = ""
ka.sendText(msg.to,"[displayName]:\n" + msg.contentMetadata["displayName"] + "\n[mid]:\n" + msg.contentMetadata["mid"] + "\n[statusMessage]:\n" + contact.statusMessage + "\n[pictureStatus]:\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n[coverURL]:\n" + str(cu))
else:
contact = ka.getContact(msg.contentMetadata["mid"])
try:
cu = ka.channel.getCover(msg.contentMetadata["mid"])
except:
cu = ""
ka.sendText(msg.to,"[displayName]:\n" + contact.displayName + "\n[mid]:\n" + msg.contentMetadata["mid"] + "\n[statusMessage]:\n" + contact.statusMessage + "\n[pictureStatus]:\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n[coverURL]:\n" + str(cu))
elif msg.contentType == 16:
if wait["timeline"] == True:
msg.contentType = 0
if wait["lang"] == "JP":
msg.text = "🔼POST link🔼 URL⤵️\n" + msg.contentMetadata["postEndUrl"]
else:
msg.text = "URL→\n" + msg.contentMetadata["postEndUrl"]
ka.sendText(msg.to,msg.text)
elif msg.text is None:
return
#==============================================================================#
elif msg.text in ["Key","Staff help","help","Help"]:
ka.sendText(msg.to,helpMessage)
elif msg.text in ["Tome1","help creator","Man:creator"]:
ka.sendText(msg.to,creatorMessage)
elif msg.text in ["Tome2","help self","Man:selfbot"]:
ka.sendText(msg.to,publikMessage)
elif msg.text in ["Tome3","Man:set","Man:setting"]:
ka.sendText(msg.to,setMessage)
elif msg.text in ["Tome4","Media","Man:media"]:
ka.sendText(msg.to,mediaMessage)
#==============================================================================#
elif msg.text == "Ginfo":
if msg.toType == 2:
ginfo = ka.getGroup(msg.to)
try:
gCreator = ginfo.creator.displayName
except:
gCreator = "Error"
if wait["lang"] == "JP":
if ginfo.invitee is None:
sinvitee = "0"
else:
sinvitee = str(len(ginfo.invitee))
if ginfo.preventJoinByTicket == True:
u = "Close"
else:
u = "Open"
ka.sendText(msg.to,"[Group name]\n" + str(ginfo.name) + "\n\n[Gid]\n" + msg.to + "\n\n[Group creator]\n" + gCreator + "\n\n[Profile status]\nhttp://dl.profile.line.naver.jp/" + ginfo.pictureStatus + "\n\n•Members group : " + str(len(ginfo.members)) + " members\n•MemberInvite : " + sinvitee + " people\n•URL group : " + u + "\n•by : SELFBOT_MAN_PROTECT")
else:
ka.sendText(msg.to,"[group name]\n" + str(ginfo.name) + "\n[gid]\n" + msg.to + "\n[group creator]\n" + gCreator + "\n[profile status]\nhttp://dl.profile.line.naver.jp/" + ginfo.pictureStatus)
else:
if wait["lang"] == "JP":
ka.sendText(msg.to,"Can not be used outside the group")
else:
ka.sendText(msg.to,"Not for use less than group")
elif msg.text is None:
return
#==============================================================================#
elif msg.text in ["Creator","Owner"]:
msg.contentType = 13
msg.contentMetadata = {'mid': 'ua0a82f37270408d4e63b0b1fbb0e4c7f'}
ka.sendMessage(msg)
#==============================================================================#
elif msg.text in ["@1","@2"]:
msg.contentType = 13
ka.sendMessage(msg.to,"ปรึกษาเรื่องบอท ทักได้คับ\n☞ เปิดสอนเขียนบอท Selfbot กันรัน\n☞ รับทำเชลบอท ในราคาเบาๆ Selfbot⤵️\n🔹 ฟังชั่นบอท 🔹\n -0- เช็คสมาชิกอ่านกลุ่มได้\n -1- @แท๊กสมาชิกได้ทั้งกลุ่ม\n -2- มีข้อความต้อนรับสมาชิก เข้า-ออก (Auto)\n -3- รายงานสมาชิกที่ยุ่งเกี่ยวกับระบบกลุ่ม (รายงานข้อมูล)\n -4- มีลูกเล่นหลากหลายและยังแปลภาษาได้ด้วย \n4.1 (ชุด-Media) \n4.2 (ชุด-Steal) \n4.3 (ชุด-Hack) \n4.4 (ชุด-Translator)\n\n☞สำหรับคนที่:มีอริเยอะ ช่วยป้องกัน 2มาตฐาน\n - (ระบบกันรัน : ยกเลิกรันออโต้)\n - (ล้างรัน : ลงคำสั่งเพื่อยกเลิกกลุ่มรัน Auto)\n - และยังป้องกันการดึงแชทรวม (Virus chat) การดึงเข้าแชทรวมด้วยไวรัส แชท,ไวรัส จะถูกยกเลิกการดึงอัตโนมัติ\n\nหมดห่วงทุกการเกรียน สนใจเรียนวิชาหรือสั่งทำ เปิดเช่า⤵️ สอบถามรายละเอียดเพิ่มเติม.. Link⤵️\n🆔line.me/ti/p/~tomebotline \n\nปล. สำหรับคนที่อยากทำชุดบอท(Protect)..ไว้ป้องกันกลุ่ม\n✅ลูกค้าที่ต้องการทำบอท(kicker)เพิ่ม ตัวล่ะ 50บาท\nTHAILAND : creator & admin bot\nName creator : SELFBOT MAN-PC ✧꧁ℳѦれ꧂✧\nprotect & media @2018")
#==============================================================================#
elif "Admin add @" in msg.text:
if msg.from_ in owner:
print "[Command]Staff add executing"
_name = msg.text.replace("Admin add @","")
_nametarget = _name.rstrip(' ')
gs = ka.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
random.choice(KAC).sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
ka.findAndAddContactsByMid(target)
kb.findAndAddContactsByMid(target)
kc.findAndAddContactsByMid(target)
kd.findAndAddContactsByMid(target)
ke.findAndAddContactsByMid(target)
kf.findAndAddContactsByMid(target)
kg.findAndAddContactsByMid(target)
kh.findAndAddContactsByMid(target)
ki.findAndAddContactsByMid(target)
kj.findAndAddContactsByMid(target)
admin.append(target)
ka.sendText(msg.to,"👑Admin Already Added Boss Man👑")
except:
pass
print "[Command]Admin add executed"
else:
ka.sendText(msg.to,"You Are Not My Boss !!!")
ka.sendText(msg.to,"Command Denied")
#==============================================================================#
elif "Owner add @" in msg.text:
if msg.from_ in owner:
print "[Command]Owner add executing"
_name = msg.text.replace("Owner add @","")
_nametarget = _name.rstrip(' ')
gs = ka.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
random.choice(KAC).sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
ka.findAndAddContactsByMid(target)
# kb.findAndAddContactsByMid(target)
# kc.findAndAddContactsByMid(target)
# kd.findAndAddContactsByMid(target)
# ke.findAndAddContactsByMid(target)
# kf.findAndAddContactsByMid(target)
# kg.findAndAddContactsByMid(target)
# kh.findAndAddContactsByMid(target)
# ki.findAndAddContactsByMid(target)
# kj.findAndAddContactsByMid(target)
owner.append(target)
ka.sendText(msg.to,"👑Owner Already Added Boss Man👑")
except:
pass
print "[Command]Owner add executed"
else:
ka.sendText(msg.to,"You Are Not My Boss !!!")
ka.sendText(msg.to,"Command Denied")
#==============================================================================#
elif "Admin remove @" in msg.text:
if msg.from_ in owner:
print "[Command]Staff remove executing"
_name = msg.text.replace("Admin remove @","")
_nametarget = _name.rstrip(' ')
gs = ka.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
random.choice(KAC).sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
admin.remove(target)
ka.sendText(msg.to,"Admin Deleted 👀")
except:
pass
print "[Command]Admin remove executed"
else:
ka.sendText(msg.to,"You Are Not My Boss !!!")
ka.sendText(msg.to,"Command Denied")
#==============================================================================#
elif "Owner remove @" in msg.text:
if msg.from_ in owner:
print "[Command]Owner remove executing"
_name = msg.text.replace("Owner remove @","")
_nametarget = _name.rstrip(' ')
gs = ka.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
random.choice(KAC).sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
owner.remove(target)
ka.sendText(msg.to,"Owner Deleted 👀")
except:
pass
print "[Command]Owner remove executed"
else:
ka.sendText(msg.to,"You Are Not My Boss !!!")
ka.sendText(msg.to,"Command Denied")
#==============================================================================#
elif msg.text in ["Adminlist","Stafflist"]:
if admin == []:
ka.sendText(msg.to,"The stafflist is empty")
else:
ka.sendText(msg.to,"Tunggu...")
mc = "👑 Admin selfbot-man 👑\n𖤓≛≛≛≛≛≛≛≛≛≛≛≛≛≛𖤓\n"
for mi_d in admin:
mc += "[🔘] " + ka.getContact(mi_d).displayName + "🔏\n"
ka.sendText(msg.to,mc)
print "[Command]Stafflist executed"
#==============================================================================#
elif msg.text in ["Ownerlist","ownerlist"]:
if owner == []:
ka.sendText(msg.to,"The Owner is empty")
else:
ka.sendText(msg.to,"Tunggu...")
mc = "👑 Owner selfbot-man 👑\n𖤓≛≛≛≛≛≛≛≛≛≛≛≛≛≛𖤓\n"
for mi_d in owner:
mc += "[🔘] " + ka.getContact(mi_d).displayName + "🔏\n"
ka.sendText(msg.to,mc)
print "[Command]Ownerlist executed"
#==============================================================================#
elif msg.contentType == 16:
if wait["Timeline"] == True:
msg.contentType = 0
msg.text = "🔘POST📬\n💌URL-timeline⤵️\n" + msg.contentMetadata["postEndUrl"]
random.choice(KAC).sendText(msg.to,msg.text)
#==============================================================================#
elif msg.text in ["List group"]:
gid = ka.getGroupIdsJoined()
h = ""
jml = 0
for i in gid:
gn = ka.getGroup(i).name
h += "╠ [ %s ]\n" % (gn)
jml += 1
ka.sendText(msg.to,"╔══[ List Group ]\n"+ h +"╚══[ Total Group ] "+str(jml))
#==============================================================================#
elif "/invitemeto: " in msg.text:
if msg.from_ in owner:
gid = msg.text.replace("/invitemeto: ","")
if gid == "":
ka.sendText(msg.to,"Invalid group id")
else:
try:
ka.findAndAddContactsByMid(msg.from_)
ka.inviteIntoGroup(gid,[msg.from_])
except:
try:
kb.findAndAddContactsByMid(msg.from_)
kb.inviteIntoGroup(gid,[msg.from_])
except:
try:
kc.findAndAddContactsByMid(msg.from_)
kc.inviteIntoGroup(gid,[msg.from_])
except:
try:
kd.findAndAddContactsByMid(msg.from_)
kd.inviteIntoGroup(gid,[msg.from_])
except:
try:
ke.findAndAddContactsByMid(msg.from_)
ke.inviteIntoGroup(gid,[msg.from_])
except:
ka.sendText(msg.to,"Mungkin kami tidak di dalaam grup itu")
#==============================================================================#
elif msg.text in ["Bot out","Leave all group"]:
if msg.from_ in owner:
gid = ka.getGroupIdsJoined()
gid = kb.getGroupIdsJoined()
gid = kc.getGroupIdsJoined()
gid = kd.getGroupIdsJoined()
gid = ke.getGroupIdsJoined()
for i in gid:
ke.leaveGroup(i)
kd.leaveGroup(i)
kc.leaveGroup(i)
kb.leaveGroup(i)
ka.leaveGroup(i)
if wait["lang"] == "JP":
ka.sendText(msg.to,"Sayonara")
else:
ka.sendText(msg.to,"He declined all invitations")
#==============================================================================#
elif msg.text in ["Notifed on","เปิดแจ้งเตือน","M on"]:
if msg.from_ in admin:
if wait["Notifed"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"All Notifed On\n\nเปิดเเจ้งเเตือนของคุณเเล้ว")
else:
ka.sendText(msg.to,"Done\n\nเปิดเเจ้งเเตือนของคุณเเล้ว")
else:
wait["Notifed"] = True
if wait["lang"] == "JP":
ka.sendText(msg.to,"All Notifed On\n\nเปิดเเจ้งเเตือนของคุณเเล้ว")
else:
ka.sendText(msg.to,"Done\n\nเปิดเเจ้งเเตือนของคุณเเล้ว")
elif msg.text in ["Notifed off","ปิดแจ้งเตือน","M off"]:
if msg.from_ in admin:
if wait["Notifed"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"All Notifed Off\n\nปิดเเจ้งเเตือนของคุณเเล้ว")
else:
ka.sendText(msg.to,"Done\n\nปิดเเจ้งเเตือนของคุณเเล้ว")
else:
wait["Notifed"] = False
if wait["lang"] == "JP":
ka.sendText(msg.to,"All Notifed Off\n\nปิดเเจ้งเเตือนของคุณเเล้ว")
else:
ka.sendText(msg.to,"Done\n\nปิดเเจ้งเเตือนของคุณเเล้ว")
elif msg.text in ["Notifedbot on","เปิดเเจ้งเตือนบอท","Mbot on"]:
if msg.from_ in admin:
if wait["Notifedbot"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"All bot Notifed On\n\nเปิดเเจ้งเเตือนบอทเเล้ว")
else:
ka.sendText(msg.to,"Done\n\nเปิดเเจ้งเเตือนบอทเเล้ว")
else:
wait["Notifedbot"] = True
if wait["lang"] == "JP":
ka.sendText(msg.to,"All bot Notifed On\n\nเปิดเเจ้งเเตือนบอทเเล้ว")
else:
ka.sendText(msg.to,"Done\n\nเปิดเเจ้งเเตือนบอทเเล้ว")
elif msg.text in ["Notifedbot off","ปิดแจ้งเตือนบอท","Mbot off"]:
if msg.from_ in admin:
if wait["Notifedbot"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"All bot Notifed Off\n\nปิดเเจ้งเเตือนบอทเเล้ว")
else:
ka.sendText(msg.to,"Done\n\nปิดเเจ้งเเตือนบอทเเล้ว")
else:
wait["Notifedbot"] = False
if wait["lang"] == "JP":
ka.sendText(msg.to,"All bot Notifed Off\n\nปิดเเจ้งเเตือนบอทเเล้ว")
else:
ka.sendText(msg.to,"Done\n\nปิดเเจ้งเเตือนบอทเเล้ว")
elif msg.text in ["Like on","เปิด ไลค์"]:
if wait["likeOn"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"เปิดอยู่แล้ว。")
else:
wait["likeOn"] = True
if wait["lang"] == "JP":
ka.sendText(msg.to,"เปิดระบบออโต้ไลค์.👌")
elif msg.text in ["ปิด ไลค์","Like off"]:
if wait["likeOn"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"ปิดอยู่แล้ว")
else:
wait["likeOn"] = False
if wait["lang"] == "JP":
ka.sendText(msg.to,"ปิดระบบออโต้ไลค์.👌")
#========================================
#==================================================================================#
elif msg.text in ["Clear"]:
if msg.from_ in owner:
if msg.toType == 2:
group = ka.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.invitee]
for _mid in gMembMids:
random.choice(KAC).cancelGroupInvitation(msg.to,[_mid])
ka.sendText(msg.to,"I pretended to cancel and canceled.")
#==============================================================================#
elif msg.text in ["Cl","Cancel"]:
if msg.from_ in owner:
if msg.toType == 2:
group = ka.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.invitee]
for _mid in gMembMids:
random.choice(KAC).cancelGroupInvitation(msg.to,[_mid])
ka.sendText(msg.to,"🌐Cancel All Group Invite🌐")
#==============================================================================#
elif msg.text in ["Ourl","Url on"]:
if msg.from_ in admin:
if msg.toType == 2:
X = ka.getGroup(msg.to)
X.preventJoinByTicket = False
ka.updateGroup(X)
ka.sendText(msg.to,"🔘OPEN link-Url")
else:
ka.sendText(msg.to,"Can not be used outside the group")
#==============================================================================#
elif msg.text in ["Curl","Url off"]:
if msg.from_ in admin:
if msg.toType == 2:
X = ka.getGroup(msg.to)
X.preventJoinByTicket = True
ka.updateGroup(X)
ka.sendText(msg.to,"📴CLOSE link-Url")
else:
ka.sendText(msg.to,"Can not be used outside the group")
#==============================================================================#
elif msg.text in ["Cancelinvite on","cancelinvite on"]:
if msg.from_ in owner:
if wait["Protectcancel"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"🔘OPEN/PROTECT Cancel Invite")
else:
ka.sendText(msg.to,"Berhasil mengaktifkan Cancel Invite")
elif msg.text in ["Cancelinvite off","cancelinvite off"]:
if msg.from_ in owner:
if wait["Protectcancel"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"📴CLOSE/PROTECT Cancel Invite")
else:
ka.sendText(msg.to,"Berhasil menonaktifkan Cancel Invite")
elif "Gcancel:" in msg.text:
try:
strnum = msg.text.replace("Gcancel:","")
if strnum == "off":
wait["autoCancel"]["on"] = False
if wait["lang"] == "JP":
ka.sendText(msg.to,"Invitation refused turned off\nTo turn on please specify the number of people and send")
else:
ka.sendText(msg.to,"关了邀请拒绝。要时开请指定人数发送")
else:
num = int(strnum)
wait["autoCancel"]["on"] = True
if wait["lang"] == "JP":
ka.sendText(msg.to,strnum + " The group of people and below decided to automatically refuse invitation")
else:
ka.sendText(msg.to,strnum + "使人以下的小组用自动邀请拒绝")
except:
if wait["lang"] == "JP":
ka.sendText(msg.to,"Value is wrong")
else:
ka.sendText(msg.to,"Bizarre ratings")
#==============================================================================#
elif msg.text in ["Add:on","เปิด เพิ่มเพื่อน","Auto add:on","Add on"]:
if wait["autoAdd"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"Sudah on Bosqu")
else:
ka.sendText(msg.to,"Ok Bosqu")
else:
wait["autoAdd"] = True
if wait["lang"] == "JP":
ka.sendText(msg.to,"Ok Bosqu")
else:
ka.sendText(msg.to,"Sudah on Bosqu")
elif msg.text in ["Add:off","Auto add off","ปิด เพิ่มเพื่อน","Add off"]:
if wait["autoAdd"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"Sudah off Bosqu")
else:
ka.sendText(msg.to,"Ok Bosqu")
else:
wait["autoAdd"] = False
if wait["lang"] == "JP":
ka.sendText(msg.to,"Ok Bosqu")
else:
ka.sendText(msg.to,"Sudah off Bosqu")
#==============================================================================#
elif "Message set:" in msg.text:
wait["message"] = msg.text.replace("Message set:","")
ka.sendText(msg.to,"message changed\n\n"+ datetime.today().strftime('%H:%M:%S'))
elif "Add message: " in msg.text:
wait["message"] = msg.text.replace("Add message: ","")
if wait["lang"] == "JP":
ka.sendText(msg.to,"message changed\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
ka.sendText(msg.to,"done。\n\n"+ datetime.today().strftime('%H:%M:%S'))
elif msg.text in ["Message","Com"]:
if wait["lang"] == "JP":
ka.sendText(msg.to,"message change to\n\n" + wait["message"])
else:
ka.sendText(msg.to,"The automatic appending information is set as follows。\n\n" + wait["message"])
elif "Coms set:" in msg.text:
c = msg.text.replace("คอมเม้น:","Coms set:","")
if c in [""," ","\n",None]:
ka.sendText(msg.to,"String that can not be changed")
else:
wait["comment"] = c
ka.sendText(msg.to,"changed\n\n" + c)
elif "Add comment: " in msg.text:
c = msg.text.replace("Add comment: ","")
if c in [""," ","\n",None]:
ka.sendText(msg.to,"String that can not be changed")
else:
wait["comment"] = c
ka.sendText(msg.to,"changed\n\n" + c)
elif msg.text in ["เปิด คอมเม้น","Com on","Comment:on"]:
if wait["commentOn"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"Done")
else:
ka.sendText(msg.to,"Already on")
else:
wait["commentOn"] = True
if wait["lang"] == "JP":
ka.sendText(msg.to,"Done")
else:
ka.sendText(msg.to,"Already on")
elif msg.text in ["ปิด คอมเม้น","Com off","Comment:off"]:
if wait["commentOn"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"Done")
else:
ka.sendText(msg.to,"Already off")
else:
wait["commentOn"] = False
if wait["lang"] == "JP":
ka.sendText(msg.to,"Done")
else:
ka.sendText(msg.to,"Already off")
elif msg.text in ["Comment","Coms"]:
ka.sendText(msg.to,"message changed to\n\n" + str(wait["comment"]))
elif msg.text in ["HHX1","Hhx1"]:
ka.sendText(msg.to,"[เช็คข้อความต้อนรับของคุณ]\n\n" + str(wait["acomment"]))
elif msg.text in ["HHX2","Hhx2"]:
ka.sendText(msg.to,"[เช็คข้อความกล่าวถึงคนออกจากกลุ่ม]\n\n" + str(wait["bcomment"]))
elif msg.text in ["HHX3","Hhx3"]:
ka.sendText(msg.to,"[เช็คข้อความกล่าวถึงคนลบสมาชิก]\n\n" + str(wait["ccomment"]))
elif "Hhx1:" in msg.text:
c = msg.text.replace("Hhx1:","")
if c in [""," ","\n",None]:
ka.sendText(msg.to,"เกิดข้อผิดพลาด..!!")
else:
wait["acomment"] = c
ka.sendText(msg.to,"➠ ตั้งค่าข้อความต้อนรับ👌\n\n" + c)
elif "Hhx2:" in msg.text:
c = msg.text.replace("Hhx2:","")
if c in [""," ","\n",None]:
ka.sendText(msg.to,"เกิดข้อผิดพลาด..!!")
else:
wait["bcomment"] = c
ka.sendText(msg.to,"➠ ตั้งค่าข้อความกล่าวถึงคนออกจากกลุ่ม👌\n\n" + c)
elif "Hhx3:" in msg.text:
c = msg.text.replace("Hhx3:","")
if c in [""," ","\n",None]:
ka.sendText(msg.to,"เกิดข้อผิดพลาด..!!")
else:
wait["ccomment"] = c
ka.sendText(msg.to,"➠ ตั้งค่าข้อความกล่าวถึงคนลบสมาชิก👌\n\n" + c)
elif msg.text in ["Hhx1 on"]:
if wait["acommentOn"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ เปิดข้อความต้อนรับเเล้ว👌")
else:
ka.sendText(msg.to,"Already on")
else:
wait["acommentOn"] = True
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ เปิดข้อความต้อนรับเเล้ว👌")
else:
ka.sendText(msg.to,"Already on")
elif msg.text in ["Hhx2 on"]:
if wait["bcommentOn"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ เปิดข้อความกล่าวถึงคนออกจากกลุ่ม👌")
else:
ka.sendText(msg.to,"Already on")
else:
wait["bcommentOn"] = True
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ เปิดข้อความกล่าวถึงคนออกจากกลุ่ม👌")
else:
ka.sendText(msg.to,"Already on")
elif msg.text in ["Hhx3 on"]:
if wait["ccommentOn"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ เปิดข้อความกล่าวถึงคนลบสมาชิก👌")
else:
ka.sendText(msg.to,"Already on")
else:
wait["ccommentOn"] = True
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ เปิดข้อความกล่าวถึงคนลบสมาชิก👌")
else:
ka.sendText(msg.to,"Already on")
elif msg.text in ["Hhx1 off"]:
if wait["acommentOn"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ ปิดข้อความต้อนรับเเล้ว👌")
else:
ka.sendText(msg.to,"Already off")
else:
wait["acommentOn"] = False
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ ปิดข้อความต้อนรับเเล้ว👌")
else:
ka.sendText(msg.to,"Already off")
elif msg.text in ["Hhx2 off"]:
if wait["bcommentOn"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ ปิดข้อความกล่าวถึงคนออกจากกลุ่ม👌")
else:
ka.sendText(msg.to,"Already off")
else:
wait["bcommentOn"] = False
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ ปิดข้อความกล่าวถึงคนออกจากกลุ่ม👌")
else:
ka.sendText(msg.to,"Already off")
elif msg.text in ["Hhx3 off"]:
if wait["ccommentOn"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ ปิดข้อความกล่าวถึงคนลบสมาชิก👌")
else:
ka.sendText(msg.to,"Already off")
else:
wait["ccommentOn"] = False
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ ปิดข้อความกล่าวถึงคนลบสมาชิก👌")
else:
ka.sendText(msg.to,"Already off")
#==================================================================================#
elif msg.text in ["Purge on","purge on","Purge: on","purge: on"]:
if msg.from_ in admin:
if wait["Protectjoin"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"Berhasil mengaktifkan High Protect")
else:
ka.sendText(msg.to,"Berhasil mengaktifkan High Protect")
elif msg.text in ["Purge off","purge off","Purge: off","purge: off"]:
if msg.from_ in admin:
if wait["Protectjoin"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"Berhasil menonaktifkan High Protect")
else:
ka.sendText(msg.to,"Berhasil menonaktifkan High Protect")
#==============================================================================#
elif msg.text in ["Cancel on","cancel on","ปิดเชิญ"]:
if msg.from_ in owner:
if wait["Protectcancl"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"🔘OPEN/PROTECT ระบบป้องกันเชิญถูกเปิดใช้งาน")
else:
ka.sendText(msg.to,"Berhasil mengaktifkan Cancel")
elif msg.text in ["Cancel off","cancel off","เปิดเชิญ"]:
if msg.from_ in owner:
if wait["Protectcancl"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"📴CLOSE/PROTECT ระบบป้องกันเชิญถูกปิดใช้งาน")
else:
ka.sendText(msg.to,"Berhasil menonaktifkan Cancel")
#==============================================================================#
elif msg.text in ["Qr on","qr on","เปิดป้องกันลิงก์","ป้องกันลิ้ง"]:
if msg.from_ in owner:
if wait["Protectgr"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"🔘OPEN/PROTECT URL:QR เปิดระบบป้องกันลิงก์กลุ่ม")
else:
ka.sendText(msg.to,"Berhasil mengaktifkan Protect QR")
elif msg.text in ["Qr off","qr off","ปิดป้องกันลิงก์"]:
if msg.from_ in owner:
if wait["Protectgr"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"📴CLOSE/PROTECT URL:QR ปิดระบบป้องกันลิงก์กลุ่ม")
else:
ka.sendText(msg.to,"Berhasil menonaktifkan Protect QR")
#==============================================================================#
elif msg.text in ["Contact On","Contact on","contact on"]:
if msg.from_ in owner:
if wait["contact"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"🔘OPEN / Info Contact")
else:
ka.sendText(msg.to,"Berhasil mengaktifkan Info Contact")
elif msg.text in ["Contact Off","Contact off","contact off"]:
if msg.from_ in owner:
if wait["contact"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"📴CLOSE / Info Contact")
else:
ka.sendText(msg.to,"Berhasil menonaktifkan Info Contact")
#==============================================================================#
elif msg.text in ["Join on","Autojoin on","เปิดเข้ากลุ่ม"]:
if msg.from_ in owner:
if wait["autoJoin"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"🔘OPEN Auto Join เข้าร่วมกลุ่มเชิญออโต้")
else:
ka.sendText(msg.to,"Berhasil mengaktifkan Auto Join")
elif msg.text in ["Join off","Autojoin off","ปิดเข้ากลุ่ม"]:
if msg.from_ in owner:
if wait["autoJoin"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"📴CLOSE Auto Join ปิดเข้าร่วมกลุ่มเชิญ")
else:
ka.sendText(msg.to,"Berhasil menonaktifkan Auto Join")
#==============================================================================#
elif msg.text in ["Leave on","Autoleave on"]:
if msg.from_ in owner:
if wait["leaveRoom"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"🔘OPEN Auto Leave เปิดป้องกันการดึงแชทรวม")
else:
ka.sendText(msg.to,"Berhasil mengaktifkan Auto Leave")
elif msg.text in ["Leave off","Autoleave off"]:
if msg.from_ in owner:
if wait["leaveRoom"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"📴CLOSE Auto Leave ปิดป้องกันการดึงแชทรวม")
else:
ka.sendText(msg.to,"Berhasil menonaktifkan Auto Leave")
#==============================================================================#
elif msg.text in ["Share on","Share:on"]:
if msg.from_ in owner:
if wait["timeline"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"🔘OPEN Mode Share")
else:
ka.sendText(msg.to,"Berhasil mengaktifkan Mode Share")
elif msg.text in ["Share off","Share:off"]:
if msg.from_ in owner:
if wait["timeline"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"📴CLOSE Mode Share")
else:
ka.sendText(msg.to,"Berhasil menonaktifkan Mode Share")
#==============================================================================#
elif msg.text in ["Sambutan on","Sam:on","เปิดต้อนรับ"]:
if msg.from_ in owner:
if wait["Sambutan"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"🔘OPEN เปิดใช้งานต้อนรับ,บอทตอบโต้")
elif msg.text in ["Sambutan off","Sam:off","ปิดต้อนรับ"]:
if msg.from_ in owner:
if wait["Sambutan"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"📴CLOSE ปิดใช้งานต้อนรับ,บอทตอบโต้")
#==============================================================================#
elif msg.text in ["Simisimi on","Simisimi:on","Chatbot:on"]:
settings["simiSimi"][msg.to] = True
wait["Simi"] = True
ka.sendText(msg.to,"🔘OPEN เปิดการสนทนาบอท")
elif msg.text in ["Simisimi off","Simisimi:off","Chatbot:off"]:
settings["simiSimi"][msg.to] = False
wait["Simi"] = False
ka.sendText(msg.to,"📴CLOSE ปิดการสนทนาบอท")
#==============================================================================#
elif msg.text in ["เปิด อ่าน","Read on","Read:on"]:
wait['alwayRead'] = True
ka.sendText(msg.to,"เปิดอ่านข้อความอัตโนมัติ.👌")
elif msg.text in ["ปิด อ่าน","Read off","Read:off"]:
wait['alwayRead'] = False
ka.sendText(msg.to,"ปิดอ่านข้อความอัตโนมัติ.👌")
elif msg.text in ["Tag on","Autorespon:on","Respon on","Respon:on"]:
wait["detectMention"] = True
ka.sendText(msg.to,"Auto Respon ON")
elif msg.text in ["Tag off","Autorespon:off","Respon off","Respon:off"]:
wait["detectMention"] = False
ka.sendText(msg.to,"Auto Respon OFF")
elif msg.text in ["Tag1","Tag1"]:
ka.sendText(msg.to,"ข้อความแทคล่าสุดคือ\n\n" + str(wait["tag1"]))
elif msg.text in ["Tag2","Tag2"]:
ka.sendText(msg.to,"ข้อความแทคล่าสุดคือ\n\n" + str(wait["tag2"]))
elif msg.text in ["Tag1:"]:
wait["tag1"] = msg.text.replace("Tag1: ","")
ka.sendText(msg.to,"ข้อความแทคล่าสุดคือ")
elif msg.text in ["Tag2:"]:
wait["tag2"] = msg.text.replace("Tag2: ","")
ka.sendText(msg.to,"ข้อความแทคล่าสุดคือ")
elif msg.text in ["Kicktag on","Autokick:on","Responkick on","Responkick:on"]:
wait["kickMention"] = True
ka.sendText(msg.to,"Auto Kick ON")
elif msg.text in ["Kicktag off","Autokick:off","Responkick off","Responkick:off"]:
wait["kickMention"] = False
ka.sendText(msg.to,"Auto Kick OFF")
#============================================================================#
elif "Spam " in msg.text:
if msg.from_ in admin:
txt = msg.text.split(" ")
jmlh = int(txt[2])
teks = msg.text.replace("Spam "+str(txt[1])+" "+str(jmlh)+ " ","")
tulisan = jmlh * (teks+"\n")
#Keke cantik <3
if txt[1] == "on":
if jmlh <= 10000:
for x in range(jmlh):
ka.sendText(msg.to, teks)
else:
ka.sendText(msg.to, "Out of range! ")
elif txt[1] == "off":
if jmlh <= 10000:
ka.sendText(msg.to, tulisan)
else:
ka.sendText(msg.to, "Out of range! ")
#====================================================================#
elif "Mid @" in msg.text:
_name = msg.text.replace("Mid @","")
_nametarget = _name.rstrip(' ')
gs = ka.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
ka.sendText(msg.to, g.mid)
else:
pass
#====================================================================#
elif "Sider on" in msg.text:
try:
del cctv['point'][msg.to]
del cctv['sidermem'][msg.to]
del cctv['cyduk'][msg.to]
except:
pass
cctv['point'][msg.to] = msg.id
cctv['sidermem'][msg.to] = ""
cctv['cyduk'][msg.to]=True
wait["Sider"] = True
ka.sendText(msg.to,"Berhasil mengaktifkan Sider point")
elif "Sider off" in msg.text:
if msg.to in cctv['point']:
cctv['cyduk'][msg.to]=False
wait["Sider"] = False
ka.sendText(msg.to, "Berhasil menonaktifkan Sider point")
else:
ka.sendText(msg.to, "Setting Masih Mode Off\nMohon Maaf")
#--------------------------------
elif msg.text in ["Allprotect on","เปิดชุดป้องกัน"]:
if msg.from_ in admin:
wait["Protectcancel"] = True
wait["Protectcancl"] = True
wait["Protectjoin"] = True
wait["Protectgr"] = True
wait["Protection"] = True
ka.sendText(msg.to,"🔘OPEN/PROTECT ระบบป้องกันถูกเปิดใช้งาน")
else:
ka.sendText(msg.to,"TEAM STAFF.BOT MAN ON")
if msg.from_ in admin:
wait["Protectcancel"] = False
wait["Protectcancl"] = False
wait["Protectjoin"] = False
wait["Protectgr"] = False
wait["Protection"] = False
ka.sendText(msg.to,"📴CLOSE/PROTECT ระบบป้องกันถูกเปิดใช้งาน")
else:
ka.sendText(msg.to,"TEAM STAFFBOT MAN OFF PROTECTION")
#========================[ P R O T E C T I O N : A L L ]========================#
elif msg.text in ["ProtectALL on","เปิดระบบป้องกัน"]:
if msg.from_ in admin:
wait["Protectcancel"] = True
wait["Protectcancl"] = True
wait["Protectjoin"] = True
wait["Protectgr"] = True
wait["Protection"] = True
ka.sendText(msg.to,"🔘OPEN/PROTECT ระบบป้องกันถูกเปิดใช้งาน")
else:
ka.sendText(msg.to,"TEAM STAFF.BOT MAN ON")
elif msg.text in ["ProtectALL off","ปิดระบบป้องกัน"]:
if msg.from_ in admin:
wait["Protectcancel"] = False
wait["Protectcancl"] = False
wait["Protectjoin"] = False
wait["Protectgr"] = False
wait["Protection"] = False
ka.sendText(msg.to,"📴CLOSE/PROTECT ระบบป้องกันถูกเปิดใช้งาน")
else:
ka.sendText(msg.to,"TEAM STAFFBOT MAN OFF PROTECTION")
#==============================[ S E T : T I N G ]==============================#
elif msg.text in ["Allprotect on","เปิดระบบป้องกัน"]:
if msg.from_ in admin:
wait["contact"] = True
wait["Auvv "] = True
wait["Protectjoin"] = True
wait["Protectgr"] = True
wait["Protection"] = True
ka.sendText(msg.to,"🔘OPEN/PROTECT ระบบป้องกันถูกเปิดใช้งาน")
else:
ka.sendText(msg.to,"TEAM STAFF.BOT MAN ON")
elif msg.text in ["Allprotect oft","ปิดระบบป้องกัน"]:
if msg.from_ in admin:
wait["Protectcancel"] = False
wait["Protectcancl"] = False
wait["Protectjoin"] = False
wait["Protectgr"] = False
wait["Protection"] = False
ka.sendText(msg.to,"📴CLOSE/PROTECT ระบบป้องกันถูกเปิดใช้งาน")
else:
ka.sendText(msg.to,"TEAM STAFFBOT MAN OFF PROTECTION")
#==============================================================================#
elif msg.text in ["เชคค่า","เช็คค่า","Set"]:
if msg.from_ in admin:
print "Setting pick up..."
md = "╭══════════════════╮\n║─┅═✥ᴛᴇᴀᴍᵀᴴᴬᴵᴸᴬᴺᴰʙᴏᴛLɪɴᴇ✥═┅─\n║ •─✯͜͡✯TOME★BOTLINE✯͜͡✯─• \n╰══════════════════╯\n╭═════════════════╮\n"
if wait["likeOn"] == True: md+="╠❂➣ ออโต้ไลค์ : ✔ เปิดอยู่\n"
else:md+="╠❂➣ ออโต้ไลค์ : ❌ ปิดแล้ว\n"
if wait["detectMention"] == True: md+="╠❂➣ ตอบแทค : ✔ เปิดแล้ว\n"
else:md+="╠❂➣ ตอบแทค : ❌ ปิดแล้ว\n"
if wait["kickMention"] == True: md+="╠❂➣ ออโต้เตะ: ✔ เปิดอยู่\n"
else:md+="╠❂➣ ออโต้เตะ : ❌ ปิดอยู่\n"
if wait["Notifed"] == True: md+="╠❂➣ Notifed : ✔ เปิดอยู่\n"
else:md+="╠❂➣ Notifed : ❌ ปิดอยู่\n"
if wait["Notifedbot"] == True: md+="╠❂➣ Notifedbot : ✔ เปิดอยู่\n"
else:md+="╠❂➣ Notifedbot : ❌ ปิดอยู่\n"
if wait["acommentOn"] == True: md+="╠❂➣ Hhx1 : ✔ เปิดอยู่\n"
else:md+="╠❂➣ Hhx1 : ❌ ปิดอยู่\n"
if wait["bcommentOn"] == True: md+="╠❂➣ Hhx2 : ✔ เปิดอยู่\n"
else:md+="╠❂➣ Hhx2 : ❌ ปิดอยู่\n"
if wait["ccommentOn"] == True: md+="╠❂➣ Hhx3 : ✔ เปิดอยู่\n"
else:md+="╠❂➣ Hhx3 : ❌ ปิดอยู่\n"
if wait["autoCancel"]["on"] == True:md+="╠❂➣ Group cancel :" + str(wait["autoCancel"]["members"]) + " ห้องที่เปิดใช้งาน\n"
else: md+="╠❂➣ Group cancel : ❌ ปิดอยู่\n"
if wait["autoAdd"] == True: md+="╠❂➣ ออโต้ เพิ่มเพื่อน : ✔ เปิดอยู่\n"
else:md+="╠❂➣ ออโต้ เพิ่มเพื่อน : ❌ ปิดอยู่\n"
if wait["Protectgr"] == True: md+="╠❂➣🔒Protect QR Enable\n"
else: md+="╠❂➣🔓Protect QR Disable\n"
if wait["Protectcancl"] == True: md+="╠❂➣🔒Protect Invite Enable\n"
else: md+="╠❂➣🔓Protect Invite Disable\n"
if wait["Protectcancel"] == True: md+="╠❂➣🔒Protect Cancel Enable\n"
else: md+="╠❂➣🔓Protect Cancel Disable\n"
if wait["Protectjoin"] == True: md+="╠❂➣🔒High protect Enable\n"
else: md+="╠❂➣🔓High protect Disable\n"
if wait["contact"] == True: md+="╠❂➣🔘Contact ✔\n"
else: md+="╠❂➣🔘Contact ✖\n"
if wait["autoJoin"] == True: md+="╠❂➣🔘Auto Join ✔\n"
else: md+="╠❂���🔘Auto Join ✖\n"
if wait["leaveRoom"] == True: md+="╠❂➣🔘Auto Leave ✔\n"
else: md+="╠❂➣🔘Auto Leave ✖\n"
if wait["timeline"] == True: md+="╠❂➣🔘Share ✔\n"
else: md+="╠❂➣🔘Share ✖\n"
if wait["Sambutan"] == True: md+="╠❂➣🔘Sambutan ✔\n"
else: md+="╠❂➣🔘Sambutan ✖\n"
ka.sendText(msg.to,md + "╰══════════════════╯")
msg.contentType = 13
msg.contentMetadata = {'mid': admsa}
ka.sendMessage(msg)
# else:
# ka.sendText(msg.to,"This Command Only For Admin & Owner")
#==============================================================================#
elif msg.text in ["Tagall","Tag all","Mention all"]:
if msg.from_ in owner:
group = ka.getGroup(msg.to)
nama = [contact.mid for contact in group.members]
cb = ""
cb2 = ""
strt = int(0)
akh = int(0)
for md in nama:
akh = akh + int(6)
cb += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M":"""+json.dumps(md)+"},"""
strt = strt + int(7)
akh = akh + 1
cb2 += "@nrik \n"
cb = (cb[:int(len(cb)-1)])
msg.contentType = 0
msg.text = cb2
msg.contentMetadata ={'MENTION':'{"MENTIONEES":['+cb+']}','EMTVER':'4'}
try:
ka.sendMessage(msg)
except Exception as error:
print error
#==============================================================================#
elif "แทค" == msg.text.lower():
group = ka.getGroup(msg.to)
nama = [contact.mid for contact in group.members]
nm1, nm2, nm3, nm4, nm5, jml = [], [], [], [], [], len(nama)
if jml <= 100:
summon(msg.to, nama)
if jml > 100 and jml < 200:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, len(nama)-1):
nm2 += [nama[j]]
summon(msg.to, nm2)
if jml > 200 and jml < 500:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, 199):
nm2 += [nama[j]]
summon(msg.to, nm2)
for k in range(200, 299):
nm3 += [nama[k]]
summon(msg.to, nm3)
for l in range(300, 399):
nm4 += [nama[l]]
summon(msg.to, nm4)
for m in range(400, len(nama)-1):
nm5 += [nama[m]]
summon(msg.to, nm5)
if jml > 500:
print "Terlalu Banyak Men 500+"
cnt = Message()
cnt.text = "[SELF BOT\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]:\n" + str(jml) + " Members"
cnt.to = msg.to
ka.sendMessage(cnt)
#==================================================================================#
elif msg.text == "Lurking on":
if msg.from_ in owner:
tz = pytz.timezone("Asia/Jakarta")
timeNow = datetime.now(tz=tz)
day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]
hr = timeNow.strftime("%A")
bln = timeNow.strftime("%m")
for i in range(len(day)):
if hr == day[i]: hasil = hari[i]
for k in range(0, len(bulan)):
if bln == str(k): bln = bulan[k-1]
readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]"
if msg.to in read['readPoint']:
try:
del read['readPoint'][msg.to]
del read['readMember'][msg.to]
del read['readTime'][msg.to]
except:
pass
read['readPoint'][msg.to] = msg.id
read['readMember'][msg.to] = ""
read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S')
read['ROM'][msg.to] = {}
with open('sider.json', 'w') as fp:
json.dump(read, fp, sort_keys=True, indent=4)
ka.sendText(msg.to,"Lurking already on")
else:
try:
del read['readPoint'][msg.to]
del read['readMember'][msg.to]
del read['readTime'][msg.to]
except:
pass
read['readPoint'][msg.to] = msg.id
read['readMember'][msg.to] = ""
read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S')
read['ROM'][msg.to] = {}
with open('sider.json', 'w') as fp:
json.dump(read, fp, sort_keys=True, indent=4)
ka.sendText(msg.to, "Set reading point:\n" + readTime)
elif msg.text == "Lurking off":
if msg.from_ in owner:
tz = pytz.timezone("Asia/Jakarta")
timeNow = datetime.now(tz=tz)
day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]
hr = timeNow.strftime("%A")
bln = timeNow.strftime("%m")
for i in range(len(day)):
if hr == day[i]: hasil = hari[i]
for k in range(0, len(bulan)):
if bln == str(k): bln = bulan[k-1]
readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]"
if msg.to not in read['readPoint']:
ka.sendText(msg.to,"Lurking already off")
else:
try:
del read['readPoint'][msg.to]
del read['readMember'][msg.to]
del read['readTime'][msg.to]
except:
pass
ka.sendText(msg.to, "Delete reading point:\n" + readTime)
elif msg.text == "Lurking reset":
if msg.from_ in owner:
tz = pytz.timezone("Asia/Jakarta")
timeNow = datetime.now(tz=tz)
day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]
hr = timeNow.strftime("%A")
bln = timeNow.strftime("%m")
for i in range(len(day)):
if hr == day[i]: hasil = hari[i]
for k in range(0, len(bulan)):
if bln == str(k): bln = bulan[k-1]
readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]"
if msg.to in read["readPoint"]:
try:
read["readPoint"][msg.to] = True
read["readMember"][msg.to] = {}
read["readTime"][msg.to] = readTime
read["ROM"][msg.to] = {}
except:
pass
ka.sendText(msg.to, "Reset reading point:\n" + readTime)
else:
ka.sendText(msg.to, "Lurking belum diaktifkan ngapain di reset?")
elif msg.text == "Lurking":
if msg.from_ in owner:
tz = pytz.timezone("Asia/Jakarta")
timeNow = datetime.now(tz=tz)
day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]
hr = timeNow.strftime("%A")
bln = timeNow.strftime("%m")
for i in range(len(day)):
if hr == day[i]: hasil = hari[i]
for k in range(0, len(bulan)):
if bln == str(k): bln = bulan[k-1]
readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]"
if msg.to in read['readPoint']:
if read["ROM"][msg.to].items() == []:
ka.sendText(msg.to, "Lurkers:\nNone")
else:
chiya = []
for rom in read["ROM"][msg.to].items():
chiya.append(rom[1])
cmem = ka.getContacts(chiya)
zx = ""
zxc = ""
zx2 = []
xpesan = '[ Reader ]\n'
for x in range(len(cmem)):
xname = str(cmem[x].displayName)
pesan = ''
pesan2 = pesan+"@a\n"
xlen = str(len(zxc)+len(xpesan))
xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1)
zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid}
zx2.append(zx)
zxc += pesan2
msg.contentType = 0
msg.text = xpesan+ zxc + "\nLurking time: \n" + readTime
lol ={'MENTION':str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}
msg.contentMetadata = lol
try:
ka.sendMessage(msg)
except Exception as error:
print error
pass
else:
ka.sendText(msg.to, "Lurking has not been set.")
#==============================================================================#
elif msg.text in ["Gurl","Url","ลิงก์กลุ่ม"]:
if msg.from_ in admin:
if msg.toType == 2:
x = ka.getGroup(msg.to)
if x.preventJoinByTicket == True:
x.preventJoinByTicket = False
ka.updateGroup(x)
gurl = ka.reissueGroupTicket(msg.to)
ka.sendText(msg.to,"line://ti/g/" + gurl)
else:
if wait["lang"] == "JP":
ka.sendText(msg.to,"Can't be used outside the group")
else:
ka.sendText(msg.to,"Not for use less than group")
else:
ka.sendText(msg.to,"This Command Only For Admin & Owner")
#==============================================================================#
elif msg.text in ["Masuk","Bot in","Staff in"]:
if msg.from_ in owner:
G = ka.getGroup(msg.to)
ginfo = ka.getGroup(msg.to)
G.preventJoinByTicket = False
ka.updateGroup(G)
invsend = 0
Ticket = ka.reissueGroupTicket(msg.to)
kb.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.00001)
G = ka.getGroup(msg.to)
G.preventJoinByTicket = True
ka.updateGroup(G)
print "Semua Sudah Lengkap"
#==============================================================================#
elif msg.text in ["timeline"]:
try:
url = ka.activity(limit=10)
ka.sendText(msg.to,url['result']['posts'][0]['postInfo']['postId'])
except Exception as E:
print E
#==============================================================================#
elif msg.text in ["Keluar","Staff out","Out","Staff bye"]:
if msg.from_ in owner:
if msg.toType == 2:
ginfo = ka.getGroup(msg.to)
try:
kb.leaveGroup(msg.to)
kc.leaveGroup(msg.to)
kd.leaveGroup(msg.to)
ke.leaveGroup(msg.to)
kf.leaveGroup(msg.to)
kg.leaveGroup(msg.to)
kh.leaveGroup(msg.to)
ki.leaveGroup(msg.to)
kj.leaveGroup(msg.to)
#ka.leaveGroup(msg.to)
except:
pass
#===============================================================================#
elif msg.text in ["@bye"]:
if msg.from_ in owner:
if msg.toType == 2:
ginfo = ka.getGroup(msg.to)
try:
ka.leaveGroup(msg.to)
except:
pass
#==============================================================================#
elif msg.text in ["Absen"]:
if msg.from_ in admin:
ka.sendText(msg.to,"ルフィ😭")
kb.sendText(msg.to,"ゾーラー😭")
kc.sendText(msg.to,"サンジ😭")
kd.sendText(msg.to,"ウソップ😭")
ke.sendText(msg.to,"チョッパー😭")
#==============================================================================#
elif msg.text.lower() in ["respon"]:
ka.sendText(msg.to,responsename)
kb.sendText(msg.to,responsename2)
kc.sendText(msg.to,responsename3)
kd.sendText(msg.to,responsename4)
ke.sendText(msg.to,responsename5)
kf.sendText(msg.to,responsename6)
kg.sendText(msg.to,responsename7)
kh.sendText(msg.to,responsename8)
ki.sendText(msg.to,responsename9)
kj.sendText(msg.to,responsename10)
#==============================================================================#
elif msg.text.lower() in ["Sp","Speed"]:
fake=["0.002253985673451seconds"]
fspeed=random.choice(fake)
ka.sendText(msg.to," Progress.....")
ka.sendText(msg.to,(fspeed))
#==============================================================================#
elif msg.text in ["Sp","Speed","speed"]:
start = time.time()
ka.sendText(msg.to, "Bot 1 Processing Request")
elapsed_time = time.time() - start
ka.sendText(msg.to, "%sseconds" % (elapsed_time))
# ki.sendText(msg.to, "%sseconds" % (elapsed_time))
# ki2.sendText(msg.to, "%sseconds" % (elapsed_time))
# ki3.sendText(msg.to, "%sseconds" % (elapsed_time))
# ki4.sendText(msg.to, "%sseconds" % (elapsed_time))
# ki5.sendText(msg.to, "%sseconds" % (elapsed_time))
# ki6.sendText(msg.to, "%sseconds" % (elapsed_time))
#==============================================================================#
elif msg.text in ["Banlist","บัญชีดำ"]:
if msg.from_ in admin:
if wait["blacklist"] == {}:
ka.sendText(msg.to,"Nothing Banned User")
else:
ka.sendText(msg.to,"💂ศาล💹เบิกตัว📚\n🔘จำเลย ผู้กระทำความผิด ขึ้นบัญชีดำ⤵️")
mc = ""
for mi_d in wait["blacklist"]:
mc += "👤" +ka.getContact(mi_d).displayName + " 👀รอลงอาญา\n"
ka.sendText(msg.to,mc)
#==============================================================================#
elif msg.text in ["Clear ban","Cb","ล้างดำ"]:
if msg.from_ in owner:
wait["blacklist"] = {}
ka.sendText(msg.to,"💀Clear Blacklist Boss Man💀")
#==============================================================================#
elif "Error!" in msg.text:
if msg.from_ in owner:
if msg.toType == 2:
print "ok"
_name = msg.text.replace("Error!","")
gs = ka.getGroup(msg.to)
gs = kb.getGroup(msg.to)
gs = kc.getGroup(msg.to)
gs = kd.getGroup(msg.to)
gs = ke.getGroup(msg.to)
gs = kf.getGroup(msg.to)
gs = kg.getGroup(msg.to)
gs = kh.getGroup(msg.to)
gs = ki.getGroup(msg.to)
gs = kj.getGroup(msg.to)
ka.sendText(msg.to,"This My Team WAR")
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
ka.sendText(msg.to,"Not found")
else:
for target in targets:
if target not in Bots or owner:
if target in owner:
pass
elif target in admin:
pass
elif target in Bots:
pass
else:
try:
klist=[ka,kb,kc,kd,ke,kf,kg,kh,ki,kj]
kicker=random.choice(klist)
kicker.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except:
random.choice(KAC).kickoutFromGroup(msg.to,[target])
#==============================================================================#
elif msg.text in ["Bot restart"]:
if msg.from_ in owner:
ka.sendText(msg.to, "Kami Siap Restart\nWaktu Restart Sekitar 10 Detik ")
restart_program()
else:
ka.sendText(msg.to,"This Command Only For Owner")
#==============================================================================#
elif "/music " in msg.text:
songname = msg.text.replace("/music ","")
params = {"songname": songname}
r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
abc = song[3].replace('https://','http://')
ka.sendText(msg.to, "🔘Title : " + song[0] + "\n🔘Length : " + song[1] + "\n🔘Link download : " + song[4])
ka.sendText(msg.to, "Lagu " + song[0] + "\nSedang Di Prosses... Tunggu Sebentar ^_^ ")
ka.sendAudioWithURL(msg.to,abc)
ka.sendText(msg.to, "Selamat Mendengarkan Lagu " + song[0])
#==============================================================================#
elif '/lirik ' in msg.text.lower():
try:
songname = msg.text.lower().replace('/lirik ','')
params = {'songname': songname}
r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
hasil = 'Lyric Lagu ('
hasil += song[0]
hasil += ')\n\n'
hasil += song[5]
ka.sendText(msg.to, hasil)
except Exception as wak:
ka.sendText(msg.to, str(wak))
#==============================================================================#
elif '/ig ' in msg.text.lower():
try:
instagram = msg.text.lower().replace("/ig ","")
html = requests.get('https://www.instagram.com/' + instagram + '/?')
soup = BeautifulSoup(html.text, 'html.parser')
data = soup.find_all('meta', attrs={'property':'og:description'})
text = data[0].get('content').split()
data1 = soup.find_all('meta', attrs={'property':'og:image'})
text1 = data1[0].get('content').split()
tj = text1[0].replace("s150x150/","")
user = "🔘Name: " + text[-2] + "\n"
user1 = "🔘Username: " + text[-1] + "\n"
followers = "🔘Followers: " + text[0] + "\n"
following = "🔘Following: " + text[2] + "\n"
post = "🔘Post: " + text[4] + "\n"
link = "🔘Link: " + "https://www.instagram.com/" + instagram
detail = "========INSTAGRAM INFO ========\n"
details = "\n========INSTAGRAM INFO ========"
ka.sendText(msg.to, detail + user + user1 + followers + following + post + link + details)
ka.sendImageWithURL(msg.to, tj)
except Exception as njer:
ka.sendText(msg.to, str(njer))
#==============================================================================#
elif 'Youtubelink: ' in msg.text:
try:
textToSearch = (msg.text).replace('Youtube ', "").strip()
query = urllib.quote(textToSearch)
url = "https://www.youtube.com/results?search_query=" + query
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html, "html.parser")
results = soup.find(attrs={'class':'yt-uix-tile-link'})
ka.sendText(msg.to,'https://www.youtube.com' + results['href'])
except:
ka.sendText(msg.to,"🔘กรุณาใช้คำศัพท์ที่ถูกต้องและทำการค้นหาอีกครั้ง")
#==============================================================================#
elif '/yt: ' in msg.text:
try:
textToSearch = (msg.text).replace('Youtube ', "").strip()
query = urllib.quote(textToSearch)
url = "https://www.youtube.com/results?search_query=" + query
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html, "html.parser")
results = soup.find(attrs={'class':'yt-uix-tile-link'})
ka.sendText(msg.to,'https://www.youtube.com' + results['href'])
except:
ka.sendText(msg.to,"🔘กรุณาใช้คำศัพท์ที่ถูกต้องและทำการค้นหาอีกครั้ง")
#==============================================================================#
elif "Say-id " in msg.text:
say = msg.text.replace("Say-id ","")
lang = 'id'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
ka.sendAudio(msg.to,"hasil.mp3")
elif "Say-en " in msg.text:
say = msg.text.replace("Say-en ","")
lang = 'en'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
ka.sendAudio(msg.to,"hasil.mp3")
elif "Say-jp " in msg.text:
say = msg.text.replace("Say-jp ","")
lang = 'ja'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
ka.sendAudio(msg.to,"hasil.mp3")
elif "Say welcome" in msg.text:
gs = ka.getGroup(msg.to)
say = msg.text.replace("Say welcome","Selamat Datang Di "+ gs.name)
lang = 'id'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
ka.sendAudio(msg.to,"hasil.mp3")
#==============================================================================#
elif "playstore " in msg.text.lower():
tob = msg.text.lower().replace("playstore ","")
ka.sendText(msg.to,"Sedang Mencari...")
ka.sendText(msg.to,"🔘Title : "+tob+"\n🔘Source : Google Play\n🔘Link download : https://play.google.com/store/search?q=" + tob)
ka.sendText(msg.to,"🔘by : SELFBOT MAN MEDIA @2018")
#==============================================================================#
elif "/เพลสโตร์:" in msg.text.lower():
tob = msg.text.lower().replace("/เพลสโตร์:","")
ka.sendText(msg.to,"Playstore...")
ka.sendText(msg.to,"🔘Title : "+tob+"\n🔘Source : Google Play\n🔘Link download : https://play.google.com/store/search?q=" + tob)
ka.sendText(msg.to,"🔘by : SELFBOT MAN MEDIA @2018")
#==============================================================================#
elif msg.text.lower() in ["me"]:
msg.contentType = 13
msg.contentMetadata = {'mid': msg.from_}
ka.sendMessage(msg)
#==============================================================================#
elif "/apakah " in msg.text:
apk = msg.text.replace("/apakah ","")
rnd = ["Ya","Tidak","Bisa Jadi","Mungkin"]
p = random.choice(rnd)
lang = 'id'
tts = gTTS(text=p, lang=lang)
tts.save("hasil.mp3")
ka.sendAudio(msg.to,"hasil.mp3")
elif "/hari " in msg.text:
apk = msg.text.replace("/hari ","")
rnd = ["Senin","Selasa","Rabu","Kamis","Jumat","Sabtu","Minggu"]
p = random.choice(rnd)
lang = 'id'
tts = gTTS(text=p, lang=lang)
tts.save("hasil.mp3")
ka.sendAudio(msg.to,"hasil.mp3")
elif "/berapa " in msg.text:
apk = msg.text.replace("/berapa ","")
rnd = ['10%','20%','30%','40%','50%','60%','70%','80%','90%','100%','0%']
p = random.choice(rnd)
lang = 'id'
tts = gTTS(text=p, lang=lang)
tts.save("hasil.mp3")
ka.sendAudio(msg.to,"hasil.mp3")
elif "/berapakah " in msg.text:
apk = msg.text.replace("/berapakah ","")
rnd = ['1','2','3','4','5','6','7','8','9','10','Tidak Ada']
p = random.choice(rnd)
lang = 'id'
tts = gTTS(text=p, lang=lang)
tts.save("hasil.mp3")
ka.sendAudio(msg.to,"hasil.mp3")
elif "/kapan " in msg.text:
apk = msg.text.replace("/kapan ","")
rnd = ["kapan kapan","besok","satu abad lagi","Hari ini","Tahun depan","Minggu depan","Bulan depan","Sebentar lagi","Tidak Akan Pernah"]
p = random.choice(rnd)
lang = 'id'
tts = gTTS(text=p, lang=lang)
tts.save("hasil.mp3")
ka.sendAudio(msg.to,"hasil.mp3")
#==============================================================================#
elif "Image " in msg.text:
search = msg.text.replace("Image ","")
url = 'https://www.google.com/search?espv=2&biw=1366&bih=667&tbm=isch&oq=kuc&aqs=mobile-gws-lite.0.0l5&q=' + search
raw_html = (download_page(url))
items = []
items = items + (_images_get_all_items(raw_html))
path = random.choice(items)
print path
try:
ka.sendImageWithURL(msg.to,path)
except:
pass
#==============================================================================#
elif "/รูปภาพ:" in msg.text:
search = msg.text.replace("/รูปภาพ:","")
url = 'https://www.google.com/search?espv=2&biw=1366&bih=667&tbm=isch&oq=kuc&aqs=mobile-gws-lite.0.0l5&q=' + search
raw_html = (download_page(url))
items = []
items = items + (_images_get_all_items(raw_html))
path = random.choice(items)
print path
try:
ka.sendImageWithURL(msg.to,path)
except:
pass
#==============================================================================#
elif "Tr-id " in msg.text:
isi = msg.text.replace("Tr-id ","")
translator = Translator()
hasil = translator.translate(isi, dest='id')
A = hasil.text
A = A.encode('utf-8')
ka.sendText(msg.to, A)
elif "Tr-en " in msg.text:
isi = msg.text.replace("Tr-en ","")
translator = Translator()
hasil = translator.translate(isi, dest='en')
A = hasil.text
A = A.encode('utf-8')
ka.sendText(msg.to, A)
#==============================================================================#
elif "Id@en" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'en'
kata = msg.text.replace("Id@en ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
ka.sendText(msg.to,"----Dari Indonesia----\n" + "" + kata + "\n\n----Ke Inggris----\n" + "" + result)
elif "En@id" in msg.text:
bahasa_awal = 'en'
bahasa_tujuan = 'id'
kata = msg.text.replace("En@id ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
ka.sendText(msg.to,"----Dari Inggris----\n" + "" + kata + "\n\n----Ke Indonesia----\n" + "" + result)
#==============================================================================#
elif msg.text.lower() == 'runtime':
eltime = time.time() - mulai
van = "Bot Sudah Berjalan Selama :\n"+waktu(eltime)
ka.sendText(msg.to,van)
#==============================================================================#
elif msg.text.lower() == '/เช็คเวลาบอท':
eltime = time.time() - mulai
van = "🔘ระยะเวลาการทำงานของบอท:⤵️\n"+waktu(eltime)
ka.sendText(msg.to,van)
#==============================================================================#
elif "SearchID: " in msg.text:
userid = msg.text.replace("SearchID: ","")
contact = ka.findContactsByUserid(userid)
msg.contentType = 13
msg.contentMetadata = {'mid': contact.mid}
ka.sendMessage(msg)
#==============================================================================#
elif "LineID: " in msg.text:
userid = msg.text.replace("LineID: ","")
contact = ka.findContactsByUserid(userid)
msg.contentType = 13
msg.contentMetadata = {'mid': contact.mid}
ka.sendMessage(msg)
#==============================================================================#
elif "removechat" in msg.text.lower():
if msg.from_ in admin:
try:
ka.removeAllMessages(op.param2)
kb.removeAllMessages(op.param2)
kc.removeAllMessages(op.param2)
kd.removeAllMessages(op.param2)
ke.removeAllMessages(op.param2)
kf.removeAllMessages(op.param2)
kg.removeAllMessages(op.param2)
kh.removeAllMessages(op.param2)
ki.removeAllMessages(op.param2)
kj.removeAllMessages(op.param2)
print "[Command] Remove Chat"
ka.sendText(msg.to,"Done")
except Exception as error:
print error
ka.sendText(msg.to,"Error")
#==============================================================================#
elif "/ล้างแชทบอท" in msg.text.lower():
if msg.from_ in admin:
try:
ka.removeAllMessages(op.param2)
kb.removeAllMessages(op.param2)
kc.removeAllMessages(op.param2)
kd.removeAllMessages(op.param2)
ke.removeAllMessages(op.param2)
kf.removeAllMessages(op.param2)
kg.removeAllMessages(op.param2)
kh.removeAllMessages(op.param2)
ki.removeAllMessages(op.param2)
kj.removeAllMessages(op.param2)
print "[Command] Remove Chat"
ka.sendText(msg.to,"🔘ลบข้อมูลแชทบอทเรียบร้อย")
except Exception as error:
print error
ka.sendText(msg.to,"Error")
#==============================================================================#
elif msg.text in ["Glist"]:
if msg.from_ in owner:
ka.sendText(msg.to, "Tunggu Sebentar. . .")
gid = ka.getGroupIdsJoined()
h = ""
for i in gid:
h += "╠" + "%s\n" % (ka.getGroup(i).name +"▶["+str(len(ka.getGroup(i).members))+"]")
ka.sendText(msg.to,"╔════[ Glist ]════\n" + h + "╠════════════" + "\n║ Total Groups =" +" ["+str(len(gid))+"]\n╚════[ Glist ]════")
elif msg.text in ["Glistmid"]:
if msg.from_ in owner:
gruplist = ke.getGroupIdsJoined()
kontak = ke.getGroups(gruplist)
num=1
msgs="════════List GrupMid══════"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.id)
num=(num+1)
msgs+="\n══════List GrupMid════l═══\n\nTotal Grup : %i" % len(kontak)
ke.sendText(msg.to, msgs)
#==============================================================================#
if op.type == 25:
msg = op.message
if msg.text.lower() in ["pheytcg fgtagg all"]:
group = ka.getGroup(msg.to)
nama = [contact.mid for contact in group.members]
nm1, nm2, nm3, nm4, nm5, jml = [], [], [], [], [], len(nama)
if jml <= 100:
mention(msg.to, nama)
if jml > 100 and jml < 200:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, len(nama)):
nm2 += [nama[j]]
mention(msg.to, nm2)
if jml > 200 and jml < 300:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, 200):
nm2 += [nama[j]]
mention(msg.to, nm2)
for k in range(201, len(nama)):
nm3 += [nama[k]]
mention(msg.to, nm3)
if jml > 300 and jml < 400:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, 200):
nm2 += [nama[j]]
mention(msg.to, nm2)
for k in range(201, 300):
nm3 += [nama[k]]
mention(msg.to, nm3)
for l in range(301, len(nama)):
nm4 += [nama[l]]
mention(msg.to, nm4)
if jml > 400 and jml < 500:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, 200):
nm2 += [nama[j]]
mention(msg.to, nm2)
for k in range(201, 300):
nm3 += [nama[k]]
mention(msg.to, nm3)
for l in range(301, 400):
nm4 += [nama[l]]
mention(msg.to, nm4)
for h in range(401, len(nama)):
nm5 += [nama[h]]
mention(msg.to, nm5)
if jml > 500:
ka.sendText(msg.to,'Member melebihi batas.')
cnt = Message()
cnt.text = "PHET TAG DONE : " + str(jml) + " Members"
cnt.to = msg.to
ka.sendMessage(cnt)
if op.type == 26:
msg = op.message
if msg.text.lower() in ["1123"]:
group = ka.getGroup(msg.to)
nama = [contact.mid for contact in group.members]
nm1, nm2, nm3, nm4, nm5, jml = [], [], [], [], [], len(nama)
if jml <= 100:
mention(msg.to, nama)
if jml > 100 and jml < 200:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, len(nama)):
nm2 += [nama[j]]
mention(msg.to, nm2)
if jml > 200 and jml < 300:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, 200):
nm2 += [nama[j]]
mention(msg.to, nm2)
for k in range(201, len(nama)):
nm3 += [nama[k]]
mention(msg.to, nm3)
if jml > 300 and jml < 400:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, 200):
nm2 += [nama[j]]
mention(msg.to, nm2)
for k in range(201, 300):
nm3 += [nama[k]]
mention(msg.to, nm3)
for l in range(301, len(nama)):
nm4 += [nama[l]]
mention(msg.to, nm4)
if jml > 400 and jml < 500:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, 200):
nm2 += [nama[j]]
mention(msg.to, nm2)
for k in range(201, 300):
nm3 += [nama[k]]
mention(msg.to, nm3)
for l in range(301, 400):
nm4 += [nama[l]]
mention(msg.to, nm4)
for h in range(401, len(nama)):
nm5 += [nama[h]]
mention(msg.to, nm5)
if jml > 500:
ka.sendText(msg.to,'Member melebihi batas.')
cnt = Message()
cnt.text = "PHET TAG DONE : " + str(jml) + " Members"
cnt.to = msg.to
ka.sendMessage(cnt)
#=====================================================================================#
if op.type == 26:
msg = op.message
if msg.contentType == 16:
url = msg.contentMetadata['postEndUrl']
ka.like(url[25:58], url[66:], likeType=1001)
ka.comment(url[25:58], url[66:], wait["comment1"])
# ki1.like(url[25:58], url[66:], likeType=1001)
# ki1.comment(url[25:58], url[66:], wait["comment1"])
# ki2.like(url[25:58], url[66:], likeType=1001)
# ki2.comment(url[25:58], url[66:], wait["comment1"])
# ki3.like(url[25:58], url[66:], likeType=1001)
# ki3.comment(url[25:58], url[66:], wait["comment1"])
# ki4.like(url[25:58], url[66:], likeType=1001)
# ki4.comment(url[25:58], url[66:], wait["comment1"])
# ki5.like(url[25:58], url[66:], likeType=1001)
# ki5.comment(url[25:58], url[66:], wait["comment1"])
# ki6.like(url[25:58], url[66:], likeType=1001)
# ki6.comment(url[25:58], url[66:], wait["comment1"])
# ki7.like(url[25:58], url[66:], likeType=1001)
# ki7.comment(url[25:58], url[66:], wait["comment1"])
# ki8.like(url[25:58], url[66:], likeType=1001)
# ki8.comment(url[25:58], url[66:], wait["comment1"])
# ki9.like(url[25:58], url[66:], likeType=1001)
# ki9.comment(url[25:58], url[66:], wait["comment1"])
# ki10.like(url[25:58], url[66:], likeType=1001)
# ki10.comment(url[25:58], url[66:], wait["comment1"])
print ("AUTO LIKE SELFBOT")
print ("Auto Like By.TOMEBOTLINE")
#=====================================================================================#
if op.type == 55:
try:
if op.param1 in read['readPoint']:
if op.param2 in read['readMember'][op.param1]:
pass
else:
read['readMember'][op.param1] += op.param2
read['ROM'][op.param1][op.param2] = op.param2
with open('sider.json', 'w') as fp:
json.dump(read, fp, sort_keys=True, indent=4)
else:
pass
except:
pass
#==============================================================================#
if op.type == 59:
print op
except Exception as error:
print error
while True:
try:
Ops = ka.fetchOps(ka.Poll.rev, 5)
except EOFError:
raise Exception("It might be wrong revision\n" + str(ka.Poll.rev))
for Op in Ops:
if (Op.type != OpType.END_OF_OPERATION):
ka.Poll.rev = max(ka.Poll.rev, Op.revision)
bot(Op)
| 46.978302 | 1,021 | 0.438901 |
import LINETCR
from LINETCR.lib.curve.ttypes import *
from datetime import datetime
from time import sleep
from bs4 import BeautifulSoup
from threading import Thread
from googletrans import Translator
from gtts import gTTS
import time,random,sys,json,codecs,threading,glob,urllib,urllib2,urllib3,re,string,ast,os,subprocess,six,ast,pytz,requests,tempfile
ka = LINETCR.LINE()
ka.login(token='Esi6ZiwdDw5gpjEU9Cv9.Um990fn/eZ7CJP/I34GAIq./PwWHpfnEuZGLqzlrLpgHw0ThH0QploYuYq6xQKUdZc=')
ka.loginResult()
backup = LINETCR.LINE()
backup.login(token='Esi6ZiwdDw5gpjEU9Cv9.Um990fn/eZ7CJP/I34GAIq./PwWHpfnEuZGLqzlrLpgHw0ThH0QploYuYq6xQKUdZc=')
backup.loginResult()
print "Login.. SELFBOT_MAN_PROTECT"
reload(sys)
sys.setdefaultencoding('utf-8')
helpMessage ="""Thailand : SELFBOT_MAN_PC
╭══════════════════╮
║ ♨️ SELFBOT_MAN_PC_HELP ♨️
║͜͡☆➣ คำสั่ง-> 「Tome1」
║͜͡☆➣ คำสั่ง-> 「Tome2」
║͜͡☆➣ คำสั่ง-> 「Tome3」
║͜͡☆➣ คำสั่ง-> 「Tome4」
╰══════════════════╯
╭══════════════════╮
║ ♨️ติดตั้งชุดระบบป้องกัน[Protect]♨️
║ ลงคำสั่ง ครั้งเดียว ระบบทำงานยกเชุด
║•คำสั่ง.. Allprotect on
║•คำสั่ง.. Allprotect off
║•คำสั่ง.. เปิดระบบป้องกัน
║•คำสั่ง.. ปิดระบบป้องกัน
╰══════════════════╯
╭══════════════════╮
║ ♨️รับทำเชลบอท [SELFBOT] กันรัน
║•รับทำ..[ชุดบอทป้องกัน+Protect+]
║•รับทำ..[ชุดบอทส่วนตัว+Kicker+]
║•รับทำ..[บอทแท๊ก,ทั้งกลุ่ม+Mention]
║•รับทำ..[ชุดบอทบิน] ☞มีครบทุกฟังชั่น
╰══════════════════╯
──────┅═ইई═┅──────
สอบถามรายละเอียดเพิ่มเติม.. Link⤵️
http://line.me/ti/p/~1ove..neverdie
──────┅═ইई═┅──────
"""
creatorMessage ="""HELP_creator
╭══════════════════╮
║ ♨️ SELFBOT_MAN_PC_HELP ♨️
╰══════════════════╯
╭══════════════════╮
║͜͡☆➣ steal
║͜͡☆➣ /invitemeto:
║͜͡☆➣ Clear/Cancel
║͜͡☆➣ Ourl/Curl
║͜͡☆➣ Link on/off
║͜͡☆➣ Status/Set
║͜͡☆➣ Lurking
║͜͡☆➣ Gurl/URL/ลิงก์กลุ่ม
║͜͡☆➣ เข้า = Staff in
║͜͡☆➣ ออก = Staff bye
║͜͡☆➣ ตัวหลักออก = @bye
║͜͡☆➣ Leave all group
║͜͡☆➣ Banlist/บัญชีดำ
║͜͡☆➣ Clear ban/Cb/ล้างดำ
║͜͡☆➣ Bot restart
║͜͡☆➣ Glist
║͜͡☆➣ Glistmid
║͜͡☆➣
║͜͡☆➣ Tagall/Mention all
╰══════════════════╯
"""
setMessage ="""HELP_settings
╭══════════════════╮
║ ♨️ SELFBOT_MAN_PC_HELP ♨️
╰══════════════════╯
╭══════════════════╮
║͜͡☆➣ Purge on/off
║͜͡☆➣ Cancel on/off
║͜͡☆➣ Qr on/off
║͜͡☆➣ Contact on/off
║͜͡☆➣ Join on/off
║͜͡☆➣ Leave on/off
║͜͡☆➣ Share on/off
║͜͡☆➣ Simisimi on/off
║͜͡☆➣ Sider on/off
║͜͡☆➣ Lurking on/off
║͜͡☆➣ Lurking reset
║͜͡☆➣ Admin add @
║͜͡☆➣ Admin remove @
║͜͡☆➣ Sambutan on/off
║͜͡☆➣ Cancelinvite on/off
╰══════╬💀╬══════╯
"""
publikMessage ="""HELP_selfbot
╭══════════════════╮
║ ♨️ SELFBOT_MAN_PC_HELP ♨️
╰══════════════════╯
╭══════════════════╮
║͜͡☆➣ Me
║͜͡☆➣ Creator
║͜͡☆➣ Ginfo
║͜͡☆➣ Adminlist
║͜͡☆➣ List group
║͜͡☆➣ Absen
║͜͡☆➣ Respon
╰══════════════════╯
"""
mediaMessage ="""HELP_media
╭══════════════════╮
║ ♨️ SELFBOT_MAN_PC_HELP ♨️
╰══════════════════╯
╭══════════════════╮
║͜͡☆➣ /music
║͜͡☆➣ /lirik
║͜͡☆➣ /ig Instagrams
║͜͡☆➣ /yt: Youtubelink:
║͜͡☆➣ Say-id
║͜͡☆➣ Say-en
║͜͡☆➣ Say welcome
║͜͡☆➣ Playstore
║͜͡☆➣ /apakah
║͜͡☆➣ /hari
║͜͡☆➣ /berapa
║͜͡☆➣ /berapakah
║͜͡☆➣ /kapan
║͜͡☆➣ Image
║͜͡☆➣ Runtime
║͜͡☆➣ Tr-en แปลภาษา
║͜͡☆➣ Tr-id แปลภาษา
║͜͡☆➣ En@id อังกฤษ-อินโด
║͜͡☆➣ Id@en อินโด-อังกฤษ
║͜͡☆➣ SearchID:ใส่ใอดีไลน์
║͜͡☆➣ LineID:ใส่ใอดีไลน์
║͜͡☆➣ /เพลสโตร์:
║͜͡☆➣ /รูปภาพ:
║͜͡☆➣ /เช็คเวลาบอท
╰═════════════════╯
🔴✦เปิด/ปิดข้อความต้อนรับ✦🔴
╭══════════════════╮
║͜͡☆🔴➣ Hhx1 on ➠เปิดต้อนรับ
║͜͡☆🔴➣ Hhx1 off ➠ปิดต้อนรับ
║͜͡☆🔴➣ Hhx2 on ➠เปิดออกกลุ่ม
║͜͡☆🔴➣ Hhx2 off ➠ปิดออกกลุ่ม
║͜͡☆🔴➣ Hhx3 on ➠เปิดพูดถึงคนลบ
║͜͡☆🔴➣ Hhx3 off ➠ปิดพูดถึงคนลบ
║͜͡☆🔴➣ Mbot on ➠เปิดเเจ้งเตือน
║͜͡☆🔴➣ Mbot off ➠ปิดเเจ้งเตือน
║͜͡☆🔴➣ M on ➠เปิดเเจ้งเตือนตนเอง
║͜͡☆🔴➣ M off ➠ปิดเเจ้งเตือนตนเอง
║͜͡☆🔴➣ Tag on ➠เปิดกล่าวถึงเเท็ค
║͜͡☆🔴➣ Tag off ➠ปิดกล่าวถึงเเท็ค
║͜͡☆🔴➣ Kicktag on ➠เปิดเตะคนเเท็ค
║͜͡☆🔴➣ Kicktag off ➠ปิดเตะคนเเท็ค
╰═════════════════╯
🔴✦โหมดตั้งค่าข้อความ✦🔴
╭═════════════════╮
║͜͡☆🔴➣Hhx1˓: ➠ไส่ข้อความต้อนรับ
║͜͡☆🔴➣Hhx2˓: ➠ไส่ข้อความออกจากกลุ่ม
║͜͡☆🔴➣Hhx3˓: ➠ไส่ข้อความเมื่อมีคนลบ
║͜͡☆🔴➣Tag1: ➠ใส่ข้อความแทค
║͜͡☆🔴➣Tag2: ➠ ใส่ข้อความแทค
╰═════════════════╯
🔴✦โหมดเช็คตั้งค่าข้อความ✦🔴
╭═════════════════╮
║͜͡☆🔴➣Hhx1 ➠เช็คข้อความต้อนรับ
║͜͡☆🔴➣Hhx2 ➠เช็คข้อความคนออก
║͜͡☆🔴➣Hhx3 ➠เช็คข้อความคนลบ
║͜͡☆🔴➣Tag1 ➠เช็ตข้อความแทค
║͜͡☆🔴➣Tag2 ➠เช็คข้อความแทค
╰═════════════════╯
╭═════════════════╮
║─┅═✥ᴛᴇᴀᴍᵀᴴᴬᴵᴸᴬᴺᴰʙᴏᴛLɪɴᴇ✥═┅
║•─✯͜͡✯TOME★BOTLINE✯͜͡✯─•
╰═════════════════╯
ลิ้ง:http://line.me/ti/p/~tomebotline
──┅═✥===========✥═┅──
"""
KAC = [ka]
mid = ka.getProfile().mid
Bots=["ub8cf7dd0537e133edc8e9fa2df881a89",mid]
self = ["ub8cf7dd0537e133edc8e9fa2df881a89",mid]
admin = "ub8cf7dd0537e133edc8e9fa2df881a89"
admsa = "ub8cf7dd0537e133edc8e9fa2df881a89"
owner = "ub8cf7dd0537e133edc8e9fa2df881a89"
adminMID = "ub8cf7dd0537e133edc8e9fa2df881a89"
Creator="ub8cf7dd0537e133edc8e9fa2df881a89"
owner=["ub8cf7dd0537e133edc8e9fa2df881a89"]
admin=["ub8cf7dd0537e133edc8e9fa2df881a89"]
contact = ka.getProfile()
backup1 = ka.getProfile()
backup1.displayName = contact.displayName
backup1.statusMessage = contact.statusMessage
backup1.pictureStatus = contact.pictureStatus
responsename = ka.getProfile().displayName
wait = {
"contact":False,
"Bot":{},
'autoAdd':False,
"autoJoin":True,
"detectMention":True,
"kickMention":False,
"steal":False,
"autoCancel":{"on":True,"members":1},
"leaveRoom":True,
"timeline":True,
"likeOn":True,
"Timeline":True,
"autoAdd":False,
"lang":"JP",
"commentOn":True,
"comment1":"""
[ AOTO LIKE ]
[ SELF BOT ]
[ รับติดตั้ง เชลบอท ราคาประหยัด ]
─┅═✥ᴛᴇᴀᴍᵀᴴᴬᴵᴸᴬᴺᴰʙᴏᴛLɪɴᴇ✥═┅─
•─✯͜͡✯TOME★BOTLINE✯͜͡✯─•
http://line.me/ti/p/~tomebotline
▀██──▄███▄─▀██─██▀██▀▀▀█
─██─███─███─██─██─██▄█
─██─▀██▄██▀─▀█▄█▀─██▀█
▄██▄▄█▀▀▀─────▀──▄██▄▄▄█
📲 โทรศัพท์ 0928081567
""",
"comment1":"""
_________มีเซลบอท________จำหน่าย
________88888888________8888888
______888888888888____88888888888
__888888822222222222888882222888888
_888888822222222222222882222222228888
▀██▀─▄███▄─▀██─██▀██▀▀█
▒██─███─███─██─██─██▄█
▒██─▀██▄██▀─▀█▄█▀─██▀█
▄██▄▄█▀▀▀─────▀──▄██▄▄█
_888882222222222222222_____88888888
___8888888882222______88888888888
______88888_TOMEBOTLINE_8888888
________88_TEAMBOTTHAILAND_88
__________88888888888888888
______________88888888888
________________8888
╔•═•-⊰⊱•══•⊰⊱•═•⊰⊱•══•⊰⊱•═•╗
〘•สนใจติดต่อที่ลิ้งด้านล่าง•〙
👇👇👇👇
™〖Ĵắ¢ҝҝїě〗🌷TOME🎀BOTLINE🌷
™〖Ĵắ¢ҝҝїě〗☞ᵀËÄMBOTTHAILAND
http://line.me/ti/p/~tomebotline
╚•══•-⊰⊱•═•⊰⊱•═•⊰⊱•══•⊰ ⊱•═•╝
""",
"commentOn":True,
"acommentOn":False,
"bcommentOn":False,
"ccommentOn":False,
"commentBlack":{},
"wblack":False,
"dblack":False,
"wblacklist":False,
"dblacklist":False,
"Protectgr":False,
"Protectjoin":False,
"Protectcancl":False,
"Protectcancel":False,
"protectionOn":False,
"atjointicket":True,
"blacklist":{},
"steal":{},
"Hhx1":False,
"Hhx2":False,
"Hhx3":False,
"Notifed":False,
"Notifedbot":False,
"atjointicket":False,
"pnharfbot":{},
"pname":{},
"pro_name":{},
"tag1":"\n[🔯ยังไม่มีข้อความ ตอบกลับ🔯]",
"tag2":"\n[🔯ยังไม่มีข้อความ ตอบกลับ🔯]",
"posts":False,
"message":"Thank For Add Me.. \n\n คุยเรื่องบอทปรึกษาได้ครับ มีครบทุกฟังชั่น\nhttp://line.me/ti/p/~tomebotline \n(รับติดตั้งบอทSiri V10 และ รับทำเชลบอทกันรัน) \nเปิดสอนเขียนโปรแกรมบอท ชุดบอทป้องกัน บอทแท๊ก บอทแจ้งเตือนและต้อนรับสมาชิกเข้ากลุ่ม \n\nสนใจทักมาสอบถามได้ครับ \nLine ID. 1ove..neverdie",
"Sambutan":True,
"Sider":{},
}
cctv = {
"cyduk":{},
"point":{},
"sidermem":{}
}
read = {
"readPoint":{},
"readMember":{},
"readTime":{},
"ROM":{}
}
wait2 = {
"readPoint":{},
"readMember":{},
"setTime":{},
"ROM":{}
}
settings = {
"simiSimi":{}
}
setTime = {}
setTime = read['readTime']
mulai = time.time()
def download_page(url):
version = (3,0)
cur_version = sys.version_info
if cur_version >= version:
import urllib,request
try:
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
req = urllib,request.Request(url, headers = headers)
resp = urllib,request.urlopen(req)
respData = str(resp.read())
return respData
except Exception as e:
print(str(e))
else:
import urllib2
try:
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
req = urllib2.Request(url, headers = headers)
response = urllib2.urlopen(req)
page = response.read()
return page
except:
return"Page Not found"
def _images_get_next_item(s):
start_line = s.find('rg_di')
if start_line == -1:
end_quote = 0
link = "no_links"
return link, end_quote
else:
start_line = s.find('"class="rg_meta"')
start_content = s.find('"ou"',start_line+90)
end_content = s.find(',"ow"',start_content-90)
content_raw = str(s[start_content+6:end_content-1])
return content_raw, end_content
def _images_get_all_items(page):
items = []
while True:
item, end_content = _images_get_next_item(page)
if item == "no_links":
break
else:
items.append(item)
time.sleep(0.1)
page = page[end_content:]
return items
def waktu(secs):
mins, secs = divmod(secs,60)
hours, mins = divmod(mins,60)
return '%02d Jam %02d Menit %02d Detik' % (hours, mins, secs)
def cms(string, commands): #/XXX, >XXX, ;XXX, ^XXX, %XXX, $XXX...
tex = ["+","@","/",">",";","^","%","$","^","サテラ:","サテラ:","サテラ:","サテラ:"]
for texX in tex:
for command in commands:
if string ==command:
return True
return False
def upload_tempimage(client):
'''
Upload a picture of a kitten. We don't ship one, so get creative!
'''
config = {
'album': album,
'name': 'bot auto upload',
'title': 'bot auto upload',
'description': 'bot auto upload'
}
print("Uploading image... ")
image = client.upload_from_path(image_path, config=config, anon=False)
print("Done")
print()
return image
def summon(to, nama):
aa = ""
bb = ""
strt = int(14)
akh = int(14)
nm = nama
for mm in nm:
akh = akh + 2
aa += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M":"""+json.dumps(mm)+"},"""
strt = strt + 6
akh = akh + 4
bb += "\xe2\x95\xa0 @x \n"
aa = (aa[:int(len(aa)-1)])
msg = Message()
msg.to = to
msg.text = "\xe2\x95\x94\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\n"+bb+"\xe2\x95\x9a\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90"
msg.contentMetadata ={'MENTION':'{"MENTIONEES":['+aa+']}','EMTVER':'4'}
print "[Command] Tag All"
try:
ka.sendMessage(msg)
except Exception as error:
print error
def sendAudio(self, to_, path):
M = Message()
M.text = None
M.to = to_
M.contentMetadata = None
M.contentPreview = None
M.contentType = 3
M_id = self._client.sendMessage(0,M).id
files = {
'file': open(path, 'rb'),
}
def sendMessage(to, text, contentMetadata={}, contentType=0):
mes = Message()
mes.to, mes.from_ = to, profile.mid
mes.text = text
mes.contentType, mes.contentMetadata = contentType, contentMetadata
if to not in messageReq:
messageReq[to] = -1
messageReq[to] += 1
def sendImage(self, to_, path):
M = Message(to=to_, text=None, contentType = 1)
M.contentMetadata = None
M.contentPreview = None
M2 = self._client.sendMessage(0,M)
M_id = M2.id
files = {
'file': open(path, 'rb'),
}
params = {
'name': 'media',
'oid': M_id,
'size': len(open(path, 'rb').read()),
'type': 'image',
'ver': '1.0',
}
data = {
'params': json.dumps(params)
}
r = self.post_content('https://obs-sg.line-apps.com/talk/m/upload.nhn', data=data, files=files)
if r.status_code != 201:
raise Exception('Upload image failure.')
return True
def sendImageWithURL(self, to_, url):
path = '%s/pythonLine-%i.data' % (tempfile.gettempdir(), randint(0, 9))
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(path, 'w') as f:
shutil.copyfileobj(r.raw, f)
else:
raise Exception('Download image failure.')
try:
self.sendImage(to_, path)
except:
try:
self.sendImage(to_, path)
except Exception as e:
raise e
def sendAudio(self, to_, path):
M = Message()
M.text = None
M.to = to_
M.contentMetadata = None
M.contentPreview = None
M.contentType = 3
M_id = self._client.sendMessage(0,M).id
files = {
'file': open(path, 'rb'),
}
params = {
'name': 'media',
'oid': M_id,
'size': len(open(path, 'rb').read()),
'type': 'audio',
'ver': '1.0',
}
data = {
'params': json.dumps(params)
}
r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
if r.status_code != 201:
raise Exception('Upload audio failure.')
return True
def sendAudioWithURL(self, to_, url):
path = self.downloadFileWithURL(url)
try:
self.sendAudio(to_, path)
except Exception as e:
raise Exception(e)
def sendAudioWithUrl(self, to_, url):
path = '%s/pythonLine-%1.data' % (tempfile.gettempdir(), randint(0, 9))
r = requests.get(url, stream=True, verify=False)
if r.status_code == 200:
with open(path, 'w') as f:
shutil.copyfileobj(r.raw, f)
else:
raise Exception('Download audio failure.')
try:
self.sendAudio(to_, path)
except Exception as e:
raise e
def sendVideo(self, to_, path):
M = Message(to=to_,contentType = 2)
M.contentMetadata = {
'VIDLEN' : '0',
'DURATION' : '0'
}
M.contentPreview = None
M_id = self.Talk.client.sendMessage(0,M).id
files = {
'file': open(path, 'rb'),
}
params = {
'name': 'media',
'oid': M_id,
'size': len(open(path, 'rb').read()),
'type': 'video',
'ver': '1.0',
}
data = {
'params': json.dumps(params)
}
r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
if r.status_code != 201:
raise Exception('Upload image failure.')
return True
def sendVideoWithURL(self, to_, url):
path = 'pythonLines.data'
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(path, 'w') as f:
shutil.copyfileobj(r.raw, f)
else:
raise Exception('Download Audio failure.')
try:
self.sendVideo(to_, path)
except Exception as e:
raise e
def sendGif(self, to_, path):
M = Message(to=to_,contentType = 1)
M.contentMetadata = {
'VIDLEN' : '0',
'DURATION' : '0'
}
M.contentPreview = None
M_id = self.Talk.client.sendMessage(0,M).id
files = {
'file': open(path, 'rb'),
}
params = {
'name': 'media',
'oid': M_id,
'size': len(open(path, 'rb').read()),
'type': 'image',
'ver': '1.0',
}
data = {
'params': json.dumps(params)
}
r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
if r.status_code != 201:
raise Exception('Upload Gif failure.')
return True
def sendGifWithURL(self, to_, url):
path = 'pythonLiness.data'
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(path, 'w') as f:
shutil.copyfileobj(r.raw, f)
else:
raise Exception('Download Gif failure.')
try:
self.sendGif(to_, path)
except Exception as e:
raise e
def downloadFileWithURL(self, fileUrl):
saveAs = '%s/pythonLine-%i.data' % (tempfile.gettempdir(), randint(0, 9))
r = self.get_content(fileUrl)
if r.status_code == 200:
with open(saveAs, 'wb') as f:
shutil.copyfileobj(r.raw, f)
return saveAs
else:
raise Exception('Download file failure.')
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
def bot(op):
try:
if op.type == 0:
return
if op.type == 5:
if wait["autoAdd"] == True:
ka.findAndAddContactsByMid(op.param1)
if(wait["message"]in[""," ","\n",None]):
pass
else:
ka.sendText(op.param1,str(wait["message"]))
if op.type == 55:
try:
group_id = op.param1
user_id=op.param2
subprocess.Popen('echo "'+ user_id+'|'+str(op.createdTime)+'" >> dataSeen/%s.txt' % group_id, shell=True, stdout=subprocess.PIPE, )
except Exception as e:
print e
if op.type == 55:
try:
if cctv['cyduk'][op.param1]==True:
if op.param1 in cctv['point']:
Name = ka.getContact(op.param2).displayName
if Name in cctv['sidermem'][op.param1]:
pass
else:
cctv['sidermem'][op.param1] += "\n• " + Name
if " " in Name:
nick = Name.split(' ')
if len(nick) == 2:
ka.sendText(op.param1, "Hi " + "[ " + Name + " ]" + "\ndo not take a peek here to chat😁 ")
time.sleep(0.2)
summon(op.param1,[op.param2])
else:
ka.sendText(op.param1, "Hi " + "[ " + Name + " ]" + "\ndo not take a peek here to chat😁 ")
time.sleep(0.2)
summon(op.param1,[op.param2])
else:
ka.sendText(op.param1, "Hi " + "☞ " + Name + " ☜" + "\ndo not take a peek here to chat😁 ")
time.sleep(0.2)
summon(op.param1,[op.param2])
else:
pass
else:
pass
except:
pass
else:
pass
#==============================================================================#
if op.type == 22:
if wait["leaveRoom"] == True:
ka.leaveRoom(op.param1)
if op.type == 24:
if wait["leaveRoom"] == True:
ka.leaveRoom(op.param1)
if op.type == 26:
msg = op.message
#==============================================================================#
if op.type == 13:
if mid in op.param3:
if wait["autoJoin"] == True:
if op.param2 in owner:
ka.acceptGroupInvitation(op.param1)
G = ka.getGroup(op.param1)
G.preventJoinByTicket = False
ka.updateGroup(G)
Ticket = ka.reissueGroupTicket(op.param1)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
# kc.acceptGroupInvitationByTicket(op.param1,Ticket)
# kd.acceptGroupInvitationByTicket(op.param1,Ticket)
# ke.acceptGroupInvitationByTicket(op.param1,Ticket)
# kf.acceptGroupInvitationByTicket(op.param1,Ticket)
# kg.acceptGroupInvitationByTicket(op.param1,Ticket)
# kh.acceptGroupInvitationByTicket(op.param1,Ticket)
# ki.acceptGroupInvitationByTicket(op.param1,Ticket)
# kj.acceptGroupInvitationByTicket(op.param1,Ticket)
G.preventJoinByTicket = True
ka.updateGroup(G)
else:
ka.rejectGroupInvitation(op.param1)
# if Amid in op.param3:
# if wait["autoJoin"] == True:
# if op.param2 in owner:
# kb.acceptGroupInvitation(op.param1)
# else:
# kb.rejectGroupInvitation(op.param1)
# else:
# print "autoJoin is Off"
# if Bmid in op.param3:
# if wait["autoJoin"] == True:
# if op.param2 in owner:
# kc.acceptGroupInvitation(op.param1)
# else:
# kc.rejectGroupInvitation(op.param1)
# else:
# print "autoJoin is Off"
#
# if Cmid in op.param3:
# if wait["autoJoin"] == True:
# if op.param2 in owner:
# kd.acceptGroupInvitation(op.param1)
# else:
# kd.rejectGroupInvitation(op.param1)
# else:
# print "autoJoin is Off"
#
# if Dmid in op.param3:
# if wait["autoJoin"] == True:
# if op.param2 in owner:
# ke.acceptGroupInvitation(op.param1)
# else:
# ke.rejectGroupInvitation(op.param1)
# else:
# print "autoJoin is Off"
#
# if Emid in op.param3:
# if wait["autoJoin"] == True:
# if op.param2 in owner:
# kf.acceptGroupInvitation(op.param1)
# else:
# kf.rejectGroupInvitation(op.param1)
# else:
# print "autoJoin is Off"
#
#if Fmid in op.param3:
# if wait["autoJoin"] == True:
# if op.param2 in owner:
# kg.acceptGroupInvitation(op.param1)
# else:
# kg.rejectGroupInvitation(op.param1)
# else:
# print "autoJoin is Off"
# if Gmid in op.param3:
# if wait["autoJoin"] == True:
# if op.param2 in owner:
# kh.acceptGroupInvitation(op.param1)
# else:
# kh.rejectGroupInvitation(op.param1)
# else:
# print "autoJoin is Off"
# if Hmid in op.param3:
# if wait["autoJoin"] == True:
# if op.param2 in owner:
# ki.acceptGroupInvitation(op.param1)
# else:
# ki.rejectGroupInvitation(op.param1)
# else:
# print "autoJoin is Off"
# if Imid in op.param3:
# if wait["autoJoin"] == True:
# if op.param2 in owner:
# kj.acceptGroupInvitation(op.param1)
# else:
# kj.rejectGroupInvitation(op.param1)
# else:
# print "autoJoin is Off"
if Jmid in op.param3:
if wait["autoJoin"] == True:
if op.param2 in owner:
ka.acceptGroupInvitation(op.param1)
else:
ka.rejectGroupInvitation(op.param1)
else:
print "autoJoin is Off"
#=========================================================================#
if op.type == 13:
if mid in op.param3:
G = ka.getGroup(op.param1)
if wait["autoJoin"] == True:
if wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
ka.rejectGroupInvitation(op.param1)
else:
ka.acceptGroupInvitation(op.param1)
ka.sendText(op.param1, "Your invitation was declined\n\n[SELF BOT\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]]\n\nhttp://line.me/ti/p/9r-uE5EU09")
else:
ka.acceptGroupInvitation(op.param1)
ka.sendText(op.param1, "Your invitation was declined\n\n[SEL FBOT\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]]\n\nhttp://line.me/ti/p/9r-uE5EU09")
elif wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
ka.rejectGroupInvitation(op.param1)
else:
Inviter = op.param3.replace("",',')
InviterX = Inviter.split(",")
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, InviterX)
if matched_list == []:
pass
else:
ka.cancelGroupInvitation(op.param1, matched_list)
if Amid1 in op.param3:
G = ka.getGroup(op.param1)
if wait["autoJoin"] == True:
if wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
kb.rejectGroupInvitation(op.param1)
else:
kb.acceptGroupInvitation(op.param1)
else:
kb.acceptGroupInvitation(op.param1)
elif wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
kb.rejectGroupInvitation(op.param1)
else:
Inviter = op.param3.replace("",',')
InviterX = Inviter.split(",")
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, InviterX)
if matched_list == []:
pass
else:
kb.cancelGroupInvitation(op.param1, matched_list)
if Amid2 in op.param3:
G = ka.getGroup(op.param1)
if wait["autoJoin"] == True:
if wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
kc.rejectGroupInvitation(op.param1)
else:
kc.acceptGroupInvitation(op.param1)
else:
kc.acceptGroupInvitation(op.param1)
elif wait["autoCancel"]["on"] == True:
if len(G.members) <= wait["autoCancel"]["members"]:
kc.rejectGroupInvitation(op.param1)
#==============================================================================#
if op.type == 13:
if wait["Protectcancl"] == True:
group = ka.getGroup(op.param1)
gMembMids = [contact.mid for contact in group.invitee]
if op.param2 not in Bots or admin:
if op.param2 in Bots:
pass
elif op.param2 in owner:
pass
elif op.param2 in admin:
pass
else:
try:
ka.cancelGroupInvitation(op.param1, gMembMids)
ka.sendText(op.param1,ka.getContact(op.param2).displayName + "\n" + "Who do you want to invite ??? \nYou Are Not Our Admin, So We Cancel it.\nPlease Contact Admin/Owner")
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
except:
random.choice(KAC).cancelGroupInvitation(op.param1, gMembMids)
random.choice(KAC).sendText(op.param1,random.choice(KAC).getContact(op.param2).displayName + "\n" + "🔘Who do you want to invite ??? \n🔘You Are Not Our Admin, So We Cancel it.\n🔘Please Contact Admin/Owner\n\n[ระบบออโต้ถูกเปิดใช้งาน]\n🔘การเชิญสมาชิกเข้าร่วมกลุ่ม ควรแจ้งให้ทราบ..\n🔘โดยผ่าน.. Admin:bot-group หรือลงข้อมูลสมาชิกไว้\n(หากผิดพลาดยังใง รบกวนทักแชท)")
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
#==============================================================================#
if op.type == 13:
if wait["Protectcancl"] == True:
if wait["blacklist"][op.param3] == True:
ka.sendText(op.param1,ka.getContact(op.param3).displayName + " On Blacklist Boss Man\n•We Will Cancel Invitation\n•by : SELFBOT_MAN_PROTECT")
random.choice(KAC).cancelGroupInvitation(op.param1,[op.param3])
#==============================================================================#
if op.type == 11:
if wait["Protectgr"] == True:
if ka.getGroup(op.param1).preventJoinByTicket == False:
if op.param2 in Bots:
pass
elif op.param2 in owner:
pass
elif op.param2 in admin:
pass
else:
random.choice(KAC).sendText(op.param1,random.choice(KAC).getContact(op.param2).displayName + "Dont Playing Link Group Bro")
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
random.choice(KAC).preventJoinByTicket = True
random.choice(KAC).sendText(op.param1,random.choice(KAC).getContact(op.param2).displayName + "\n" + "🔘We Enter Into Blacklist Boss Man")
wait["blacklist"][op.param2] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
#==============================================================================#
if op.type == 17:
if wait["Sambutan"] == True:
if op.param2 in owner:
return
ginfo = ka.getGroup(op.param1)
contact = ka.getContact(op.param2)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
ka.sendText(op.param1,"•Hello ↪️" + ka.getContact(op.param2).displayName + "↩️\n•Welcome To 🔛 " + str(ginfo.name) + " " + "\n•by : SELFBOT_MAN_PROTECT")
c = Message(to=op.param1, from_=None, text=None, contentType=13)
c.contentMetadata={'mid':op.param2}
ka.sendMessage(c)
ka.sendImageWithURL(op.param1,image)
d = Message(to=op.param1, from_=None, text=None, contentType=7)
d.contentMetadata={
"STKID": "247",
"STKPKGID": "3",
"STKVER": "100" }
ka.sendMessage(d)
print "MEMBER JOIN TO GROUP"
#==============================================================================#
if op.type == 15:
if wait["Sambutan"] == True:
if op.param2 in admin:
return
ka.sendText(op.param1,"Good Bye " + ka.getContact(op.param2).displayName + "\nSee You Next Time . . . (p′︵‵。) 🤗")
c = Message(to=op.param1, from_=None, text=None, contentType=13)
c.contentMetadata={'mid':op.param2}
ka.sendMessage(c)
random.choice(KAC).inviteIntoGroup(op.param1,[op.param2])
print "MEMBER HAS LEFT THE GROUP"
#==============================================================================#
if op.type == 17: #Protect Join
if wait["Protectjoin"] == True:
if wait["blacklist"][op.param2] == True:
ka.sendText(op.param1,ka.getContact(op.param2).displayName + " On Blacklist Boss Man\n•We Will Kick 👀")
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
#==============================================================================#
if op.type == 17:
if wait["Notifed"] == True:
if op.param2 in owner:
return
ginfo = ka.getGroup(op.param1)
contact = ka.getContact(op.param2)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
ka.sendText(op.param1,"•สวัสดีจ้าคนมาใหม่ ↪" + ka.getContact(op.param2).displayName + "↩️\n•ยินดีต้อนรับสู่ห้อง\n 🔛 " + str(ginfo.name) + " " + "\n\n•by : SELFBOT TOME↔BOTLINE")
c = Message(to=op.param1, from_=None, text=None, contentType=13)
c.contentMetadata={'mid':op.param2}
ka.sendMessage(c)
ka.sendImageWithURL(op.param1,image)
d = Message(to=op.param1, from_=None, text=None, contentType=7)
d.contentMetadata={
"STKID": "247",
"STKPKGID": "3",
"STKVER": "100" }
ka.sendMessage(d)
print "MEMBER JOIN TO GROUP"
#==============================================================================#
if op.type == 15:
if wait["Notifed"] == True:
if op.param2 in admin:
return
ka.sendText(op.param1,"Good Bye " + ka.getContact(op.param2).displayName + "\nSee You Next Time . . . (p′︵‵。) 🤗")
c = Message(to=op.param1, from_=None, text=None, contentType=13)
c.contentMetadata={'mid':op.param2}
ka.sendMessage(c)
ka.sendImageWithURL(op.param1,image)
random.choice(KAC).inviteIntoGroup(op.param1,[op.param2])
print "MEMBER HAS LEFT THE GROUP"
#==============================================================================#
if op.type == 19:
if wait["Notifed"] == True:
if op.param2 in Bots:
return
ka.sendText(op.param1,cl.getContact(op.param2).displayName + "\n ไม่น่าจะจุกเท่าไหร่หรอก ")
print "MEMBER HAS KICKOUT FROM THE GROUP"
if op.type == 15:
if wait["Notifedbot"] == True:
if op.param2 in Bots:
return
ki1.sendText(op.param1,cl.getContact(op.param2).displayName + "\n\n Bye~bye ")
ki2.sendText(op.param1,cl.getContact(op.param2).displayName + "\n\n Bye~bye ")
print "MEMBER OUT GROUP"
if op.type == 17:
if wait["Notifedbot"] == True:
if op.param2 in Bots:
return
ginfo = cka.getGroup(op.param1)
contact = ka.getContact(op.param2)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
ka.sendImageWithURL(op.param1,image)
ka.sendText(op.param1,cl.getContact(op.param2).displayName + "\n\n[🙋ยินดี���อนรับ][By. ☬ധู้さန້ণق↔ധഖาໄฟ☬]")
print "MEMBER HAS JOIN THE GROUP"
if op.type == 19:
if wait["Notifedbot"] == True:
if op.param2 in Bots:
return
ki1.sendText(op.param1,cl.getContact(op.param2).displayName + "\n ไม่น่าจะจุกเท่าไหร่หรอก ")
ki2.sendText(op.param1,cl.getContact(op.param2).displayName + "\n ไม่น่าจะจุกเท่าไหร่หรอก ")
print "MEMBER HAS KICKOUT FROM THE GROUP"
# if op.type == 15:
# if wait["bcommentOn"] == True:
# if op.param2 in Bots:
# return
# cl.sendText(op.param1,cl.getContact(op.param2).displayName + "\n" + str(wait["bcomment"]))
# print "MEMBER OUT GROUP"
# if op.type == 17:
# if wait["acommentOn"] == True:
# if op.param2 in Bots:
# return
# cl.sendText(op.param1,cl.getContact(op.param2).displayName + "\n" + str(wait["acomment"]))
# print "MEMBER HAS JOIN THE GROUP"
#==============================================================================#
if op.type == 17:
if wait["acommentOn"] == True:
if op.param2 in Bots:
return
ginfo = ka.getGroup(op.param1)
contact = ka.getContact(op.param2)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
ka.sendText(op.param1,"•Hello ↪️" + ka.getContact(op.param2).displayName + "↩️\n•Welcome To 🔛 " + str(wait["acommentOn"]) + " " + "\n•by : SELFBOTTOME↔BOTLINE")
c = Message(to=op.param1, from_=None, text=None, contentType=13)
c.contentMetadata={'mid':op.param2}
ka.sendMessage(c)
ka.sendImageWithURL(op.param1,image)
d = Message(to=op.param1, from_=None, text=None, contentType=7)
d.contentMetadata={
"STKID": "247",
"STKPKGID": "3",
"STKVER": "100" }
ka.sendMessage(d)
print "MEMBER JOIN TO GROUP"
#==============================================================================#
if op.type == 15:
if wait["bcommentOn"] == True:
if op.param2 in Bots:
return
ka.sendText(op.param1,"Good Bye " + ka.getContact(op.param2).displayName + str(["bcommentOn"]))
c = Message(to=op.param1, from_=None, text=None, contentType=13)
c.contentMetadata={'mid':op.param2}
ka.sendMessage(c)
ka.sendImageWithURL(op.param1,image)
random.choice(KAC).inviteIntoGroup(op.param1,[op.param2])
print "MEMBER HAS LEFT THE GROUP"
#==============================================================================#
if op.type == 19:
if wait["ccommentOn"] == True:
if op.param2 in Bots:
return
ka.sendText(op.param1,cl.getContact(op.param2).displayName + "\n" + str(wait["ccomment"]))
print "MEMBER HAS KICKOUT FROM THE GROUP"
#==============================================================================#
if op.type == 19: #Member Ke Kick
if op.param2 in Bots:
pass
elif op.param2 in owner:
pass
elif op.param2 in admin:
pass
else:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
wait["blacklist"][op.param2] = True
#==============================================================================#
# if op.type == 26:
# msg = op.message
# if msg.contentType == 16:
# url = msg.contentMetadata['postEndUrl']
# ka.like(url[25:58], url[66:], likeType=1001)
# ka.comment(url[25:58], url[66:], wait["comment1"])
# ki1.like(url[25:58], url[66:], likeType=1001)
# ki1.comment(url[25:58], url[66:], wait["comment1"])
# ki2.like(url[25:58], url[66:], likeType=1001)
# ki2.comment(url[25:58], url[66:], wait["comment1"])
# ki3.like(url[25:58], url[66:], likeType=1001)
# ki3.comment(url[25:58], url[66:], wait["comment1"])
# ki4.like(url[25:58], url[66:], likeType=1001)
# ki4.comment(url[25:58], url[66:], wait["comment1"])
# ki5.like(url[25:58], url[66:], likeType=1001)
# ki5.comment(url[25:58], url[66:], wait["comment1"])
# ki6.like(url[25:58], url[66:], likeType=1001)
# ki6.comment(url[25:58], url[66:], wait["comment1"])
# ki7.like(url[25:58], url[66:], likeType=1001)
# ki7.comment(url[25:58], url[66:], wait["comment1"])
# ki8.like(url[25:58], url[66:], likeType=1001)
# ki8.comment(url[25:58], url[66:], wait["comment1"])
# ki9.like(url[25:58], url[66:], likeType=1001)
# ki9.comment(url[25:58], url[66:], wait["comment1"])
# ki10.like(url[25:58], url[66:], likeType=1001)
# ki10.comment(url[25:58], url[66:], wait["comment1"])
# print ("AUTO LIKE SELFBOT")
# print ("Auto Like By.☬ധู้さန້ণق↔ധഖาໄฟ☬")
#==============================================================================#
if op.type == 19:
if op.param2 in Bots:
pass
elif op.param2 in owner:
pass
elif op.param2 in admin:
pass
else:
if op.param3 in mid:
if op.param2 not in Bots or owner:
G = kj.getGroup(op.param1)
G.preventJoinByTicket = False
kj.updateGroup(G)
Ticket = kj.reissueGroupTicket(op.param1)
backup.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
backup.kickoutFromGroup(op.param1,[op.param2])
H = backup.getGroup(op.param1)
H.preventJoinByTicket = False
backup.updateGroup(H)
Ticket = backup.reissueGroupTicket(op.param1)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = kj.getGroup(op.param1)
G.preventJoinByTicket = True
kj.updateGroup(G)
backup.leaveGroup(op.param1)
wait["blacklist"][op.param2] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
#==============================================================================#
elif op.param3 in Amid:
if op.param2 not in Bots or owner:
G = kc.getGroup(op.param1)
kc.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
kc.updateGroup(G)
Ticket = kc.reissueGroupTicket(op.param1)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = kc.getGroup(op.param1)
G.preventJoinByTicket = True
kc.updateGroup(G)
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in Bmid:
if op.param2 not in Bots or owner:
G = kd.getGroup(op.param1)
kd.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
kd.updateGroup(G)
Ticket = kd.reissueGroupTicket(op.param1)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = kd.getGroup(op.param1)
G.preventJoinByTicket = True
kd.updateGroup(G)
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in Cmid:
if op.param2 not in Bots or owner:
G = ke.getGroup(op.param1)
ke.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
ke.updateGroup(G)
Ticket = ke.reissueGroupTicket(op.param1)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = ke.getGroup(op.param1)
G.preventJoinByTicket = True
ke.updateGroup(G)
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in Dmid:
if op.param2 not in Bots or owner:
G = kf.getGroup(op.param1)
kf.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
kf.updateGroup(G)
Ticket = kf.reissueGroupTicket(op.param1)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = kf.getGroup(op.param1)
G.preventJoinByTicket = True
kf.updateGroup(G)
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in Emid:
if op.param2 not in Bots or owner:
G = kg.getGroup(op.param1)
kg.kickoutFromGroup(op.param1,[op.param2])
G.reventJoinByTicket = False
kg.updateGroup(G)
Ticket = kg.reissueGroupTicket(op.param1)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = kg.getGroup(op.param1)
G.preventJoinByTicket = True
kg.updateGroup(G)
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in Fmid:
if op.param2 not in Bots or owner:
G = kh.getGroup(op.param1)
kh.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
kh.updateGroup(G)
Ticket = kh.reissueGroupTicket(op.param1)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = kh.getGroup(op.param1)
G.preventJoinByTicket = True
kh.updateGroup(G)
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in Gmid:
if op.param2 not in Bots or owner:
G = ki.getGroup(op.param1)
ki.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
ki.updateGroup(G)
Ticket = ki.reissueGroupTicket(op.param1)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = ki.getGroup(op.param1)
G.preventJoinByTicket = True
ki.updateGroup(G)
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in Hmid:
if op.param2 not in Bots or owner:
G = kj.getGroup(op.param1)
kj.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
kj.updateGroup(G)
Ticket = kj.reissueGroupTicket(op.param1)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = kj.getGroup(op.param1)
G.preventJoinByTicket = True
kj.updateGroup(G)
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in Imid:
if op.param2 not in Bots or owner:
G = kb.getGroup(op.param1)
kb.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
kb.updateGroup(G)
Ticket = kb.reissueGroupTicket(op.param1)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = kb.getGroup(op.param1)
G.preventJoinByTicket = True
kb.updateGroup(G)
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in Jmid:
if op.param2 not in Bots or owner:
G = ka.getGroup(op.param1)
ka.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
ka.updateGroup(G)
Ticket = ka.reissueGroupTicket(op.param1)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kb.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
ka.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.00001)
G = ka.getGroup(op.param1)
G.preventJoinByTicket = True
ka.updateGroup(G)
wait["blacklist"][op.param2] = True
#===============================================================================#
if op.type == 19: #admin
if op.param2 in Bots:
pass
elif op.param2 in owner:
pass
elif op.param2 in admin:
pass
else:
try:
if op.param3 in admin:
if op.param2 not in Bots or owner:
if op.param2 in Bots:
pass
elif op.param2 in owner:
pass
else:
try:
ka.kickoutFromGroup(op.param1,[op.param2])
kb.kickoutFromGroup(op.param1,[op.param2])
kc.kickoutFromGroup(op.param1,[op.param2])
kd.kickoutFromGroup(op.param1,[op.param2])
ke.kickoutFromGroup(op.param1,[op.param2])
kf.kickoutFromGroup(op.param1,[op.param2])
kg.kickoutFromGroup(op.param1,[op.param2])
kh.kickoutFromGroup(op.param1,[op.param2])
ki.kickoutFromGroup(op.param1,[op.param2])
kj.kickoutFromGroup(op.param1,[op.param2])
ka.inviteIntoGroup(op.param1,[op.param3])
kb.inviteIntoGroup(op.param1,[op.param3])
kc.inviteIntoGroup(op.param1,[op.param3])
kd.inviteIntoGroup(op.param1,[op.param3])
ke.inviteIntoGroup(op.param1,[op.param3])
kf.inviteIntoGroup(op.param1,[op.param3])
kg.inviteIntoGroup(op.param1,[op.param3])
kh.inviteIntoGroup(op.param1,[op.param3])
ki.inviteIntoGroup(op.param1,[op.param3])
kj.inviteIntoGroup(op.param1,[op.param3])
wait["blacklist"][op.param2] = True
except:
random.choice(KAC).getGroup(op.param1)
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
random.choice(KAC).inviteIntoGroup(op.param1,[op.param3])
wait["blacklist"][op.param2] = True
#==============================================================================#
elif op.param3 in owner:
if op.param2 not in Bots or owner:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
#ka.inviteIntoGroup(op.param1,[op.param3])
wait["blacklist"][op.param2] = True
except:
random.choice(KAC).getGroup(op.param1)
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
#random.choice(KAC).inviteIntoGroup(op.param1,[op.param3])
wait["blacklist"][op.param2] = True
except:
try:
ka.kickoutFromGroup(op.param1,[op.param2])
wait["blacklist"][op.param2] = True
except:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
wait["blacklist"][op.param2] = True
#==============================================================================#
if op.type == 22:
if wait["leaveRoom"] == True:
ka.leaveRoom(op.param1)
if op.type == 24:
if wait["leaveRoom"] == True:
ka.leaveRoom(op.param1)
#==============================================================================#
if op.type == 25:
msg = op.message
if op.type == 19:
if op.param2 in Bots:
pass
elif op.param2 in admin:
pass
else:
msg = Message(to=op.param1, from_=None, text=None, contentType=13)
msg.contentMetadata={'mid':op.param2}
ka.sendMessage(msg)
ka.sendText(op.param1,ka.getContact(op.param2).displayName + " Kick 👀")
#==============================================================================#
if op.type == 11:
if op.param2 in Bots:
pass
elif op.param2 in admin:
pass
else:
msg = Message(to=op.param1, from_=None, text=None, contentType=13)
msg.contentMetadata={'mid':op.param2}
ka.sendMessage(msg)
#==============================================================================#
if op.type == 25:
msg = op.message
if msg.to in settings["simiSimi"]:
if settings["simiSimi"][msg.to] == True:
if msg.text is not None:
text = msg.text
r = requests.get("http://api.ntcorp.us/chatbot/v1/?text=" + text.replace(" ","+") + "&key=beta1.nt")
data = r.text
data = json.loads(data)
if data['status'] == 200:
if data['result']['result'] == 100:
ka.sendText(msg.to, "「MAN-auto-Chat」⤵️" + "\n" + data['result']['response'].encode('utf-8'))
#==============================================================================#
if 'MENTION' in msg.contentMetadata.keys() != None:
if wait["detectMention"] == True:
contact = ka.getContact(msg.from_)
cName = contact.displayName
balas = [cName + "\n" + str(wait["tag1"]) , cName + "\n" + str(wait["tag2"])]
ret_ = "[Auto Respond] " + random.choice(balas)
name = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata['MENTION'])
mentionees = mention['MENTIONEES']
for mention in mentionees:
if mention['M'] in Bots:
ka.sendText(msg.to,ret_)
break
# if 'MENTION' in msg.contentMetadata.keys() != None:
# if wait["detectMention"] == True:
# contact = cl.getContact(msg.from_)
# cName = contact.displayName
# balas = ["Dont Tag Me!! Im Busy",cName + ""]
# ret_ = "[Auto] " + random.choice(balas)
# name = re.findall(r'@(\w+)', msg.text)
# mention = ast.literal_eval(msg.contentMetadata['MENTION'])
# mentionees = mention['MENTIONEES']
# for mention in mentionees:
# if mention['M'] in Bots:
# cl.sendText(msg.to,ret_)
# msg.contentType = 7
# msg.text = ''
# msg.contentMetadata = {
# 'STKPKGID': '9662',
# 'STKTXT': '[]',
# 'STKVER': '16',
# 'STKID':'697'
# }
# cl.sendMessage(msg)
# break
if "MENTION" in msg.contentMetadata.keys() != None:
if wait['detectMention'] == True:
contact = ka.getContact(msg.from_)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
cName = contact.displayName
msg.text1 = "@"+cName+" "
balas = ["\n╭═════════════════╮\n║͜͡☆➣🔒มีเชลบอทลบรัน พร้อมคิกเก้อ💟\n║͜͡☆➣🔒ลบบินกลุ่ม ออโต้ไลค์\n║͜͡☆➣ 🔒และอื่นๆอีกมากมาย\n║͜͡☆➣🔒กันสมาชิกเปิดลิ้งห้อง\n║͜͡☆➣🔒กันรัน\n║͜͡☆➣🔒กันสมาชิกเชิญคนนอกเข้า\n║͜͡☆➣🔒กันสมาชิกเปลี่ยนชื่อกลุ่ม\n║͜͡☆➣🔒กันคนนอกเข้ามาลบคนในกลุ่ม\n║͜͡☆➣🔒และยังมีเซลกันรันอีกด้วย ราคา150บาท\n║͜͡☆➣👉สนใจติดต่อลิ้งด้านล่างเรยครับ👈\n║͜͡☆➣โอนเข้าบัญชี💲เทานั้น\n║͜͡☆➣สนใจ แอดมาคุยได้\n╰═════════════════╯\n╭═════════════════╮\n║͜͡☆➣http://line.me/ti/p/~dmc.072_tome\n║͜͡☆➣http://line.me/ti/p/~tomebotline\n╰═════════════════╯"]
ret_ = msg.text1 + random.choice(balas)
name = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata["MENTION"])
mentionees = mention['MENTIONEES']
for mention in mentionees:
if mention['M'] in Bots:
ka.sendText(msg.to,ret_)
msg.contentType = 7
msg.text = ''
msg.contentMetadata = {
'STKPKGID': '35485149',
'STKTXT': '[]',
'STKVER': '16',
'STKID':'3232633'
}
ka.sendImageWithURL(msg.to,image)
break
if 'MENTION' in msg.contentMetadata.keys() != None:
if wait["kickMention"] == True:
contact = ka.getContact(msg.from_)
cName = contact.displayName
balas = ["Dont Tag Me!! Im Busy",cName + " Ngapain Ngetag?",cName + " Nggak Usah Tag-Tag! Kalo Penting Langsung Pc Aja","-_-","Alin lagi off", cName + " Kenapa Tag saya?","SPAM PC aja " + cName, "Jangan Suka Tag gua " + cName, "Kamu siapa " + cName + "?", "Ada Perlu apa " + cName + "?","Tenggelamkan tuh yang suka tag pake BOT","Tersummon -_-"]
ret_ = "[Auto Respond] " + random.choice(balas)
name = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata['MENTION'])
mentionees = mention['MENTIONEES']
for mention in mentionees:
if mention['M'] in Bots:
ka.sendText(msg.to,ret_)
ka.kickoutFromGroup(msg.to,[msg.from_])
break
#=====================================================================#
if op.type == 32:
if wait["Protectcancel"] == True:
if op.param2 not in admin:
if op.param2 in Bots:
pass
elif op.param2 in admin:
pass
else:
random.choice(KAC).sendText(op.param1,random.choice(KAC).getContact(op.param2).displayName + " •Cancel Invitation 👀")
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
random.choice(KAC).inviteIntoGroup(op.param1,[op.param3])
wait["blacklist"][op.param2] = True
#==============================================================================#
if msg.toType == 1:
if wait["leaveRoom"] == True:
ka.leaveRoom(msg.to)
#==============================================================================#
if msg.contentType == 16:
url = msg.contentMetadata("line://home/post?userMid="+mid+"&postId="+"new_post")
ka.like(url[25:58], url[66:], likeType=1001)
#==============================================================================#
if op.type == 25:
msg = op.message
if op.type == 25:
msg = op.message
if msg.text in ["Bot on"]:
wait["Bot"] = True
ka.sendText(msg.to,"Bot Sudah on Kembali.")
if op.type == 25:
if wait["Bot"] == True:
msg = op.message
if op.type == 25:
msg = op.message
#==============================================================================#
if msg.contentType == 13:
if msg.from_ in owner:
if wait["steal"] == True:
_name = msg.contentMetadata["displayName"]
copy = msg.contentMetadata["mid"]
groups = ka.getGroup(msg.to)
pending = groups.invitee
targets = []
for s in groups.members:
if _name in s.displayName:
print "[Target] Stealed"
break
else:
targets.append(copy)
if targets == []:
pass
else:
for target in targets:
try:
ka.findAndAddContactsByMid(target)
contact = ka.getContact(target)
cu = ka.channel.getCover(target)
path = str(cu)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
ka.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nMid :\n" + msg.contentMetadata["mid"] + "\n\nBio :\n" + contact.statusMessage)
ka.sendText(msg.to,"Profile Picture " + contact.displayName)
ka.sendImageWithURL(msg.to,image)
ka.sendText(msg.to,"Cover " + contact.displayName)
ka.sendImageWithURL(msg.to,path)
wait["steal"] = False
break
except:
pass
#==============================================================================#
elif wait["wblack"] == True:
if msg.contentMetadata["mid"] in wait["commentBlack"]:
ka.sendText(msg.to,"already")
wait["wblack"] = False
else:
wait["commentBlack"][msg.contentMetadata["mid"]] = True
wait["wblack"] = False
ka.sendText(msg.to,"decided not to comment")
#==============================================================================#
elif wait["dblack"] == True:
if msg.contentMetadata["mid"] in wait["commentBlack"]:
del wait["commentBlack"][msg.contentMetadata["mid"]]
ka.sendText(msg.to,"deleted")
wait["dblack"] = False
else:
wait["dblack"] = False
ka.sendText(msg.to,"It is not in the black list")
#==============================================================================#
elif wait["wblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
ka.sendText(msg.to,"already")
wait["wblacklist"] = False
else:
wait["blacklist"][msg.contentMetadata["mid"]] = True
wait["wblacklist"] = False
ka.sendText(msg.to,"aded")
#==============================================================================#
elif wait["dblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
del wait["blacklist"][msg.contentMetadata["mid"]]
ka.sendText(msg.to,"deleted")
wait["dblacklist"] = False
else:
wait["dblacklist"] = False
ka.sendText(msg.to,"It is not in the black list")
#==============================================================================#
elif wait["contact"] == True:
msg.contentType = 0
ka.sendText(msg.to,msg.contentMetadata["mid"])
if 'displayName' in msg.contentMetadata:
contact = ka.getContact(msg.contentMetadata["mid"])
try:
cu = ka.channel.getCover(msg.contentMetadata["mid"])
except:
cu = ""
ka.sendText(msg.to,"[displayName]:\n" + msg.contentMetadata["displayName"] + "\n[mid]:\n" + msg.contentMetadata["mid"] + "\n[statusMessage]:\n" + contact.statusMessage + "\n[pictureStatus]:\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n[coverURL]:\n" + str(cu))
else:
contact = ka.getContact(msg.contentMetadata["mid"])
try:
cu = ka.channel.getCover(msg.contentMetadata["mid"])
except:
cu = ""
ka.sendText(msg.to,"[displayName]:\n" + contact.displayName + "\n[mid]:\n" + msg.contentMetadata["mid"] + "\n[statusMessage]:\n" + contact.statusMessage + "\n[pictureStatus]:\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n[coverURL]:\n" + str(cu))
elif msg.contentType == 16:
if wait["timeline"] == True:
msg.contentType = 0
if wait["lang"] == "JP":
msg.text = "🔼POST link🔼 URL⤵️\n" + msg.contentMetadata["postEndUrl"]
else:
msg.text = "URL→\n" + msg.contentMetadata["postEndUrl"]
ka.sendText(msg.to,msg.text)
elif msg.text is None:
return
#==============================================================================#
elif msg.text in ["Key","Staff help","help","Help"]:
ka.sendText(msg.to,helpMessage)
elif msg.text in ["Tome1","help creator","Man:creator"]:
ka.sendText(msg.to,creatorMessage)
elif msg.text in ["Tome2","help self","Man:selfbot"]:
ka.sendText(msg.to,publikMessage)
elif msg.text in ["Tome3","Man:set","Man:setting"]:
ka.sendText(msg.to,setMessage)
elif msg.text in ["Tome4","Media","Man:media"]:
ka.sendText(msg.to,mediaMessage)
#==============================================================================#
elif msg.text == "Ginfo":
if msg.toType == 2:
ginfo = ka.getGroup(msg.to)
try:
gCreator = ginfo.creator.displayName
except:
gCreator = "Error"
if wait["lang"] == "JP":
if ginfo.invitee is None:
sinvitee = "0"
else:
sinvitee = str(len(ginfo.invitee))
if ginfo.preventJoinByTicket == True:
u = "Close"
else:
u = "Open"
ka.sendText(msg.to,"[Group name]\n" + str(ginfo.name) + "\n\n[Gid]\n" + msg.to + "\n\n[Group creator]\n" + gCreator + "\n\n[Profile status]\nhttp://dl.profile.line.naver.jp/" + ginfo.pictureStatus + "\n\n•Members group : " + str(len(ginfo.members)) + " members\n•MemberInvite : " + sinvitee + " people\n•URL group : " + u + "\n•by : SELFBOT_MAN_PROTECT")
else:
ka.sendText(msg.to,"[group name]\n" + str(ginfo.name) + "\n[gid]\n" + msg.to + "\n[group creator]\n" + gCreator + "\n[profile status]\nhttp://dl.profile.line.naver.jp/" + ginfo.pictureStatus)
else:
if wait["lang"] == "JP":
ka.sendText(msg.to,"Can not be used outside the group")
else:
ka.sendText(msg.to,"Not for use less than group")
elif msg.text is None:
return
#==============================================================================#
elif msg.text in ["Creator","Owner"]:
msg.contentType = 13
msg.contentMetadata = {'mid': 'ua0a82f37270408d4e63b0b1fbb0e4c7f'}
ka.sendMessage(msg)
#==============================================================================#
elif msg.text in ["@1","@2"]:
msg.contentType = 13
ka.sendMessage(msg.to,"ปรึกษาเรื่องบอท ทักได้คับ\n☞ เปิดสอนเขียนบอท Selfbot กันรัน\n☞ รับทำเชลบอท ในราคาเบาๆ Selfbot⤵️\n🔹 ฟังชั่นบอท 🔹\n -0- เช็คสมาชิกอ่านกลุ่มได้\n -1- @แท๊กสมาชิกได้ทั้งกลุ่ม\n -2- มีข้อความต้อนรับสมาชิก เข้า-ออก (Auto)\n -3- รายงานสมาชิกที่ยุ่งเกี่ยวกับระบบกลุ่ม (รายงานข้อมูล)\n -4- มีลูกเล่นหลากหลายและยังแปลภาษาได้ด้วย \n4.1 (ชุด-Media) \n4.2 (ชุด-Steal) \n4.3 (ชุด-Hack) \n4.4 (ชุด-Translator)\n\n☞สำหรับคนที่:มีอริเยอะ ช่วยป้องกัน 2มาตฐาน\n - (ระบบกันรัน : ยกเลิกรันออโต้)\n - (ล้างรัน : ลงคำสั่งเพื่อยกเลิกกลุ่มรัน Auto)\n - และยังป้องกันการดึงแชทรวม (Virus chat) การดึงเข้าแชทรวมด้วยไวรัส แชท,ไวรัส จะถูกยกเลิกการดึงอัตโนมัติ\n\nหมดห่วงทุกการเกรียน สนใจเรียนวิชาหรือสั่งทำ เปิดเช่า⤵️ สอบถามรายละเอียดเพิ่มเติม.. Link⤵️\n🆔line.me/ti/p/~tomebotline \n\nปล. สำหรับคนที่อยากทำชุดบอท(Protect)..ไว้ป้องกันกลุ่ม\n✅ลูกค้าที่ต้องการทำบอท(kicker)เพิ่ม ตัวล่ะ 50บาท\nTHAILAND : creator & admin bot\nName creator : SELFBOT MAN-PC ✧꧁ℳѦれ꧂✧\nprotect & media @2018")
#==============================================================================#
elif "Admin add @" in msg.text:
if msg.from_ in owner:
print "[Command]Staff add executing"
_name = msg.text.replace("Admin add @","")
_nametarget = _name.rstrip(' ')
gs = ka.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
random.choice(KAC).sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
ka.findAndAddContactsByMid(target)
kb.findAndAddContactsByMid(target)
kc.findAndAddContactsByMid(target)
kd.findAndAddContactsByMid(target)
ke.findAndAddContactsByMid(target)
kf.findAndAddContactsByMid(target)
kg.findAndAddContactsByMid(target)
kh.findAndAddContactsByMid(target)
ki.findAndAddContactsByMid(target)
kj.findAndAddContactsByMid(target)
admin.append(target)
ka.sendText(msg.to,"👑Admin Already Added Boss Man👑")
except:
pass
print "[Command]Admin add executed"
else:
ka.sendText(msg.to,"You Are Not My Boss !!!")
ka.sendText(msg.to,"Command Denied")
#==============================================================================#
elif "Owner add @" in msg.text:
if msg.from_ in owner:
print "[Command]Owner add executing"
_name = msg.text.replace("Owner add @","")
_nametarget = _name.rstrip(' ')
gs = ka.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
random.choice(KAC).sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
ka.findAndAddContactsByMid(target)
# kb.findAndAddContactsByMid(target)
# kc.findAndAddContactsByMid(target)
# kd.findAndAddContactsByMid(target)
# ke.findAndAddContactsByMid(target)
# kf.findAndAddContactsByMid(target)
# kg.findAndAddContactsByMid(target)
# kh.findAndAddContactsByMid(target)
# ki.findAndAddContactsByMid(target)
# kj.findAndAddContactsByMid(target)
owner.append(target)
ka.sendText(msg.to,"👑Owner Already Added Boss Man👑")
except:
pass
print "[Command]Owner add executed"
else:
ka.sendText(msg.to,"You Are Not My Boss !!!")
ka.sendText(msg.to,"Command Denied")
#==============================================================================#
elif "Admin remove @" in msg.text:
if msg.from_ in owner:
print "[Command]Staff remove executing"
_name = msg.text.replace("Admin remove @","")
_nametarget = _name.rstrip(' ')
gs = ka.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
random.choice(KAC).sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
admin.remove(target)
ka.sendText(msg.to,"Admin Deleted 👀")
except:
pass
print "[Command]Admin remove executed"
else:
ka.sendText(msg.to,"You Are Not My Boss !!!")
ka.sendText(msg.to,"Command Denied")
#==============================================================================#
elif "Owner remove @" in msg.text:
if msg.from_ in owner:
print "[Command]Owner remove executing"
_name = msg.text.replace("Owner remove @","")
_nametarget = _name.rstrip(' ')
gs = ka.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
random.choice(KAC).sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
owner.remove(target)
ka.sendText(msg.to,"Owner Deleted 👀")
except:
pass
print "[Command]Owner remove executed"
else:
ka.sendText(msg.to,"You Are Not My Boss !!!")
ka.sendText(msg.to,"Command Denied")
#==============================================================================#
elif msg.text in ["Adminlist","Stafflist"]:
if admin == []:
ka.sendText(msg.to,"The stafflist is empty")
else:
ka.sendText(msg.to,"Tunggu...")
mc = "👑 Admin selfbot-man 👑\n𖤓≛≛≛≛≛≛≛≛≛≛≛≛≛≛𖤓\n"
for mi_d in admin:
mc += "[🔘] " + ka.getContact(mi_d).displayName + "🔏\n"
ka.sendText(msg.to,mc)
print "[Command]Stafflist executed"
#==============================================================================#
elif msg.text in ["Ownerlist","ownerlist"]:
if owner == []:
ka.sendText(msg.to,"The Owner is empty")
else:
ka.sendText(msg.to,"Tunggu...")
mc = "👑 Owner selfbot-man 👑\n𖤓≛≛≛≛≛≛≛≛≛≛≛≛≛≛𖤓\n"
for mi_d in owner:
mc += "[🔘] " + ka.getContact(mi_d).displayName + "🔏\n"
ka.sendText(msg.to,mc)
print "[Command]Ownerlist executed"
#==============================================================================#
elif msg.contentType == 16:
if wait["Timeline"] == True:
msg.contentType = 0
msg.text = "🔘POST📬\n💌URL-timeline⤵️\n" + msg.contentMetadata["postEndUrl"]
random.choice(KAC).sendText(msg.to,msg.text)
#==============================================================================#
elif msg.text in ["List group"]:
gid = ka.getGroupIdsJoined()
h = ""
jml = 0
for i in gid:
gn = ka.getGroup(i).name
h += "╠ [ %s ]\n" % (gn)
jml += 1
ka.sendText(msg.to,"╔══[ List Group ]\n"+ h +"╚══[ Total Group ] "+str(jml))
#==============================================================================#
elif "/invitemeto: " in msg.text:
if msg.from_ in owner:
gid = msg.text.replace("/invitemeto: ","")
if gid == "":
ka.sendText(msg.to,"Invalid group id")
else:
try:
ka.findAndAddContactsByMid(msg.from_)
ka.inviteIntoGroup(gid,[msg.from_])
except:
try:
kb.findAndAddContactsByMid(msg.from_)
kb.inviteIntoGroup(gid,[msg.from_])
except:
try:
kc.findAndAddContactsByMid(msg.from_)
kc.inviteIntoGroup(gid,[msg.from_])
except:
try:
kd.findAndAddContactsByMid(msg.from_)
kd.inviteIntoGroup(gid,[msg.from_])
except:
try:
ke.findAndAddContactsByMid(msg.from_)
ke.inviteIntoGroup(gid,[msg.from_])
except:
ka.sendText(msg.to,"Mungkin kami tidak di dalaam grup itu")
#==============================================================================#
elif msg.text in ["Bot out","Leave all group"]:
if msg.from_ in owner:
gid = ka.getGroupIdsJoined()
gid = kb.getGroupIdsJoined()
gid = kc.getGroupIdsJoined()
gid = kd.getGroupIdsJoined()
gid = ke.getGroupIdsJoined()
for i in gid:
ke.leaveGroup(i)
kd.leaveGroup(i)
kc.leaveGroup(i)
kb.leaveGroup(i)
ka.leaveGroup(i)
if wait["lang"] == "JP":
ka.sendText(msg.to,"Sayonara")
else:
ka.sendText(msg.to,"He declined all invitations")
#==============================================================================#
elif msg.text in ["Notifed on","เปิดแจ้งเตือน","M on"]:
if msg.from_ in admin:
if wait["Notifed"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"All Notifed On\n\nเปิดเเจ้งเเตือนของคุณเเล้ว")
else:
ka.sendText(msg.to,"Done\n\nเปิดเเจ้งเเตือนของคุณเเล้ว")
else:
wait["Notifed"] = True
if wait["lang"] == "JP":
ka.sendText(msg.to,"All Notifed On\n\nเปิดเเจ้งเเตือนของคุณเเล้ว")
else:
ka.sendText(msg.to,"Done\n\nเปิดเเจ้งเเตือนของคุณเเล้ว")
elif msg.text in ["Notifed off","ปิดแจ้งเตือน","M off"]:
if msg.from_ in admin:
if wait["Notifed"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"All Notifed Off\n\nปิดเเจ้งเเตือนของคุณเเล้ว")
else:
ka.sendText(msg.to,"Done\n\nปิดเเจ้งเเตือนของคุณเเล้ว")
else:
wait["Notifed"] = False
if wait["lang"] == "JP":
ka.sendText(msg.to,"All Notifed Off\n\nปิดเเจ้งเเตือนของคุณเเล้ว")
else:
ka.sendText(msg.to,"Done\n\nปิดเเจ้งเเตือนของคุณเเล้ว")
elif msg.text in ["Notifedbot on","เปิดเเจ้งเตือนบอท","Mbot on"]:
if msg.from_ in admin:
if wait["Notifedbot"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"All bot Notifed On\n\nเปิดเเจ้งเเตือนบอทเเล้ว")
else:
ka.sendText(msg.to,"Done\n\nเปิดเเจ้งเเตือนบอทเเล้ว")
else:
wait["Notifedbot"] = True
if wait["lang"] == "JP":
ka.sendText(msg.to,"All bot Notifed On\n\nเปิดเเจ้งเเตือนบอทเเล้ว")
else:
ka.sendText(msg.to,"Done\n\nเปิดเเจ้งเเตือนบอทเเล้ว")
elif msg.text in ["Notifedbot off","ปิดแจ้งเตือนบอท","Mbot off"]:
if msg.from_ in admin:
if wait["Notifedbot"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"All bot Notifed Off\n\nปิดเเจ้งเเตือนบอทเเล้ว")
else:
ka.sendText(msg.to,"Done\n\nปิดเเจ้งเเตือนบอทเเล้ว")
else:
wait["Notifedbot"] = False
if wait["lang"] == "JP":
ka.sendText(msg.to,"All bot Notifed Off\n\nปิดเเจ้งเเตือนบอทเเล้ว")
else:
ka.sendText(msg.to,"Done\n\nปิดเเจ้งเเตือนบอทเเล้ว")
elif msg.text in ["Like on","เปิด ไลค์"]:
if wait["likeOn"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"เปิดอยู่แล้ว。")
else:
wait["likeOn"] = True
if wait["lang"] == "JP":
ka.sendText(msg.to,"เปิดระบบออโต้ไลค์.👌")
elif msg.text in ["ปิด ไลค์","Like off"]:
if wait["likeOn"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"ปิดอยู่แล้ว")
else:
wait["likeOn"] = False
if wait["lang"] == "JP":
ka.sendText(msg.to,"ปิดระบบออโต้ไลค์.👌")
#========================================
#==================================================================================#
elif msg.text in ["Clear"]:
if msg.from_ in owner:
if msg.toType == 2:
group = ka.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.invitee]
for _mid in gMembMids:
random.choice(KAC).cancelGroupInvitation(msg.to,[_mid])
ka.sendText(msg.to,"I pretended to cancel and canceled.")
#==============================================================================#
elif msg.text in ["Cl","Cancel"]:
if msg.from_ in owner:
if msg.toType == 2:
group = ka.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.invitee]
for _mid in gMembMids:
random.choice(KAC).cancelGroupInvitation(msg.to,[_mid])
ka.sendText(msg.to,"🌐Cancel All Group Invite🌐")
#==============================================================================#
elif msg.text in ["Ourl","Url on"]:
if msg.from_ in admin:
if msg.toType == 2:
X = ka.getGroup(msg.to)
X.preventJoinByTicket = False
ka.updateGroup(X)
ka.sendText(msg.to,"🔘OPEN link-Url")
else:
ka.sendText(msg.to,"Can not be used outside the group")
#==============================================================================#
elif msg.text in ["Curl","Url off"]:
if msg.from_ in admin:
if msg.toType == 2:
X = ka.getGroup(msg.to)
X.preventJoinByTicket = True
ka.updateGroup(X)
ka.sendText(msg.to,"📴CLOSE link-Url")
else:
ka.sendText(msg.to,"Can not be used outside the group")
#==============================================================================#
elif msg.text in ["Cancelinvite on","cancelinvite on"]:
if msg.from_ in owner:
if wait["Protectcancel"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"🔘OPEN/PROTECT Cancel Invite")
else:
ka.sendText(msg.to,"Berhasil mengaktifkan Cancel Invite")
elif msg.text in ["Cancelinvite off","cancelinvite off"]:
if msg.from_ in owner:
if wait["Protectcancel"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"📴CLOSE/PROTECT Cancel Invite")
else:
ka.sendText(msg.to,"Berhasil menonaktifkan Cancel Invite")
elif "Gcancel:" in msg.text:
try:
strnum = msg.text.replace("Gcancel:","")
if strnum == "off":
wait["autoCancel"]["on"] = False
if wait["lang"] == "JP":
ka.sendText(msg.to,"Invitation refused turned off\nTo turn on please specify the number of people and send")
else:
ka.sendText(msg.to,"关了邀请拒绝。要时开请指定人数发送")
else:
num = int(strnum)
wait["autoCancel"]["on"] = True
if wait["lang"] == "JP":
ka.sendText(msg.to,strnum + " The group of people and below decided to automatically refuse invitation")
else:
ka.sendText(msg.to,strnum + "使人以下的小组用自动邀请拒绝")
except:
if wait["lang"] == "JP":
ka.sendText(msg.to,"Value is wrong")
else:
ka.sendText(msg.to,"Bizarre ratings")
#==============================================================================#
elif msg.text in ["Add:on","เปิด เพิ่มเพื่อน","Auto add:on","Add on"]:
if wait["autoAdd"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"Sudah on Bosqu")
else:
ka.sendText(msg.to,"Ok Bosqu")
else:
wait["autoAdd"] = True
if wait["lang"] == "JP":
ka.sendText(msg.to,"Ok Bosqu")
else:
ka.sendText(msg.to,"Sudah on Bosqu")
elif msg.text in ["Add:off","Auto add off","ปิด เพิ่มเพื่อน","Add off"]:
if wait["autoAdd"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"Sudah off Bosqu")
else:
ka.sendText(msg.to,"Ok Bosqu")
else:
wait["autoAdd"] = False
if wait["lang"] == "JP":
ka.sendText(msg.to,"Ok Bosqu")
else:
ka.sendText(msg.to,"Sudah off Bosqu")
#==============================================================================#
elif "Message set:" in msg.text:
wait["message"] = msg.text.replace("Message set:","")
ka.sendText(msg.to,"message changed\n\n"+ datetime.today().strftime('%H:%M:%S'))
elif "Add message: " in msg.text:
wait["message"] = msg.text.replace("Add message: ","")
if wait["lang"] == "JP":
ka.sendText(msg.to,"message changed\n\n"+ datetime.today().strftime('%H:%M:%S'))
else:
ka.sendText(msg.to,"done。\n\n"+ datetime.today().strftime('%H:%M:%S'))
elif msg.text in ["Message","Com"]:
if wait["lang"] == "JP":
ka.sendText(msg.to,"message change to\n\n" + wait["message"])
else:
ka.sendText(msg.to,"The automatic appending information is set as follows。\n\n" + wait["message"])
elif "Coms set:" in msg.text:
c = msg.text.replace("คอมเม้น:","Coms set:","")
if c in [""," ","\n",None]:
ka.sendText(msg.to,"String that can not be changed")
else:
wait["comment"] = c
ka.sendText(msg.to,"changed\n\n" + c)
elif "Add comment: " in msg.text:
c = msg.text.replace("Add comment: ","")
if c in [""," ","\n",None]:
ka.sendText(msg.to,"String that can not be changed")
else:
wait["comment"] = c
ka.sendText(msg.to,"changed\n\n" + c)
elif msg.text in ["เปิด คอมเม้น","Com on","Comment:on"]:
if wait["commentOn"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"Done")
else:
ka.sendText(msg.to,"Already on")
else:
wait["commentOn"] = True
if wait["lang"] == "JP":
ka.sendText(msg.to,"Done")
else:
ka.sendText(msg.to,"Already on")
elif msg.text in ["ปิด คอมเม้น","Com off","Comment:off"]:
if wait["commentOn"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"Done")
else:
ka.sendText(msg.to,"Already off")
else:
wait["commentOn"] = False
if wait["lang"] == "JP":
ka.sendText(msg.to,"Done")
else:
ka.sendText(msg.to,"Already off")
elif msg.text in ["Comment","Coms"]:
ka.sendText(msg.to,"message changed to\n\n" + str(wait["comment"]))
elif msg.text in ["HHX1","Hhx1"]:
ka.sendText(msg.to,"[เช็คข้อความต้อนรับของคุณ]\n\n" + str(wait["acomment"]))
elif msg.text in ["HHX2","Hhx2"]:
ka.sendText(msg.to,"[เช็คข้อความกล่าวถึงคนออกจากกลุ่ม]\n\n" + str(wait["bcomment"]))
elif msg.text in ["HHX3","Hhx3"]:
ka.sendText(msg.to,"[เช็คข้อความกล่าวถึงคนลบสมาชิก]\n\n" + str(wait["ccomment"]))
elif "Hhx1:" in msg.text:
c = msg.text.replace("Hhx1:","")
if c in [""," ","\n",None]:
ka.sendText(msg.to,"เกิดข้อผิดพลาด..!!")
else:
wait["acomment"] = c
ka.sendText(msg.to,"➠ ตั้งค่าข้อความต้อนรับ👌\n\n" + c)
elif "Hhx2:" in msg.text:
c = msg.text.replace("Hhx2:","")
if c in [""," ","\n",None]:
ka.sendText(msg.to,"เกิดข้อผิดพลาด..!!")
else:
wait["bcomment"] = c
ka.sendText(msg.to,"➠ ตั้งค่าข้อความกล่าวถึงคนออกจากกลุ่ม👌\n\n" + c)
elif "Hhx3:" in msg.text:
c = msg.text.replace("Hhx3:","")
if c in [""," ","\n",None]:
ka.sendText(msg.to,"เกิดข้อผิดพลาด..!!")
else:
wait["ccomment"] = c
ka.sendText(msg.to,"➠ ตั้งค่าข้อความกล่าวถึงคนลบสมาชิก👌\n\n" + c)
elif msg.text in ["Hhx1 on"]:
if wait["acommentOn"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ เปิดข้อความต้อนรับเเล้ว👌")
else:
ka.sendText(msg.to,"Already on")
else:
wait["acommentOn"] = True
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ เปิดข้อความต้อนรับเเล้ว👌")
else:
ka.sendText(msg.to,"Already on")
elif msg.text in ["Hhx2 on"]:
if wait["bcommentOn"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ เปิดข้อความกล่าวถึงคนออกจากกลุ่ม👌")
else:
ka.sendText(msg.to,"Already on")
else:
wait["bcommentOn"] = True
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ เปิดข้อความกล่าวถึงคนออกจากกลุ่ม👌")
else:
ka.sendText(msg.to,"Already on")
elif msg.text in ["Hhx3 on"]:
if wait["ccommentOn"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ เปิดข้อความกล่าวถึงคนลบสมาชิก👌")
else:
ka.sendText(msg.to,"Already on")
else:
wait["ccommentOn"] = True
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ เปิดข้อความกล่าวถึงคนลบสมาชิก👌")
else:
ka.sendText(msg.to,"Already on")
elif msg.text in ["Hhx1 off"]:
if wait["acommentOn"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ ปิดข้อความต้อนรับเเล้ว👌")
else:
ka.sendText(msg.to,"Already off")
else:
wait["acommentOn"] = False
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ ปิดข้อความต้อนรับเเล้ว👌")
else:
ka.sendText(msg.to,"Already off")
elif msg.text in ["Hhx2 off"]:
if wait["bcommentOn"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ ปิดข้อความกล่าวถึงคนออกจากกลุ่ม👌")
else:
ka.sendText(msg.to,"Already off")
else:
wait["bcommentOn"] = False
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ ปิดข้อความกล่าวถึงคนออกจากกลุ่ม👌")
else:
ka.sendText(msg.to,"Already off")
elif msg.text in ["Hhx3 off"]:
if wait["ccommentOn"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ ปิดข้อความกล่าวถึงคนลบสมาชิก👌")
else:
ka.sendText(msg.to,"Already off")
else:
wait["ccommentOn"] = False
if wait["lang"] == "JP":
ka.sendText(msg.to,"➠ ปิดข้อความกล่าวถึงคนลบสมาชิก👌")
else:
ka.sendText(msg.to,"Already off")
#==================================================================================#
elif msg.text in ["Purge on","purge on","Purge: on","purge: on"]:
if msg.from_ in admin:
if wait["Protectjoin"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"Berhasil mengaktifkan High Protect")
else:
ka.sendText(msg.to,"Berhasil mengaktifkan High Protect")
elif msg.text in ["Purge off","purge off","Purge: off","purge: off"]:
if msg.from_ in admin:
if wait["Protectjoin"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"Berhasil menonaktifkan High Protect")
else:
ka.sendText(msg.to,"Berhasil menonaktifkan High Protect")
#==============================================================================#
elif msg.text in ["Cancel on","cancel on","ปิดเชิญ"]:
if msg.from_ in owner:
if wait["Protectcancl"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"🔘OPEN/PROTECT ระบบป้องกันเชิญถูกเปิดใช้งาน")
else:
ka.sendText(msg.to,"Berhasil mengaktifkan Cancel")
elif msg.text in ["Cancel off","cancel off","เปิดเชิญ"]:
if msg.from_ in owner:
if wait["Protectcancl"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"📴CLOSE/PROTECT ระบบป้องกันเชิญถูกปิดใช้งาน")
else:
ka.sendText(msg.to,"Berhasil menonaktifkan Cancel")
#==============================================================================#
elif msg.text in ["Qr on","qr on","เปิดป้องกันลิงก์","ป้องกันลิ้ง"]:
if msg.from_ in owner:
if wait["Protectgr"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"🔘OPEN/PROTECT URL:QR เปิดระบบป้องกันลิงก์กลุ่ม")
else:
ka.sendText(msg.to,"Berhasil mengaktifkan Protect QR")
elif msg.text in ["Qr off","qr off","ปิดป้องกันลิงก์"]:
if msg.from_ in owner:
if wait["Protectgr"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"📴CLOSE/PROTECT URL:QR ปิดระบบป้องกันลิงก์กลุ่ม")
else:
ka.sendText(msg.to,"Berhasil menonaktifkan Protect QR")
#==============================================================================#
elif msg.text in ["Contact On","Contact on","contact on"]:
if msg.from_ in owner:
if wait["contact"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"🔘OPEN / Info Contact")
else:
ka.sendText(msg.to,"Berhasil mengaktifkan Info Contact")
elif msg.text in ["Contact Off","Contact off","contact off"]:
if msg.from_ in owner:
if wait["contact"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"📴CLOSE / Info Contact")
else:
ka.sendText(msg.to,"Berhasil menonaktifkan Info Contact")
#==============================================================================#
elif msg.text in ["Join on","Autojoin on","เปิดเข้ากลุ่ม"]:
if msg.from_ in owner:
if wait["autoJoin"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"🔘OPEN Auto Join เข้าร่วมกลุ่มเชิญออโต้")
else:
ka.sendText(msg.to,"Berhasil mengaktifkan Auto Join")
elif msg.text in ["Join off","Autojoin off","ปิดเข้ากลุ่ม"]:
if msg.from_ in owner:
if wait["autoJoin"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"📴CLOSE Auto Join ปิดเข้าร่วมกลุ่มเชิญ")
else:
ka.sendText(msg.to,"Berhasil menonaktifkan Auto Join")
#==============================================================================#
elif msg.text in ["Leave on","Autoleave on"]:
if msg.from_ in owner:
if wait["leaveRoom"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"🔘OPEN Auto Leave เปิดป้องกันการดึงแชทรวม")
else:
ka.sendText(msg.to,"Berhasil mengaktifkan Auto Leave")
elif msg.text in ["Leave off","Autoleave off"]:
if msg.from_ in owner:
if wait["leaveRoom"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"📴CLOSE Auto Leave ปิดป้องกันการดึงแชทรวม")
else:
ka.sendText(msg.to,"Berhasil menonaktifkan Auto Leave")
#==============================================================================#
elif msg.text in ["Share on","Share:on"]:
if msg.from_ in owner:
if wait["timeline"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"🔘OPEN Mode Share")
else:
ka.sendText(msg.to,"Berhasil mengaktifkan Mode Share")
elif msg.text in ["Share off","Share:off"]:
if msg.from_ in owner:
if wait["timeline"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"📴CLOSE Mode Share")
else:
ka.sendText(msg.to,"Berhasil menonaktifkan Mode Share")
#==============================================================================#
elif msg.text in ["Sambutan on","Sam:on","เปิดต้อนรับ"]:
if msg.from_ in owner:
if wait["Sambutan"] == True:
if wait["lang"] == "JP":
ka.sendText(msg.to,"🔘OPEN เปิดใช้งานต้อนรับ,บอทตอบโต้")
elif msg.text in ["Sambutan off","Sam:off","ปิดต้อนรับ"]:
if msg.from_ in owner:
if wait["Sambutan"] == False:
if wait["lang"] == "JP":
ka.sendText(msg.to,"📴CLOSE ปิดใช้งานต้อนรับ,บอทตอบโต้")
#==============================================================================#
elif msg.text in ["Simisimi on","Simisimi:on","Chatbot:on"]:
settings["simiSimi"][msg.to] = True
wait["Simi"] = True
ka.sendText(msg.to,"🔘OPEN เปิดการสนทนาบอท")
elif msg.text in ["Simisimi off","Simisimi:off","Chatbot:off"]:
settings["simiSimi"][msg.to] = False
wait["Simi"] = False
ka.sendText(msg.to,"📴CLOSE ปิดการสนทนาบอท")
#==============================================================================#
elif msg.text in ["เปิด อ่าน","Read on","Read:on"]:
wait['alwayRead'] = True
ka.sendText(msg.to,"เปิดอ่านข้อความอัตโนมัติ.👌")
elif msg.text in ["ปิด อ่าน","Read off","Read:off"]:
wait['alwayRead'] = False
ka.sendText(msg.to,"ปิดอ่านข้อความอัตโนมัติ.👌")
elif msg.text in ["Tag on","Autorespon:on","Respon on","Respon:on"]:
wait["detectMention"] = True
ka.sendText(msg.to,"Auto Respon ON")
elif msg.text in ["Tag off","Autorespon:off","Respon off","Respon:off"]:
wait["detectMention"] = False
ka.sendText(msg.to,"Auto Respon OFF")
elif msg.text in ["Tag1","Tag1"]:
ka.sendText(msg.to,"ข้อความแทคล่าสุดคือ\n\n" + str(wait["tag1"]))
elif msg.text in ["Tag2","Tag2"]:
ka.sendText(msg.to,"ข้อความแทคล่าสุดคือ\n\n" + str(wait["tag2"]))
elif msg.text in ["Tag1:"]:
wait["tag1"] = msg.text.replace("Tag1: ","")
ka.sendText(msg.to,"ข้อความแทคล่าสุดคือ")
elif msg.text in ["Tag2:"]:
wait["tag2"] = msg.text.replace("Tag2: ","")
ka.sendText(msg.to,"ข้อความแทคล่าสุดคือ")
elif msg.text in ["Kicktag on","Autokick:on","Responkick on","Responkick:on"]:
wait["kickMention"] = True
ka.sendText(msg.to,"Auto Kick ON")
elif msg.text in ["Kicktag off","Autokick:off","Responkick off","Responkick:off"]:
wait["kickMention"] = False
ka.sendText(msg.to,"Auto Kick OFF")
#============================================================================#
elif "Spam " in msg.text:
if msg.from_ in admin:
txt = msg.text.split(" ")
jmlh = int(txt[2])
teks = msg.text.replace("Spam "+str(txt[1])+" "+str(jmlh)+ " ","")
tulisan = jmlh * (teks+"\n")
#Keke cantik <3
if txt[1] == "on":
if jmlh <= 10000:
for x in range(jmlh):
ka.sendText(msg.to, teks)
else:
ka.sendText(msg.to, "Out of range! ")
elif txt[1] == "off":
if jmlh <= 10000:
ka.sendText(msg.to, tulisan)
else:
ka.sendText(msg.to, "Out of range! ")
#====================================================================#
elif "Mid @" in msg.text:
_name = msg.text.replace("Mid @","")
_nametarget = _name.rstrip(' ')
gs = ka.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
ka.sendText(msg.to, g.mid)
else:
pass
#====================================================================#
elif "Sider on" in msg.text:
try:
del cctv['point'][msg.to]
del cctv['sidermem'][msg.to]
del cctv['cyduk'][msg.to]
except:
pass
cctv['point'][msg.to] = msg.id
cctv['sidermem'][msg.to] = ""
cctv['cyduk'][msg.to]=True
wait["Sider"] = True
ka.sendText(msg.to,"Berhasil mengaktifkan Sider point")
elif "Sider off" in msg.text:
if msg.to in cctv['point']:
cctv['cyduk'][msg.to]=False
wait["Sider"] = False
ka.sendText(msg.to, "Berhasil menonaktifkan Sider point")
else:
ka.sendText(msg.to, "Setting Masih Mode Off\nMohon Maaf")
#--------------------------------
elif msg.text in ["Allprotect on","เปิดชุดป้องกัน"]:
if msg.from_ in admin:
wait["Protectcancel"] = True
wait["Protectcancl"] = True
wait["Protectjoin"] = True
wait["Protectgr"] = True
wait["Protection"] = True
ka.sendText(msg.to,"🔘OPEN/PROTECT ระบบป้องกันถูกเปิดใช้งาน")
else:
ka.sendText(msg.to,"TEAM STAFF.BOT MAN ON")
if msg.from_ in admin:
wait["Protectcancel"] = False
wait["Protectcancl"] = False
wait["Protectjoin"] = False
wait["Protectgr"] = False
wait["Protection"] = False
ka.sendText(msg.to,"📴CLOSE/PROTECT ระบบป้องกันถูกเปิดใช้งาน")
else:
ka.sendText(msg.to,"TEAM STAFFBOT MAN OFF PROTECTION")
#========================[ P R O T E C T I O N : A L L ]========================#
elif msg.text in ["ProtectALL on","เปิดระบบป้องกัน"]:
if msg.from_ in admin:
wait["Protectcancel"] = True
wait["Protectcancl"] = True
wait["Protectjoin"] = True
wait["Protectgr"] = True
wait["Protection"] = True
ka.sendText(msg.to,"🔘OPEN/PROTECT ระบบป้องกันถูกเปิดใช้งาน")
else:
ka.sendText(msg.to,"TEAM STAFF.BOT MAN ON")
elif msg.text in ["ProtectALL off","ปิดระบบป้องกัน"]:
if msg.from_ in admin:
wait["Protectcancel"] = False
wait["Protectcancl"] = False
wait["Protectjoin"] = False
wait["Protectgr"] = False
wait["Protection"] = False
ka.sendText(msg.to,"📴CLOSE/PROTECT ระบบป้องกันถูกเปิดใช้งาน")
else:
ka.sendText(msg.to,"TEAM STAFFBOT MAN OFF PROTECTION")
#==============================[ S E T : T I N G ]==============================#
elif msg.text in ["Allprotect on","เปิดระบบป้องกัน"]:
if msg.from_ in admin:
wait["contact"] = True
wait["Auvv "] = True
wait["Protectjoin"] = True
wait["Protectgr"] = True
wait["Protection"] = True
ka.sendText(msg.to,"🔘OPEN/PROTECT ระบบป้องกันถูกเปิดใช้งาน")
else:
ka.sendText(msg.to,"TEAM STAFF.BOT MAN ON")
elif msg.text in ["Allprotect oft","ปิดระบบป้องกัน"]:
if msg.from_ in admin:
wait["Protectcancel"] = False
wait["Protectcancl"] = False
wait["Protectjoin"] = False
wait["Protectgr"] = False
wait["Protection"] = False
ka.sendText(msg.to,"📴CLOSE/PROTECT ระบบป้องกันถูกเปิดใช้งาน")
else:
ka.sendText(msg.to,"TEAM STAFFBOT MAN OFF PROTECTION")
#==============================================================================#
elif msg.text in ["เชคค่า","เช็คค่า","Set"]:
if msg.from_ in admin:
print "Setting pick up..."
md = "╭══════════════════╮\n║─┅═✥ᴛᴇᴀᴍᵀᴴᴬᴵᴸᴬᴺᴰʙᴏᴛLɪɴᴇ✥═┅─\n║ •─✯͜͡✯TOME★BOTLINE✯͜͡✯─• \n╰══════════════════╯\n╭═════════════════╮\n"
if wait["likeOn"] == True: md+="╠❂➣ ออโต้ไลค์ : ✔ เปิดอยู่\n"
else:md+="╠❂➣ ออโต้ไลค์ : ❌ ปิดแล้ว\n"
if wait["detectMention"] == True: md+="╠❂➣ ตอบแทค : ✔ เปิดแล้ว\n"
else:md+="╠❂➣ ตอบแทค : ❌ ปิดแล้ว\n"
if wait["kickMention"] == True: md+="╠❂➣ ออโต้เตะ: ✔ เปิดอยู่\n"
else:md+="╠❂➣ ออโต้เตะ : ❌ ปิดอยู่\n"
if wait["Notifed"] == True: md+="╠❂➣ Notifed : ✔ เปิดอยู่\n"
else:md+="╠❂➣ Notifed : ❌ ปิดอยู่\n"
if wait["Notifedbot"] == True: md+="╠❂➣ Notifedbot : ✔ เปิดอยู่\n"
else:md+="╠❂➣ Notifedbot : ❌ ปิดอยู่\n"
if wait["acommentOn"] == True: md+="╠❂➣ Hhx1 : ✔ เปิดอยู่\n"
else:md+="╠❂➣ Hhx1 : ❌ ปิดอยู่\n"
if wait["bcommentOn"] == True: md+="╠❂➣ Hhx2 : ✔ เปิดอยู่\n"
else:md+="╠❂➣ Hhx2 : ❌ ปิดอยู่\n"
if wait["ccommentOn"] == True: md+="╠❂➣ Hhx3 : ✔ เปิดอยู่\n"
else:md+="╠❂➣ Hhx3 : ❌ ปิดอยู่\n"
if wait["autoCancel"]["on"] == True:md+="╠❂➣ Group cancel :" + str(wait["autoCancel"]["members"]) + " ห้องที่เปิดใช้งาน\n"
else: md+="╠❂➣ Group cancel : ❌ ปิดอยู่\n"
if wait["autoAdd"] == True: md+="╠❂➣ ออโต้ เพิ่มเพื่อน : ✔ เปิดอยู่\n"
else:md+="╠❂➣ ออโต้ เพิ่มเพื่อน : ❌ ปิดอยู่\n"
if wait["Protectgr"] == True: md+="╠❂➣🔒Protect QR Enable\n"
else: md+="╠❂➣🔓Protect QR Disable\n"
if wait["Protectcancl"] == True: md+="╠❂➣🔒Protect Invite Enable\n"
else: md+="╠❂➣🔓Protect Invite Disable\n"
if wait["Protectcancel"] == True: md+="╠❂➣🔒Protect Cancel Enable\n"
else: md+="╠❂➣🔓Protect Cancel Disable\n"
if wait["Protectjoin"] == True: md+="╠❂➣🔒High protect Enable\n"
else: md+="╠❂➣🔓High protect Disable\n"
if wait["contact"] == True: md+="╠❂➣🔘Contact ✔\n"
else: md+="╠❂➣🔘Contact ✖\n"
if wait["autoJoin"] == True: md+="╠❂➣🔘Auto Join ✔\n"
else: md+="╠❂���🔘Auto Join ✖\n"
if wait["leaveRoom"] == True: md+="╠❂➣🔘Auto Leave ✔\n"
else: md+="╠❂➣🔘Auto Leave ✖\n"
if wait["timeline"] == True: md+="╠❂➣🔘Share ✔\n"
else: md+="╠❂➣🔘Share ✖\n"
if wait["Sambutan"] == True: md+="╠❂➣🔘Sambutan ✔\n"
else: md+="╠❂➣🔘Sambutan ✖\n"
ka.sendText(msg.to,md + "╰══════════════════╯")
msg.contentType = 13
msg.contentMetadata = {'mid': admsa}
ka.sendMessage(msg)
# else:
# ka.sendText(msg.to,"This Command Only For Admin & Owner")
#==============================================================================#
elif msg.text in ["Tagall","Tag all","Mention all"]:
if msg.from_ in owner:
group = ka.getGroup(msg.to)
nama = [contact.mid for contact in group.members]
cb = ""
cb2 = ""
strt = int(0)
akh = int(0)
for md in nama:
akh = akh + int(6)
cb += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M":"""+json.dumps(md)+"},"""
strt = strt + int(7)
akh = akh + 1
cb2 += "@nrik \n"
cb = (cb[:int(len(cb)-1)])
msg.contentType = 0
msg.text = cb2
msg.contentMetadata ={'MENTION':'{"MENTIONEES":['+cb+']}','EMTVER':'4'}
try:
ka.sendMessage(msg)
except Exception as error:
print error
#==============================================================================#
elif "แทค" == msg.text.lower():
group = ka.getGroup(msg.to)
nama = [contact.mid for contact in group.members]
nm1, nm2, nm3, nm4, nm5, jml = [], [], [], [], [], len(nama)
if jml <= 100:
summon(msg.to, nama)
if jml > 100 and jml < 200:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, len(nama)-1):
nm2 += [nama[j]]
summon(msg.to, nm2)
if jml > 200 and jml < 500:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, 199):
nm2 += [nama[j]]
summon(msg.to, nm2)
for k in range(200, 299):
nm3 += [nama[k]]
summon(msg.to, nm3)
for l in range(300, 399):
nm4 += [nama[l]]
summon(msg.to, nm4)
for m in range(400, len(nama)-1):
nm5 += [nama[m]]
summon(msg.to, nm5)
if jml > 500:
print "Terlalu Banyak Men 500+"
cnt = Message()
cnt.text = "[SELF BOT\n[By.☬ധู้さန້ণق↔ധഖาໄฟ☬]:\n" + str(jml) + " Members"
cnt.to = msg.to
ka.sendMessage(cnt)
#==================================================================================#
elif msg.text == "Lurking on":
if msg.from_ in owner:
tz = pytz.timezone("Asia/Jakarta")
timeNow = datetime.now(tz=tz)
day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]
hr = timeNow.strftime("%A")
bln = timeNow.strftime("%m")
for i in range(len(day)):
if hr == day[i]: hasil = hari[i]
for k in range(0, len(bulan)):
if bln == str(k): bln = bulan[k-1]
readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]"
if msg.to in read['readPoint']:
try:
del read['readPoint'][msg.to]
del read['readMember'][msg.to]
del read['readTime'][msg.to]
except:
pass
read['readPoint'][msg.to] = msg.id
read['readMember'][msg.to] = ""
read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S')
read['ROM'][msg.to] = {}
with open('sider.json', 'w') as fp:
json.dump(read, fp, sort_keys=True, indent=4)
ka.sendText(msg.to,"Lurking already on")
else:
try:
del read['readPoint'][msg.to]
del read['readMember'][msg.to]
del read['readTime'][msg.to]
except:
pass
read['readPoint'][msg.to] = msg.id
read['readMember'][msg.to] = ""
read['readTime'][msg.to] = datetime.now().strftime('%H:%M:%S')
read['ROM'][msg.to] = {}
with open('sider.json', 'w') as fp:
json.dump(read, fp, sort_keys=True, indent=4)
ka.sendText(msg.to, "Set reading point:\n" + readTime)
elif msg.text == "Lurking off":
if msg.from_ in owner:
tz = pytz.timezone("Asia/Jakarta")
timeNow = datetime.now(tz=tz)
day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]
hr = timeNow.strftime("%A")
bln = timeNow.strftime("%m")
for i in range(len(day)):
if hr == day[i]: hasil = hari[i]
for k in range(0, len(bulan)):
if bln == str(k): bln = bulan[k-1]
readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]"
if msg.to not in read['readPoint']:
ka.sendText(msg.to,"Lurking already off")
else:
try:
del read['readPoint'][msg.to]
del read['readMember'][msg.to]
del read['readTime'][msg.to]
except:
pass
ka.sendText(msg.to, "Delete reading point:\n" + readTime)
elif msg.text == "Lurking reset":
if msg.from_ in owner:
tz = pytz.timezone("Asia/Jakarta")
timeNow = datetime.now(tz=tz)
day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]
hr = timeNow.strftime("%A")
bln = timeNow.strftime("%m")
for i in range(len(day)):
if hr == day[i]: hasil = hari[i]
for k in range(0, len(bulan)):
if bln == str(k): bln = bulan[k-1]
readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]"
if msg.to in read["readPoint"]:
try:
read["readPoint"][msg.to] = True
read["readMember"][msg.to] = {}
read["readTime"][msg.to] = readTime
read["ROM"][msg.to] = {}
except:
pass
ka.sendText(msg.to, "Reset reading point:\n" + readTime)
else:
ka.sendText(msg.to, "Lurking belum diaktifkan ngapain di reset?")
elif msg.text == "Lurking":
if msg.from_ in owner:
tz = pytz.timezone("Asia/Jakarta")
timeNow = datetime.now(tz=tz)
day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]
hr = timeNow.strftime("%A")
bln = timeNow.strftime("%m")
for i in range(len(day)):
if hr == day[i]: hasil = hari[i]
for k in range(0, len(bulan)):
if bln == str(k): bln = bulan[k-1]
readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nJam : [ " + timeNow.strftime('%H:%M:%S') + " ]"
if msg.to in read['readPoint']:
if read["ROM"][msg.to].items() == []:
ka.sendText(msg.to, "Lurkers:\nNone")
else:
chiya = []
for rom in read["ROM"][msg.to].items():
chiya.append(rom[1])
cmem = ka.getContacts(chiya)
zx = ""
zxc = ""
zx2 = []
xpesan = '[ Reader ]\n'
for x in range(len(cmem)):
xname = str(cmem[x].displayName)
pesan = ''
pesan2 = pesan+"@a\n"
xlen = str(len(zxc)+len(xpesan))
xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1)
zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid}
zx2.append(zx)
zxc += pesan2
msg.contentType = 0
msg.text = xpesan+ zxc + "\nLurking time: \n" + readTime
lol ={'MENTION':str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}
msg.contentMetadata = lol
try:
ka.sendMessage(msg)
except Exception as error:
print error
pass
else:
ka.sendText(msg.to, "Lurking has not been set.")
#==============================================================================#
elif msg.text in ["Gurl","Url","ลิงก์กลุ่ม"]:
if msg.from_ in admin:
if msg.toType == 2:
x = ka.getGroup(msg.to)
if x.preventJoinByTicket == True:
x.preventJoinByTicket = False
ka.updateGroup(x)
gurl = ka.reissueGroupTicket(msg.to)
ka.sendText(msg.to,"line://ti/g/" + gurl)
else:
if wait["lang"] == "JP":
ka.sendText(msg.to,"Can't be used outside the group")
else:
ka.sendText(msg.to,"Not for use less than group")
else:
ka.sendText(msg.to,"This Command Only For Admin & Owner")
#==============================================================================#
elif msg.text in ["Masuk","Bot in","Staff in"]:
if msg.from_ in owner:
G = ka.getGroup(msg.to)
ginfo = ka.getGroup(msg.to)
G.preventJoinByTicket = False
ka.updateGroup(G)
invsend = 0
Ticket = ka.reissueGroupTicket(msg.to)
kb.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.00001)
kc.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.00001)
kd.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.00001)
ke.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.00001)
kf.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.00001)
kg.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.00001)
kh.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.00001)
ki.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.00001)
kj.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.00001)
G = ka.getGroup(msg.to)
G.preventJoinByTicket = True
ka.updateGroup(G)
print "Semua Sudah Lengkap"
#==============================================================================#
elif msg.text in ["timeline"]:
try:
url = ka.activity(limit=10)
ka.sendText(msg.to,url['result']['posts'][0]['postInfo']['postId'])
except Exception as E:
print E
#==============================================================================#
elif msg.text in ["Keluar","Staff out","Out","Staff bye"]:
if msg.from_ in owner:
if msg.toType == 2:
ginfo = ka.getGroup(msg.to)
try:
kb.leaveGroup(msg.to)
kc.leaveGroup(msg.to)
kd.leaveGroup(msg.to)
ke.leaveGroup(msg.to)
kf.leaveGroup(msg.to)
kg.leaveGroup(msg.to)
kh.leaveGroup(msg.to)
ki.leaveGroup(msg.to)
kj.leaveGroup(msg.to)
#ka.leaveGroup(msg.to)
except:
pass
#===============================================================================#
elif msg.text in ["@bye"]:
if msg.from_ in owner:
if msg.toType == 2:
ginfo = ka.getGroup(msg.to)
try:
ka.leaveGroup(msg.to)
except:
pass
#==============================================================================#
elif msg.text in ["Absen"]:
if msg.from_ in admin:
ka.sendText(msg.to,"ルフィ😭")
kb.sendText(msg.to,"ゾーラー😭")
kc.sendText(msg.to,"サンジ😭")
kd.sendText(msg.to,"ウソップ😭")
ke.sendText(msg.to,"チョッパー😭")
#==============================================================================#
elif msg.text.lower() in ["respon"]:
ka.sendText(msg.to,responsename)
kb.sendText(msg.to,responsename2)
kc.sendText(msg.to,responsename3)
kd.sendText(msg.to,responsename4)
ke.sendText(msg.to,responsename5)
kf.sendText(msg.to,responsename6)
kg.sendText(msg.to,responsename7)
kh.sendText(msg.to,responsename8)
ki.sendText(msg.to,responsename9)
kj.sendText(msg.to,responsename10)
#==============================================================================#
elif msg.text.lower() in ["Sp","Speed"]:
fake=["0.002253985673451seconds"]
fspeed=random.choice(fake)
ka.sendText(msg.to," Progress.....")
ka.sendText(msg.to,(fspeed))
#==============================================================================#
elif msg.text in ["Sp","Speed","speed"]:
start = time.time()
ka.sendText(msg.to, "Bot 1 Processing Request")
elapsed_time = time.time() - start
ka.sendText(msg.to, "%sseconds" % (elapsed_time))
# ki.sendText(msg.to, "%sseconds" % (elapsed_time))
# ki2.sendText(msg.to, "%sseconds" % (elapsed_time))
# ki3.sendText(msg.to, "%sseconds" % (elapsed_time))
# ki4.sendText(msg.to, "%sseconds" % (elapsed_time))
# ki5.sendText(msg.to, "%sseconds" % (elapsed_time))
# ki6.sendText(msg.to, "%sseconds" % (elapsed_time))
#==============================================================================#
elif msg.text in ["Banlist","บัญชีดำ"]:
if msg.from_ in admin:
if wait["blacklist"] == {}:
ka.sendText(msg.to,"Nothing Banned User")
else:
ka.sendText(msg.to,"💂ศาล💹เบิกตัว📚\n🔘จำเลย ผู้กระทำความผิด ขึ้นบัญชีดำ⤵️")
mc = ""
for mi_d in wait["blacklist"]:
mc += "👤" +ka.getContact(mi_d).displayName + " 👀รอลงอาญา\n"
ka.sendText(msg.to,mc)
#==============================================================================#
elif msg.text in ["Clear ban","Cb","ล้างดำ"]:
if msg.from_ in owner:
wait["blacklist"] = {}
ka.sendText(msg.to,"💀Clear Blacklist Boss Man💀")
#==============================================================================#
elif "Error!" in msg.text:
if msg.from_ in owner:
if msg.toType == 2:
print "ok"
_name = msg.text.replace("Error!","")
gs = ka.getGroup(msg.to)
gs = kb.getGroup(msg.to)
gs = kc.getGroup(msg.to)
gs = kd.getGroup(msg.to)
gs = ke.getGroup(msg.to)
gs = kf.getGroup(msg.to)
gs = kg.getGroup(msg.to)
gs = kh.getGroup(msg.to)
gs = ki.getGroup(msg.to)
gs = kj.getGroup(msg.to)
ka.sendText(msg.to,"This My Team WAR")
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
ka.sendText(msg.to,"Not found")
else:
for target in targets:
if target not in Bots or owner:
if target in owner:
pass
elif target in admin:
pass
elif target in Bots:
pass
else:
try:
klist=[ka,kb,kc,kd,ke,kf,kg,kh,ki,kj]
kicker=random.choice(klist)
kicker.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except:
random.choice(KAC).kickoutFromGroup(msg.to,[target])
#==============================================================================#
elif msg.text in ["Bot restart"]:
if msg.from_ in owner:
ka.sendText(msg.to, "Kami Siap Restart\nWaktu Restart Sekitar 10 Detik ")
restart_program()
else:
ka.sendText(msg.to,"This Command Only For Owner")
#==============================================================================#
elif "/music " in msg.text:
songname = msg.text.replace("/music ","")
params = {"songname": songname}
r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
abc = song[3].replace('https://','http://')
ka.sendText(msg.to, "🔘Title : " + song[0] + "\n🔘Length : " + song[1] + "\n🔘Link download : " + song[4])
ka.sendText(msg.to, "Lagu " + song[0] + "\nSedang Di Prosses... Tunggu Sebentar ^_^ ")
ka.sendAudioWithURL(msg.to,abc)
ka.sendText(msg.to, "Selamat Mendengarkan Lagu " + song[0])
#==============================================================================#
elif '/lirik ' in msg.text.lower():
try:
songname = msg.text.lower().replace('/lirik ','')
params = {'songname': songname}
r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
hasil = 'Lyric Lagu ('
hasil += song[0]
hasil += ')\n\n'
hasil += song[5]
ka.sendText(msg.to, hasil)
except Exception as wak:
ka.sendText(msg.to, str(wak))
#==============================================================================#
elif '/ig ' in msg.text.lower():
try:
instagram = msg.text.lower().replace("/ig ","")
html = requests.get('https://www.instagram.com/' + instagram + '/?')
soup = BeautifulSoup(html.text, 'html.parser')
data = soup.find_all('meta', attrs={'property':'og:description'})
text = data[0].get('content').split()
data1 = soup.find_all('meta', attrs={'property':'og:image'})
text1 = data1[0].get('content').split()
tj = text1[0].replace("s150x150/","")
user = "🔘Name: " + text[-2] + "\n"
user1 = "🔘Username: " + text[-1] + "\n"
followers = "🔘Followers: " + text[0] + "\n"
following = "🔘Following: " + text[2] + "\n"
post = "🔘Post: " + text[4] + "\n"
link = "🔘Link: " + "https://www.instagram.com/" + instagram
detail = "========INSTAGRAM INFO ========\n"
details = "\n========INSTAGRAM INFO ========"
ka.sendText(msg.to, detail + user + user1 + followers + following + post + link + details)
ka.sendImageWithURL(msg.to, tj)
except Exception as njer:
ka.sendText(msg.to, str(njer))
#==============================================================================#
elif 'Youtubelink: ' in msg.text:
try:
textToSearch = (msg.text).replace('Youtube ', "").strip()
query = urllib.quote(textToSearch)
url = "https://www.youtube.com/results?search_query=" + query
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html, "html.parser")
results = soup.find(attrs={'class':'yt-uix-tile-link'})
ka.sendText(msg.to,'https://www.youtube.com' + results['href'])
except:
ka.sendText(msg.to,"🔘กรุณาใช้คำศัพท์ที่ถูกต้องและทำการค้นหาอีกครั้ง")
#==============================================================================#
elif '/yt: ' in msg.text:
try:
textToSearch = (msg.text).replace('Youtube ', "").strip()
query = urllib.quote(textToSearch)
url = "https://www.youtube.com/results?search_query=" + query
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html, "html.parser")
results = soup.find(attrs={'class':'yt-uix-tile-link'})
ka.sendText(msg.to,'https://www.youtube.com' + results['href'])
except:
ka.sendText(msg.to,"🔘กรุณาใช้คำศัพท์ที่ถูกต้องและทำการค้นหาอีกครั้ง")
#==============================================================================#
elif "Say-id " in msg.text:
say = msg.text.replace("Say-id ","")
lang = 'id'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
ka.sendAudio(msg.to,"hasil.mp3")
elif "Say-en " in msg.text:
say = msg.text.replace("Say-en ","")
lang = 'en'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
ka.sendAudio(msg.to,"hasil.mp3")
elif "Say-jp " in msg.text:
say = msg.text.replace("Say-jp ","")
lang = 'ja'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
ka.sendAudio(msg.to,"hasil.mp3")
elif "Say welcome" in msg.text:
gs = ka.getGroup(msg.to)
say = msg.text.replace("Say welcome","Selamat Datang Di "+ gs.name)
lang = 'id'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
ka.sendAudio(msg.to,"hasil.mp3")
#==============================================================================#
elif "playstore " in msg.text.lower():
tob = msg.text.lower().replace("playstore ","")
ka.sendText(msg.to,"Sedang Mencari...")
ka.sendText(msg.to,"🔘Title : "+tob+"\n🔘Source : Google Play\n🔘Link download : https://play.google.com/store/search?q=" + tob)
ka.sendText(msg.to,"🔘by : SELFBOT MAN MEDIA @2018")
#==============================================================================#
elif "/เพลสโตร์:" in msg.text.lower():
tob = msg.text.lower().replace("/เพลสโตร์:","")
ka.sendText(msg.to,"Playstore...")
ka.sendText(msg.to,"🔘Title : "+tob+"\n🔘Source : Google Play\n🔘Link download : https://play.google.com/store/search?q=" + tob)
ka.sendText(msg.to,"🔘by : SELFBOT MAN MEDIA @2018")
#==============================================================================#
elif msg.text.lower() in ["me"]:
msg.contentType = 13
msg.contentMetadata = {'mid': msg.from_}
ka.sendMessage(msg)
#==============================================================================#
elif "/apakah " in msg.text:
apk = msg.text.replace("/apakah ","")
rnd = ["Ya","Tidak","Bisa Jadi","Mungkin"]
p = random.choice(rnd)
lang = 'id'
tts = gTTS(text=p, lang=lang)
tts.save("hasil.mp3")
ka.sendAudio(msg.to,"hasil.mp3")
elif "/hari " in msg.text:
apk = msg.text.replace("/hari ","")
rnd = ["Senin","Selasa","Rabu","Kamis","Jumat","Sabtu","Minggu"]
p = random.choice(rnd)
lang = 'id'
tts = gTTS(text=p, lang=lang)
tts.save("hasil.mp3")
ka.sendAudio(msg.to,"hasil.mp3")
elif "/berapa " in msg.text:
apk = msg.text.replace("/berapa ","")
rnd = ['10%','20%','30%','40%','50%','60%','70%','80%','90%','100%','0%']
p = random.choice(rnd)
lang = 'id'
tts = gTTS(text=p, lang=lang)
tts.save("hasil.mp3")
ka.sendAudio(msg.to,"hasil.mp3")
elif "/berapakah " in msg.text:
apk = msg.text.replace("/berapakah ","")
rnd = ['1','2','3','4','5','6','7','8','9','10','Tidak Ada']
p = random.choice(rnd)
lang = 'id'
tts = gTTS(text=p, lang=lang)
tts.save("hasil.mp3")
ka.sendAudio(msg.to,"hasil.mp3")
elif "/kapan " in msg.text:
apk = msg.text.replace("/kapan ","")
rnd = ["kapan kapan","besok","satu abad lagi","Hari ini","Tahun depan","Minggu depan","Bulan depan","Sebentar lagi","Tidak Akan Pernah"]
p = random.choice(rnd)
lang = 'id'
tts = gTTS(text=p, lang=lang)
tts.save("hasil.mp3")
ka.sendAudio(msg.to,"hasil.mp3")
#==============================================================================#
elif "Image " in msg.text:
search = msg.text.replace("Image ","")
url = 'https://www.google.com/search?espv=2&biw=1366&bih=667&tbm=isch&oq=kuc&aqs=mobile-gws-lite.0.0l5&q=' + search
raw_html = (download_page(url))
items = []
items = items + (_images_get_all_items(raw_html))
path = random.choice(items)
print path
try:
ka.sendImageWithURL(msg.to,path)
except:
pass
#==============================================================================#
elif "/รูปภาพ:" in msg.text:
search = msg.text.replace("/รูปภาพ:","")
url = 'https://www.google.com/search?espv=2&biw=1366&bih=667&tbm=isch&oq=kuc&aqs=mobile-gws-lite.0.0l5&q=' + search
raw_html = (download_page(url))
items = []
items = items + (_images_get_all_items(raw_html))
path = random.choice(items)
print path
try:
ka.sendImageWithURL(msg.to,path)
except:
pass
#==============================================================================#
elif "Tr-id " in msg.text:
isi = msg.text.replace("Tr-id ","")
translator = Translator()
hasil = translator.translate(isi, dest='id')
A = hasil.text
A = A.encode('utf-8')
ka.sendText(msg.to, A)
elif "Tr-en " in msg.text:
isi = msg.text.replace("Tr-en ","")
translator = Translator()
hasil = translator.translate(isi, dest='en')
A = hasil.text
A = A.encode('utf-8')
ka.sendText(msg.to, A)
#==============================================================================#
elif "Id@en" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'en'
kata = msg.text.replace("Id@en ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
ka.sendText(msg.to,"----Dari Indonesia----\n" + "" + kata + "\n\n----Ke Inggris----\n" + "" + result)
elif "En@id" in msg.text:
bahasa_awal = 'en'
bahasa_tujuan = 'id'
kata = msg.text.replace("En@id ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
ka.sendText(msg.to,"----Dari Inggris----\n" + "" + kata + "\n\n----Ke Indonesia----\n" + "" + result)
#==============================================================================#
elif msg.text.lower() == 'runtime':
eltime = time.time() - mulai
van = "Bot Sudah Berjalan Selama :\n"+waktu(eltime)
ka.sendText(msg.to,van)
#==============================================================================#
elif msg.text.lower() == '/เช็คเวลาบอท':
eltime = time.time() - mulai
van = "🔘ระยะเวลาการทำงานของบอท:⤵️\n"+waktu(eltime)
ka.sendText(msg.to,van)
#==============================================================================#
elif "SearchID: " in msg.text:
userid = msg.text.replace("SearchID: ","")
contact = ka.findContactsByUserid(userid)
msg.contentType = 13
msg.contentMetadata = {'mid': contact.mid}
ka.sendMessage(msg)
#==============================================================================#
elif "LineID: " in msg.text:
userid = msg.text.replace("LineID: ","")
contact = ka.findContactsByUserid(userid)
msg.contentType = 13
msg.contentMetadata = {'mid': contact.mid}
ka.sendMessage(msg)
#==============================================================================#
elif "removechat" in msg.text.lower():
if msg.from_ in admin:
try:
ka.removeAllMessages(op.param2)
kb.removeAllMessages(op.param2)
kc.removeAllMessages(op.param2)
kd.removeAllMessages(op.param2)
ke.removeAllMessages(op.param2)
kf.removeAllMessages(op.param2)
kg.removeAllMessages(op.param2)
kh.removeAllMessages(op.param2)
ki.removeAllMessages(op.param2)
kj.removeAllMessages(op.param2)
print "[Command] Remove Chat"
ka.sendText(msg.to,"Done")
except Exception as error:
print error
ka.sendText(msg.to,"Error")
#==============================================================================#
elif "/ล้างแชทบอท" in msg.text.lower():
if msg.from_ in admin:
try:
ka.removeAllMessages(op.param2)
kb.removeAllMessages(op.param2)
kc.removeAllMessages(op.param2)
kd.removeAllMessages(op.param2)
ke.removeAllMessages(op.param2)
kf.removeAllMessages(op.param2)
kg.removeAllMessages(op.param2)
kh.removeAllMessages(op.param2)
ki.removeAllMessages(op.param2)
kj.removeAllMessages(op.param2)
print "[Command] Remove Chat"
ka.sendText(msg.to,"🔘ลบข้อมูลแชทบอทเรียบร้อย")
except Exception as error:
print error
ka.sendText(msg.to,"Error")
#==============================================================================#
elif msg.text in ["Glist"]:
if msg.from_ in owner:
ka.sendText(msg.to, "Tunggu Sebentar. . .")
gid = ka.getGroupIdsJoined()
h = ""
for i in gid:
h += "╠" + "%s\n" % (ka.getGroup(i).name +"▶["+str(len(ka.getGroup(i).members))+"]")
ka.sendText(msg.to,"╔════[ Glist ]════\n" + h + "╠════════════" + "\n║ Total Groups =" +" ["+str(len(gid))+"]\n╚════[ Glist ]════")
elif msg.text in ["Glistmid"]:
if msg.from_ in owner:
gruplist = ke.getGroupIdsJoined()
kontak = ke.getGroups(gruplist)
num=1
msgs="════════List GrupMid══════"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.id)
num=(num+1)
msgs+="\n══════List GrupMid════l═══\n\nTotal Grup : %i" % len(kontak)
ke.sendText(msg.to, msgs)
#==============================================================================#
if op.type == 25:
msg = op.message
if msg.text.lower() in ["pheytcg fgtagg all"]:
group = ka.getGroup(msg.to)
nama = [contact.mid for contact in group.members]
nm1, nm2, nm3, nm4, nm5, jml = [], [], [], [], [], len(nama)
if jml <= 100:
mention(msg.to, nama)
if jml > 100 and jml < 200:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, len(nama)):
nm2 += [nama[j]]
mention(msg.to, nm2)
if jml > 200 and jml < 300:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, 200):
nm2 += [nama[j]]
mention(msg.to, nm2)
for k in range(201, len(nama)):
nm3 += [nama[k]]
mention(msg.to, nm3)
if jml > 300 and jml < 400:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, 200):
nm2 += [nama[j]]
mention(msg.to, nm2)
for k in range(201, 300):
nm3 += [nama[k]]
mention(msg.to, nm3)
for l in range(301, len(nama)):
nm4 += [nama[l]]
mention(msg.to, nm4)
if jml > 400 and jml < 500:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, 200):
nm2 += [nama[j]]
mention(msg.to, nm2)
for k in range(201, 300):
nm3 += [nama[k]]
mention(msg.to, nm3)
for l in range(301, 400):
nm4 += [nama[l]]
mention(msg.to, nm4)
for h in range(401, len(nama)):
nm5 += [nama[h]]
mention(msg.to, nm5)
if jml > 500:
ka.sendText(msg.to,'Member melebihi batas.')
cnt = Message()
cnt.text = "PHET TAG DONE : " + str(jml) + " Members"
cnt.to = msg.to
ka.sendMessage(cnt)
if op.type == 26:
msg = op.message
if msg.text.lower() in ["1123"]:
group = ka.getGroup(msg.to)
nama = [contact.mid for contact in group.members]
nm1, nm2, nm3, nm4, nm5, jml = [], [], [], [], [], len(nama)
if jml <= 100:
mention(msg.to, nama)
if jml > 100 and jml < 200:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, len(nama)):
nm2 += [nama[j]]
mention(msg.to, nm2)
if jml > 200 and jml < 300:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, 200):
nm2 += [nama[j]]
mention(msg.to, nm2)
for k in range(201, len(nama)):
nm3 += [nama[k]]
mention(msg.to, nm3)
if jml > 300 and jml < 400:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, 200):
nm2 += [nama[j]]
mention(msg.to, nm2)
for k in range(201, 300):
nm3 += [nama[k]]
mention(msg.to, nm3)
for l in range(301, len(nama)):
nm4 += [nama[l]]
mention(msg.to, nm4)
if jml > 400 and jml < 500:
for i in range(0, 100):
nm1 += [nama[i]]
mention(msg.to, nm1)
for j in range(101, 200):
nm2 += [nama[j]]
mention(msg.to, nm2)
for k in range(201, 300):
nm3 += [nama[k]]
mention(msg.to, nm3)
for l in range(301, 400):
nm4 += [nama[l]]
mention(msg.to, nm4)
for h in range(401, len(nama)):
nm5 += [nama[h]]
mention(msg.to, nm5)
if jml > 500:
ka.sendText(msg.to,'Member melebihi batas.')
cnt = Message()
cnt.text = "PHET TAG DONE : " + str(jml) + " Members"
cnt.to = msg.to
ka.sendMessage(cnt)
#=====================================================================================#
if op.type == 26:
msg = op.message
if msg.contentType == 16:
url = msg.contentMetadata['postEndUrl']
ka.like(url[25:58], url[66:], likeType=1001)
ka.comment(url[25:58], url[66:], wait["comment1"])
# ki1.like(url[25:58], url[66:], likeType=1001)
# ki1.comment(url[25:58], url[66:], wait["comment1"])
# ki2.like(url[25:58], url[66:], likeType=1001)
# ki2.comment(url[25:58], url[66:], wait["comment1"])
# ki3.like(url[25:58], url[66:], likeType=1001)
# ki3.comment(url[25:58], url[66:], wait["comment1"])
# ki4.like(url[25:58], url[66:], likeType=1001)
# ki4.comment(url[25:58], url[66:], wait["comment1"])
# ki5.like(url[25:58], url[66:], likeType=1001)
# ki5.comment(url[25:58], url[66:], wait["comment1"])
# ki6.like(url[25:58], url[66:], likeType=1001)
# ki6.comment(url[25:58], url[66:], wait["comment1"])
# ki7.like(url[25:58], url[66:], likeType=1001)
# ki7.comment(url[25:58], url[66:], wait["comment1"])
# ki8.like(url[25:58], url[66:], likeType=1001)
# ki8.comment(url[25:58], url[66:], wait["comment1"])
# ki9.like(url[25:58], url[66:], likeType=1001)
# ki9.comment(url[25:58], url[66:], wait["comment1"])
# ki10.like(url[25:58], url[66:], likeType=1001)
# ki10.comment(url[25:58], url[66:], wait["comment1"])
print ("AUTO LIKE SELFBOT")
print ("Auto Like By.TOMEBOTLINE")
#=====================================================================================#
if op.type == 55:
try:
if op.param1 in read['readPoint']:
if op.param2 in read['readMember'][op.param1]:
pass
else:
read['readMember'][op.param1] += op.param2
read['ROM'][op.param1][op.param2] = op.param2
with open('sider.json', 'w') as fp:
json.dump(read, fp, sort_keys=True, indent=4)
else:
pass
except:
pass
#==============================================================================#
if op.type == 59:
print op
except Exception as error:
print error
while True:
try:
Ops = ka.fetchOps(ka.Poll.rev, 5)
except EOFError:
raise Exception("It might be wrong revision\n" + str(ka.Poll.rev))
for Op in Ops:
if (Op.type != OpType.END_OF_OPERATION):
ka.Poll.rev = max(ka.Poll.rev, Op.revision)
bot(Op)
| false | true |
f7f8986539b7a68162a81aad5b33d53bde3448f2 | 4,108 | py | Python | frappe/utils/autodoc.py | ebymathew5225/frappe | 880d824b77d2a6392a5d8ae9ea7db22199513c91 | [
"MIT"
] | 2 | 2017-08-24T20:25:13.000Z | 2017-10-15T13:14:31.000Z | frappe/utils/autodoc.py | ebymathew5225/frappe | 880d824b77d2a6392a5d8ae9ea7db22199513c91 | [
"MIT"
] | 89 | 2017-09-19T15:17:44.000Z | 2022-03-31T00:52:42.000Z | frappe/utils/autodoc.py | ebymathew5225/frappe | 880d824b77d2a6392a5d8ae9ea7db22199513c91 | [
"MIT"
] | 3 | 2019-08-09T17:52:18.000Z | 2020-07-29T08:23:46.000Z | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
"""
frappe.utils.autodoc
~~~~~~~~~~~~~~~~~~~~
Inspect elements of a given module and return its objects
"""
from __future__ import unicode_literals, print_function
import inspect, importlib, re, frappe
from frappe.model.document import get_controller
from six import text_type
def automodule(name):
"""Returns a list of attributes for given module string.
Attribute Format:
{
"name": [__name__],
"type": ["function" or "class"]
"args": [inspect.getargspec(value) (for function)]
"docs": [__doc__ as markdown]
}
:param name: Module name as string."""
attributes = []
obj = importlib.import_module(name)
for attrname in dir(obj):
value = getattr(obj, attrname)
if getattr(value, "__module__", None) != name:
# imported member, ignore
continue
if inspect.isclass(value):
attributes.append(get_class_info(value, name))
if inspect.isfunction(value):
attributes.append(get_function_info(value))
return {
"members": filter(None, attributes),
"docs": get_obj_doc(obj)
}
installed = None
def get_version(name):
print(name)
global installed
if not installed:
installed = frappe.get_installed_apps()
def _for_module(m):
app_name = m.split(".")[0]
try:
docs_version = frappe.get_attr(app_name + ".config.docs.docs_version")
except AttributeError:
docs_version = None
if docs_version:
return docs_version
return getattr(importlib.import_module(m.split(".")[0]), "__version__", "0.0.0")
if "." in name or name in installed:
return _for_module(name)
else:
return _for_module(get_controller(name).__module__)
def get_class_info(class_obj, module_name):
members = []
for attrname in dir(class_obj):
member = getattr(class_obj, attrname)
if inspect.ismethod(member):
if getattr(member, "__module__", None) != module_name:
# inherited member, ignore
continue
members.append(get_function_info(member))
return {
"name": class_obj.__name__,
"type": "class",
"bases": [b.__module__ + "." + b.__name__ for b in class_obj.__bases__],
"members": filter(None, members),
"docs": parse(get_obj_doc(class_obj))
}
def get_function_info(value):
docs = get_obj_doc(value)
return {
"name": value.__name__,
"type": "function",
"args": inspect.getargspec(value),
"docs": parse(docs) if docs else '<span class="text-muted">No docs</span>',
"whitelisted": value in frappe.whitelisted
}
def parse(docs):
"""Parse __docs__ text into markdown. Will parse directives like `:param name:` etc"""
# strip leading tabs
if not docs:
return ""
if ":param" in docs:
out, title_set = [], False
for line in docs.splitlines():
if ":param" in line:
if not title_set:
# add title and list
out.append("")
out.append("**Parameters:**")
out.append("")
title_set = True
line = re.sub("\s*:param\s([^:]+):(.*)", "- **`\g<1>`** - \g<2>", line)
elif title_set and not ":param" in line:
# marker for end of list
out.append("")
title_set = False
out.append(line)
docs = "\n".join(out)
return docs
def strip_leading_tabs(docs):
"""Strip leading tabs from __doc__ text."""
lines = docs.splitlines()
# remove empty lines in the front
start = 0
for line in lines:
if line != '': break
start += 1
if start:
lines = lines[start:]
# remove default indentation
if len(lines) > 1:
start_line = 1
ref_line = lines[start_line]
while not ref_line:
# find reference line for indentations (the first line that is nonempty (false))
start_line += 1
if start_line > len(lines): break
ref_line = lines[start_line]
strip_left = len(ref_line) - len(ref_line.lstrip())
if strip_left:
docs = "\n".join([lines[0]] + [l[strip_left:] for l in lines[1:]])
return docs
def automodel(doctype):
"""return doctype template"""
pass
def get_obj_doc(obj):
'''Return `__doc__` of the given object as unicode'''
doc = getattr(obj, "__doc__", "") or ''
if not isinstance(doc, text_type):
doc = text_type(doc, 'utf-8')
return doc | 23.474286 | 87 | 0.677459 |
from __future__ import unicode_literals, print_function
import inspect, importlib, re, frappe
from frappe.model.document import get_controller
from six import text_type
def automodule(name):
attributes = []
obj = importlib.import_module(name)
for attrname in dir(obj):
value = getattr(obj, attrname)
if getattr(value, "__module__", None) != name:
continue
if inspect.isclass(value):
attributes.append(get_class_info(value, name))
if inspect.isfunction(value):
attributes.append(get_function_info(value))
return {
"members": filter(None, attributes),
"docs": get_obj_doc(obj)
}
installed = None
def get_version(name):
print(name)
global installed
if not installed:
installed = frappe.get_installed_apps()
def _for_module(m):
app_name = m.split(".")[0]
try:
docs_version = frappe.get_attr(app_name + ".config.docs.docs_version")
except AttributeError:
docs_version = None
if docs_version:
return docs_version
return getattr(importlib.import_module(m.split(".")[0]), "__version__", "0.0.0")
if "." in name or name in installed:
return _for_module(name)
else:
return _for_module(get_controller(name).__module__)
def get_class_info(class_obj, module_name):
members = []
for attrname in dir(class_obj):
member = getattr(class_obj, attrname)
if inspect.ismethod(member):
if getattr(member, "__module__", None) != module_name:
continue
members.append(get_function_info(member))
return {
"name": class_obj.__name__,
"type": "class",
"bases": [b.__module__ + "." + b.__name__ for b in class_obj.__bases__],
"members": filter(None, members),
"docs": parse(get_obj_doc(class_obj))
}
def get_function_info(value):
docs = get_obj_doc(value)
return {
"name": value.__name__,
"type": "function",
"args": inspect.getargspec(value),
"docs": parse(docs) if docs else '<span class="text-muted">No docs</span>',
"whitelisted": value in frappe.whitelisted
}
def parse(docs):
if not docs:
return ""
if ":param" in docs:
out, title_set = [], False
for line in docs.splitlines():
if ":param" in line:
if not title_set:
out.append("")
out.append("**Parameters:**")
out.append("")
title_set = True
line = re.sub("\s*:param\s([^:]+):(.*)", "- **`\g<1>`** - \g<2>", line)
elif title_set and not ":param" in line:
out.append("")
title_set = False
out.append(line)
docs = "\n".join(out)
return docs
def strip_leading_tabs(docs):
lines = docs.splitlines()
start = 0
for line in lines:
if line != '': break
start += 1
if start:
lines = lines[start:]
if len(lines) > 1:
start_line = 1
ref_line = lines[start_line]
while not ref_line:
start_line += 1
if start_line > len(lines): break
ref_line = lines[start_line]
strip_left = len(ref_line) - len(ref_line.lstrip())
if strip_left:
docs = "\n".join([lines[0]] + [l[strip_left:] for l in lines[1:]])
return docs
def automodel(doctype):
pass
def get_obj_doc(obj):
doc = getattr(obj, "__doc__", "") or ''
if not isinstance(doc, text_type):
doc = text_type(doc, 'utf-8')
return doc | true | true |
f7f898dc0749779aeb4da872cc0240dc7f9f0065 | 10,172 | py | Python | game/engine.py | deecamp2019-group20/CNN_PokerNet | 751576cb941be57c8a37656feaff14b414c3dcb2 | [
"MIT"
] | 1 | 2019-12-12T09:01:49.000Z | 2019-12-12T09:01:49.000Z | game/engine.py | deecamp2019-group20/CNN_PokerNet | 751576cb941be57c8a37656feaff14b414c3dcb2 | [
"MIT"
] | 1 | 2019-11-25T13:43:45.000Z | 2019-11-25T13:43:45.000Z | game/engine.py | deecamp2019-group20/CNN_PokerNet | 751576cb941be57c8a37656feaff14b414c3dcb2 | [
"MIT"
] | 1 | 2020-03-15T06:20:04.000Z | 2020-03-15T06:20:04.000Z | # -*- coding: utf-8 -*-
"""
自定义相关类
"""
import numpy as np
from typing import List, Tuple, Dict
import pandas as pd
from collections import defaultdict
from os.path import join, abspath, dirname
from .card_util import All as backup, cache
from .gameutil import card_show
from copy import copy
from .r import get_moves
############################################
# 游戏类 #
############################################
class GameState():
def __init__(self):
self.hand = None
self.out = None
self.up_out = None
self.down_out = None
self.self_out = None
self.other_hand = None
self.last_move = [0]*15 # 上一个有效出牌,全零表示主动权
self.last_pid = -1 # 上一个有效出牌的玩家编号,-1表示主动权
self.last_move_ = np.zeros(15, dtype=int) # 上一个出牌,不管有效与否
self.last_last_move_ = np.zeros(15, dtype=int) # 上上个出牌,不管有效与否
class Game(object):
def __init__(self, agents: List['Agent']):
# 初始化players
self.players = agents
for p in agents:
p.game = self
self.game_reset()
def get_state(self)->GameState:
state = GameState()
state.hand = self.players[self.index].get_hand_card().copy()
tmp, state.out = Card.vectorized_card_out(self.cards_out, len(self.players))
state.up_out = tmp[self.get_up_index()]
state.down_out = tmp[self.get_down_index()]
state.self_out = tmp[self.index]
state.other_hand = (np.array([4]*13+[1,1]) - state.hand - state.out).tolist()
state.last_move = self.last_move.copy()
state.last_pid = self.last_pid
if len(self.cards_out)>=1:
self.last_move_ = self.cards_out[-1][-1].copy()
if len(self.cards_out)>=2:
self.last_last_move_ = self.cards_out[-2][-1].copy()
return state
def get_up_index(self):
return len(self.players)-1 if self.index==0 else self.index-1
def get_down_index(self):
return 0 if self.index==len(self.players)-1 else self.index+1
# 游戏环境重置
def game_reset(self):
#初始化一副扑克牌类
cards = Card.init_card_suit()
#洗牌
np.random.shuffle(cards)
#发牌并排序
self.mingpai = cards[:3]
p1_cards = cards[:20]
p1_cards.sort(key=lambda x: x.rank)
p2_cards = cards[20:37]
p2_cards.sort(key=lambda x: x.rank)
p3_cards = cards[37:]
p3_cards.sort(key=lambda x: x.rank)
self.players[0].set_hand_card( p1_cards )
self.players[1].set_hand_card( p2_cards )
self.players[2].set_hand_card( p3_cards )
self.cards_out = []
#play相关参数
self.end = False # 游戏是否结束
self.last_move = [0]*15
self.last_pid = -1
self.playround = 1 # 回合数
self.index = 0 # 当前玩家的id,0代表地主,1代表地主下家,2代表地主上家
self.yaobuqis = []
return self.players[0].get_hand_card(),\
self.players[1].get_hand_card(),\
self.players[2].get_hand_card(),\
Card.vectorized_card_list(self.mingpai)
#游戏进行
def step(self):
player = self.players[self.index]
state = self.get_state()
state, cur_moves, cur_move, self.end, info = player.step(state) #返回:在状态state下,当前玩家的出牌列表、游戏是否结束、choose自定义返回值
if sum(cur_move)==0:
self.yaobuqis.append(self.index)
#都要不起
if len(self.yaobuqis) == len(self.players)-1:
self.yaobuqis = []
self.last_move = [0]*15
self.last_pid = -1
else:
self.yaobuqis = []
self.last_move = cur_move
self.last_pid = self.index
winner = -1
if self.end:
winner = self.index
self.index = self.index + 1
#一轮结束
if self.index >= len(self.players):
self.playround = self.playround + 1
self.index = 0
return player.player_id, state, cur_moves, cur_move, winner, info
def show(self):
for i in range(len(self.players)):
card_show(self.players[i].get_hand_card(), "Player {}".format(i), 1)
############################################
# 扑克牌相关类 #
############################################
class Card(object):
"""
扑克牌类
"""
color_show = {}
#color_show = {'a': '♠', 'b':'♥', 'c':'♣', 'd':'♦'}
name_show = {'11':'J', '12':'Q', '13':'K', '14':'B', '15':'R'}
name_to_rank = {'3':1, '4':2, '5':3, \
'6':4, '7':5, '8':6, '9':7, '10':8, '11':9, '12':10, '13':11, \
'1':12, '2':13, '14':14, '15':15}
all_card_type = ['1-a', '1-b','1-c','1-d',
'2-a', '2-b','2-c','2-d',
'3-a', '3-b','3-c','3-d',
'4-a', '4-b','4-c','4-d',
'5-a', '5-b','5-c','5-d',
'6-a', '6-b','6-c','6-d',
'7-a', '7-b','7-c','7-d',
'8-a', '8-b','8-c','8-d',
'9-a', '9-b','9-c','9-d',
'10-a', '10-b','10-c','10-d',
'11-a', '11-b','11-c','11-d',
'12-a', '12-b','12-c','12-d',
'13-a', '13-b','13-c','13-d',
'14-a', '15-a']
all_card_name = [str(i) for i in range(3, 14)] + ['1', '2', '14', '15']
@staticmethod
def visual_card(cards):
c = []
for i, n in enumerate(Card.all_card_name):
c.extend([n]*cards[i])
return c
@staticmethod
def vectorized_card_list(cards: List):
v = [0] * len(Card.all_card_name)
for c in cards:
if isinstance(c, int):
i = Card.name_to_rank[str(c)]-1
elif isinstance(c, str):
i = Card.name_to_rank[c]-1
elif isinstance(c, Card):
i = c.rank-1
else:
print("Warn: Unkown card.")
v[ i ]+=1
return v
@staticmethod
def vectorized_card_out(cards_out: List[Tuple[int, np.array]], total_player=3):
cnt = {}
for rec in cards_out:
a = cnt.get(rec[0], np.zeros( 15, dtype=int )) # 15
b = np.array( rec[-1], dtype=int )
cnt[rec[0]] = a+b
a = np.zeros( 15, dtype=int )
for v in cnt.values():
a+=v
res = []
for i in range(total_player):
res.append(cnt.get(i, np.zeros( 15, dtype=int )).tolist())
return res, a.tolist()
@staticmethod
def init_card_suit():
cards = []
for card_type in Card.all_card_type:
cards.append(Card(card_type))
return cards
def __init__(self, card_type):
self.card_type = card_type # '牌面数字-花色' 举例来说,红桃A的card_type为'1-a'
self.name = self.card_type.split('-')[0] # 名称,即牌面数字
self.color = self.card_type.split('-')[1] # 花色
# 大小
self.rank = Card.name_to_rank[self.name]
def __str__(self):
return Card.name_show.get(self.name, self.name)
#return Card.name_show.get(self.name, self.name) + Card.color_show.get(self.color, self.color)
__repr__ = __str__
def get_move_desc(move: List[int]):
"""
输入出牌, 返回牌型描述:总张数,主牌rank,类型
move: 长度为15的数组,元素表示3/4/5/...15出多少张。全零表示不要。
"""
lst = []
for i, n in enumerate(Card.all_card_name):
lst.extend([int(n)]*move[i])
key = str(sorted(lst))
return cache[key]
def group_by_type(moves: List[Dict]):
"""
输入moves, 返回按牌型分组的描述。
返回值:
{ 'type1': [(move1, desc1), ...], ... }
move1 是一个15的列表,desc1是namedtuple,可用属性:sum/type/main/kicker
"""
res = defaultdict(list)
for m in moves:
desc = get_move_desc(m)
res[desc.type].append( (m, desc) )
return res
############################################
# 玩家相关类 #
############################################
class Agent(object):
"""
玩家类,所有模型都应继承此类并重写choose方法
"""
def __init__(self, player_id):
self.player_id = player_id # 0代表地主,1代表地主下家,2代表地主上家
self.__cards_left = np.zeros(15, dtype=int) # 表示3/4/5.../15有多少张
self.game = None
self.state = None # 当前游戏状态
def set_hand_card(self, cards):
self.__cards_left = np.zeros(15, dtype=int) # 表示3/4/5.../15有多少张
for c in cards:
self.__cards_left[c.rank-1]+=1
def get_hand_card(self):
return self.__cards_left
def get_public_card(self):
public_cards = self.game.mingpai
v = np.zeros(15, dtype=int)
for c in public_cards:
if isinstance(c, int):
i = Card.name_to_rank[str(c)]-1
elif isinstance(c, str):
i = Card.name_to_rank[c]-1
elif isinstance(c, Card):
# Card.rank starts from 1
i = c.rank-1
else:
print("Warn: Unkown card.")
v[ i ]+=1
return v
def get_moves(self):
'''
根据前面玩家的出牌来选牌,返回下一步所有合法出牌。
'''
moves = get_moves(self.__cards_left, self.game.last_move)
return moves
# 模型选择如何出牌
def choose(self, state: GameState) -> Tuple[List[int], object]:
return [], None
# 进行一步之后的公共操作
def __common_step(self, move):
#移除出掉的牌; 记录
try:
assert( np.all(self.__cards_left>=move) )
assert( np.all(self.__cards_left[:-2]<=4) and np.all(self.__cards_left[-2:])<=1 )
except AssertionError:
print("手牌:", self.__cards_left)
print("出牌:", move)
raise AssertionError()
self.__cards_left -= move
self.game.cards_out.append( (self.player_id, move) )
#是否牌局结束
end = False
if self.__cards_left.sum() == 0:
end = True
return end
# 出牌
def step(self, state):
self.move_list = self.get_moves() # 可在self.choose里使用
move, info = self.choose(state)
end = self.__common_step(move)
return state, self.move_list, move, end, info
def observation(self):
return self.game.get_state(), self.get_moves()
| 31.987421 | 115 | 0.514746 |
import numpy as np
from typing import List, Tuple, Dict
import pandas as pd
from collections import defaultdict
from os.path import join, abspath, dirname
from .card_util import All as backup, cache
from .gameutil import card_show
from copy import copy
from .r import get_moves
x: x.rank)
self.players[0].set_hand_card( p1_cards )
self.players[1].set_hand_card( p2_cards )
self.players[2].set_hand_card( p3_cards )
self.cards_out = []
self.end = False
self.last_move = [0]*15
self.last_pid = -1
self.playround = 1
self.index = 0
self.yaobuqis = []
return self.players[0].get_hand_card(),\
self.players[1].get_hand_card(),\
self.players[2].get_hand_card(),\
Card.vectorized_card_list(self.mingpai)
def step(self):
player = self.players[self.index]
state = self.get_state()
state, cur_moves, cur_move, self.end, info = player.step(state)
if sum(cur_move)==0:
self.yaobuqis.append(self.index)
if len(self.yaobuqis) == len(self.players)-1:
self.yaobuqis = []
self.last_move = [0]*15
self.last_pid = -1
else:
self.yaobuqis = []
self.last_move = cur_move
self.last_pid = self.index
winner = -1
if self.end:
winner = self.index
self.index = self.index + 1
if self.index >= len(self.players):
self.playround = self.playround + 1
self.index = 0
return player.player_id, state, cur_moves, cur_move, winner, info
def show(self):
for i in range(len(self.players)):
card_show(self.players[i].get_hand_card(), "Player {}".format(i), 1)
cnt[rec[0]] = a+b
a = np.zeros( 15, dtype=int )
for v in cnt.values():
a+=v
res = []
for i in range(total_player):
res.append(cnt.get(i, np.zeros( 15, dtype=int )).tolist())
return res, a.tolist()
@staticmethod
def init_card_suit():
cards = []
for card_type in Card.all_card_type:
cards.append(Card(card_type))
return cards
def __init__(self, card_type):
self.card_type = card_type
self.name = self.card_type.split('-')[0]
self.color = self.card_type.split('-')[1]
self.rank = Card.name_to_rank[self.name]
def __str__(self):
return Card.name_show.get(self.name, self.name)
__repr__ = __str__
def get_move_desc(move: List[int]):
lst = []
for i, n in enumerate(Card.all_card_name):
lst.extend([int(n)]*move[i])
key = str(sorted(lst))
return cache[key]
def group_by_type(moves: List[Dict]):
res = defaultdict(list)
for m in moves:
desc = get_move_desc(m)
res[desc.type].append( (m, desc) )
return res
o
def observation(self):
return self.game.get_state(), self.get_moves()
| true | true |
f7f89904f1d96307aafb90c5eb50ee0d0826d300 | 14,912 | py | Python | pyglet/media/codecs/ffmpeg_lib/libavcodec.py | SwineProject/pyglet | f0203870bef94d4349ad16f060c941d45270a0b5 | [
"BSD-3-Clause"
] | null | null | null | pyglet/media/codecs/ffmpeg_lib/libavcodec.py | SwineProject/pyglet | f0203870bef94d4349ad16f060c941d45270a0b5 | [
"BSD-3-Clause"
] | null | null | null | pyglet/media/codecs/ffmpeg_lib/libavcodec.py | SwineProject/pyglet | f0203870bef94d4349ad16f060c941d45270a0b5 | [
"BSD-3-Clause"
] | null | null | null | # ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2018 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''Wrapper for include/libavcodec/avcodec.h
'''
from __future__ import unicode_literals
from ctypes import (c_int, c_uint16, c_int32, c_int64, c_uint32, c_uint64,
c_uint8, c_uint, c_double, c_float, c_ubyte, c_size_t, c_char, c_char_p,
c_void_p, addressof, byref, cast, POINTER, CFUNCTYPE, Structure, Union,
create_string_buffer, memmove)
import pyglet
import pyglet.lib
from . import libavutil
avcodec = pyglet.lib.load_library(
'avcodec',
win32='avcodec-58',
darwin='avcodec.58'
)
FF_INPUT_BUFFER_PADDING_SIZE = 32
class AVPacketSideData(Structure):
_fields_ = [
('data', POINTER(c_uint8)),
('size', c_int),
('type', c_int)
]
AVBufferRef = libavutil.AVBufferRef
class AVPacket(Structure):
_fields_ = [
('buf', POINTER(AVBufferRef)),
('pts', c_int64),
('dts', c_int64),
('data', POINTER(c_uint8)),
('size', c_int),
('stream_index', c_int),
('flags', c_int),
('side_data', POINTER(AVPacketSideData)),
('side_data_elems', c_int),
('duration', c_int64),
('pos', c_int64),
('convergence_duration', c_int64) #Deprecated
]
class AVCodecParserContext(Structure): pass
AVRational = libavutil.AVRational
class AVCodecParameters(Structure):
_fields_ = [
('codec_type', c_int),
('codec_id', c_int),
('codec_tag', c_uint32),
('extradata', POINTER(c_uint8)),
('extradata_size', c_int),
('format', c_int),
('bit_rate', c_int64),
('bits_per_coded_sample', c_int),
('bits_per_raw_sample', c_int),
('profile', c_int),
('level', c_int),
('width', c_int),
('height', c_int),
('sample_aspect_ratio', AVRational),
('field_order', c_int),
('color_range', c_int),
('color_primaries', c_int),
('color_trc', c_int),
('color_space', c_int),
('chroma_location', c_int),
('video_delay', c_int),
('channel_layout', c_uint64),
('channels', c_int),
('sample_rate', c_int),
('block_align', c_int),
('frame_size', c_int),
('initial_padding', c_int),
('trailing_padding', c_int),
('seek_preroll', c_int),
]
class AVProfile(Structure):
_fields_ = [
('profile', c_int),
('name', c_char_p),
]
class AVCodecDescriptor(Structure):
_fields_ = [
('id', c_int),
('type', c_int),
('name', c_char_p),
('long_name', c_char_p),
('props', c_int),
('mime_types', c_char_p),
('profiles', POINTER(AVProfile))
]
class AVCodecInternal(Structure): pass
class AVCodec(Structure):
_fields_ = [
('name', c_char_p),
('long_name', c_char_p),
('type', c_int),
('id', c_int),
('capabilities', c_int),
('supported_framerates', POINTER(AVRational)),
('pix_fmts', POINTER(c_int)),
('supported_samplerates', POINTER(c_int)),
('sample_fmts', POINTER(c_int)),
('channel_layouts', POINTER(c_uint64)),
('max_lowres', c_uint8),
# And more...
]
class AVCodecContext(Structure): pass
class RcOverride(Structure): pass
class AVHWAccel(Structure): pass
AVClass = libavutil.AVClass
AVFrame = libavutil.AVFrame
AV_NUM_DATA_POINTERS = libavutil.AV_NUM_DATA_POINTERS
AVCodecContext._fields_ = [
('av_class', POINTER(AVClass)),
('log_level_offset', c_int),
('codec_type', c_int),
('codec', POINTER(AVCodec)),
('codec_id', c_int),
('codec_tag', c_uint),
('priv_data', c_void_p),
('internal', POINTER(AVCodecInternal)),
('opaque', c_void_p),
('bit_rate', c_int64),
('bit_rate_tolerance', c_int),
('global_quality', c_int),
('compression_level', c_int),
('flags', c_int),
('flags2', c_int),
('extradata', POINTER(c_uint8)),
('extradata_size', c_int),
('time_base', AVRational),
('ticks_per_frame', c_int),
('delay', c_int),
('width', c_int),
('height', c_int),
('coded_width', c_int),
('coded_height', c_int),
('gop_size', c_int),
('pix_fmt', c_int),
('draw_horiz_band', CFUNCTYPE(None,
POINTER(AVCodecContext), POINTER(AVFrame),
c_int*8, c_int, c_int, c_int)),
('get_format', CFUNCTYPE(c_int,
POINTER(AVCodecContext), POINTER(c_int))),
('max_b_frames', c_int),
('b_quant_factor', c_float),
('b_frame_strategy', c_int), #Deprecated
('b_quant_offset', c_float),
('has_b_frames', c_int),
('mpeg_quant', c_int), #Deprecated
('i_quant_factor', c_float),
('i_quant_offset', c_float),
('lumi_masking', c_float),
('temporal_cplx_masking', c_float),
('spatial_cplx_masking', c_float),
('p_masking', c_float),
('dark_masking', c_float),
('slice_count', c_int),
('prediction_method', c_int), #Deprecated
('slice_offset', POINTER(c_int)),
('sample_aspect_ratio', AVRational),
('me_cmp', c_int),
('me_sub_cmp', c_int),
('mb_cmp', c_int),
('ildct_cmp', c_int),
('dia_size', c_int),
('last_predictor_count', c_int),
('pre_me', c_int), #Deprecated
('me_pre_cmp', c_int),
('pre_dia_size', c_int),
('me_subpel_quality', c_int),
('me_range', c_int),
('slice_flags', c_int),
('mb_decision', c_int),
('intra_matrix', POINTER(c_uint16)),
('inter_matrix', POINTER(c_uint16)),
('scenechange_threshold', c_int), #Deprecated
('noise_reduction', c_int), #Deprecated
('intra_dc_precision', c_int),
('skip_top', c_int),
('skip_bottom', c_int),
('mb_lmin', c_int),
('mb_lmax', c_int),
('me_penalty_compensation', c_int), #Deprecated
('bidir_refine', c_int),
('brd_scale', c_int), #Deprecated
('keyint_min', c_int),
('refs', c_int),
('chromaoffset', c_int), #Deprecated
('mv0_threshold', c_int),
('b_sensitivity', c_int), #Deprecated
('color_primaries', c_int),
('color_trc', c_int),
('colorspace', c_int),
('color_range', c_int),
('chroma_sample_location', c_int),
('slices', c_int),
('field_order', c_int),
('sample_rate', c_int),
('channels', c_int),
('sample_fmt', c_int),
('frame_size', c_int),
('frame_number', c_int),
('block_align', c_int),
('cutoff', c_int),
('channel_layout', c_uint64),
('request_channel_layout', c_uint64),
('audio_service_type', c_int),
('request_sample_fmt', c_int),
('get_buffer2', CFUNCTYPE(c_int,
POINTER(AVCodecContext), POINTER(AVFrame), c_int)),
('refcounted_frames', c_int), #Deprecated
('qcompress', c_float),
('qblur', c_float),
('qmin', c_int),
('qmax', c_int),
('max_qdiff', c_int),
('rc_buffer_size', c_int),
('rc_override_count', c_int),
('rc_override', POINTER(RcOverride)),
('rc_max_rate', c_int64),
('rc_min_rate', c_int64),
('rc_max_available_vbv_use', c_float),
('rc_min_vbv_overflow_use', c_float),
('rc_initial_buffer_occupancy', c_int),
('coder_type', c_int), #Deprecated
('context_model', c_int), #Deprecated
('frame_skip_threshold', c_int), #Deprecated
('frame_skip_factor', c_int), #Deprecated
('frame_skip_exp', c_int), #Deprecated
('frame_skip_cmp', c_int), #Deprecated
('trellis', c_int),
('min_prediction_order', c_int), #Deprecated
('max_prediction_order', c_int), #Deprecated
('timecode_frame_start', c_int64), #Deprecated
('rtp_callback', CFUNCTYPE(None, #Deprecated
POINTER(AVCodecContext), c_void_p, c_int, c_int)),
('rtp_payload_size', c_int), #Deprecated
('mv_bits', c_int), #Deprecated
('header_bits', c_int), #Deprecated
('i_tex_bits', c_int), #Deprecated
('p_tex_bits', c_int), #Deprecated
('i_count', c_int), #Deprecated
('p_count', c_int), #Deprecated
('skip_count', c_int), #Deprecated
('misc_bits', c_int), #Deprecated
('frame_bits', c_int), #Deprecated
('stats_out', c_char_p),
('stats_in', c_char_p),
('workaround_bugs', c_int),
('strict_std_compliance', c_int),
('error_concealment', c_int),
('debug', c_int),
('err_recognition', c_int),
('reordered_opaque', c_int64),
('hwaccel', POINTER(AVHWAccel)),
('hwaccel_context', c_void_p),
('error', c_uint64 * AV_NUM_DATA_POINTERS),
('dct_algo', c_int),
('idct_algo', c_int),
('bits_per_coded_sample', c_int),
('bits_per_raw_sample', c_int),
('lowres', c_int),
('coded_frame', POINTER(AVFrame)), #Deprecated
('thread_count', c_int),
('thread_type', c_int),
('active_thread_type', c_int),
('thread_safe_callbacks', c_int),
('execute', CFUNCTYPE(c_int,
POINTER(AVCodecContext),
CFUNCTYPE(c_int, POINTER(AVCodecContext), c_void_p),
c_void_p, c_int, c_int, c_int)),
('execute2', CFUNCTYPE(c_int,
POINTER(AVCodecContext),
CFUNCTYPE(c_int, POINTER(AVCodecContext), c_void_p, c_int, c_int),
c_void_p, c_int, c_int)),
('nsse_weight', c_int),
('profile', c_int),
('level', c_int),
('skip_loop_filter', c_int),
('skip_idct', c_int),
('skip_frame', c_int),
('subtitle_header', POINTER(c_uint8)),
('subtitle_header_size', c_int),
('vbv_delay', c_uint64), #Deprecated
('side_data_only_packets', c_int), #Deprecated
('initial_padding', c_int),
('framerate', AVRational),
#!
('sw_pix_fmt', c_int),
('pkt_timebase', AVRational),
('codec_dexcriptor', AVCodecDescriptor),
('pts_correction_num_faulty_pts', c_int64),
('pts_correction_num_faulty_dts', c_int64),
('pts_correction_last_pts', c_int64),
('pts_correction_last_dts', c_int64),
('sub_charenc', c_char_p),
('sub_charenc_mode', c_int),
('skip_alpha', c_int),
('seek_preroll', c_int),
('debug_mv', c_int),
('chroma_intra_matrix', POINTER(c_uint16)),
('dump_separator', POINTER(c_uint8)),
('codec_whitelist', c_char_p),
('properties', c_uint),
('coded_side_data', POINTER(AVPacketSideData)),
('nb_coded_side_data', c_int),
('hw_frames_ctx', POINTER(AVBufferRef)),
('sub_text_format', c_int),
('trailing_padding', c_int),
('max_pixels', c_int64),
('hw_device_ctx', POINTER(AVBufferRef)),
('hwaccel_flags', c_int),
('apply_cropping', c_int),
('extra_hw_frames', c_int)
]
AV_CODEC_ID_VP8 = 139
AV_CODEC_ID_VP9 = 167
avcodec.av_packet_unref.argtypes = [POINTER(AVPacket)]
avcodec.av_packet_free.argtypes = [POINTER(POINTER(AVPacket))]
avcodec.av_packet_clone.restype = POINTER(AVPacket)
avcodec.av_packet_clone.argtypes = [POINTER(AVPacket)]
avcodec.av_packet_move_ref.argtypes = [POINTER(AVPacket), POINTER(AVPacket)]
avcodec.avcodec_find_decoder.restype = POINTER(AVCodec)
avcodec.avcodec_find_decoder.argtypes = [c_int]
AVDictionary = libavutil.AVDictionary
avcodec.avcodec_open2.restype = c_int
avcodec.avcodec_open2.argtypes = [POINTER(AVCodecContext),
POINTER(AVCodec),
POINTER(POINTER(AVDictionary))]
avcodec.avcodec_free_context.argtypes = [POINTER(POINTER(AVCodecContext))]
avcodec.av_packet_alloc.restype = POINTER(AVPacket)
avcodec.av_init_packet.argtypes = [POINTER(AVPacket)]
avcodec.avcodec_decode_audio4.restype = c_int
avcodec.avcodec_decode_audio4.argtypes = [POINTER(AVCodecContext),
POINTER(AVFrame), POINTER(c_int),
POINTER(AVPacket)]
avcodec.avcodec_decode_video2.restype = c_int
avcodec.avcodec_decode_video2.argtypes = [POINTER(AVCodecContext),
POINTER(AVFrame), POINTER(c_int),
POINTER(AVPacket)]
avcodec.avcodec_flush_buffers.argtypes = [POINTER(AVCodecContext)]
avcodec.avcodec_alloc_context3.restype = POINTER(AVCodecContext)
avcodec.avcodec_alloc_context3.argtypes = [POINTER(AVCodec)]
avcodec.avcodec_free_context.argtypes = [POINTER(POINTER(AVCodecContext))]
avcodec.avcodec_parameters_to_context.restype = c_int
avcodec.avcodec_parameters_to_context.argtypes = [POINTER(AVCodecContext),
POINTER(AVCodecParameters)]
avcodec.avcodec_get_name.restype = c_char_p
avcodec.avcodec_get_name.argtypes = [c_int]
avcodec.avcodec_find_decoder_by_name.restype = POINTER(AVCodec)
avcodec.avcodec_find_decoder_by_name.argtypes = [c_char_p]
__all__ = [
'avcodec',
'FF_INPUT_BUFFER_PADDING_SIZE',
'AVPacket',
'AVCodecContext',
'AV_CODEC_ID_VP8',
'AV_CODEC_ID_VP9',
]
| 37.094527 | 78 | 0.617221 |
from __future__ import unicode_literals
from ctypes import (c_int, c_uint16, c_int32, c_int64, c_uint32, c_uint64,
c_uint8, c_uint, c_double, c_float, c_ubyte, c_size_t, c_char, c_char_p,
c_void_p, addressof, byref, cast, POINTER, CFUNCTYPE, Structure, Union,
create_string_buffer, memmove)
import pyglet
import pyglet.lib
from . import libavutil
avcodec = pyglet.lib.load_library(
'avcodec',
win32='avcodec-58',
darwin='avcodec.58'
)
FF_INPUT_BUFFER_PADDING_SIZE = 32
class AVPacketSideData(Structure):
_fields_ = [
('data', POINTER(c_uint8)),
('size', c_int),
('type', c_int)
]
AVBufferRef = libavutil.AVBufferRef
class AVPacket(Structure):
_fields_ = [
('buf', POINTER(AVBufferRef)),
('pts', c_int64),
('dts', c_int64),
('data', POINTER(c_uint8)),
('size', c_int),
('stream_index', c_int),
('flags', c_int),
('side_data', POINTER(AVPacketSideData)),
('side_data_elems', c_int),
('duration', c_int64),
('pos', c_int64),
('convergence_duration', c_int64)
]
class AVCodecParserContext(Structure): pass
AVRational = libavutil.AVRational
class AVCodecParameters(Structure):
_fields_ = [
('codec_type', c_int),
('codec_id', c_int),
('codec_tag', c_uint32),
('extradata', POINTER(c_uint8)),
('extradata_size', c_int),
('format', c_int),
('bit_rate', c_int64),
('bits_per_coded_sample', c_int),
('bits_per_raw_sample', c_int),
('profile', c_int),
('level', c_int),
('width', c_int),
('height', c_int),
('sample_aspect_ratio', AVRational),
('field_order', c_int),
('color_range', c_int),
('color_primaries', c_int),
('color_trc', c_int),
('color_space', c_int),
('chroma_location', c_int),
('video_delay', c_int),
('channel_layout', c_uint64),
('channels', c_int),
('sample_rate', c_int),
('block_align', c_int),
('frame_size', c_int),
('initial_padding', c_int),
('trailing_padding', c_int),
('seek_preroll', c_int),
]
class AVProfile(Structure):
_fields_ = [
('profile', c_int),
('name', c_char_p),
]
class AVCodecDescriptor(Structure):
_fields_ = [
('id', c_int),
('type', c_int),
('name', c_char_p),
('long_name', c_char_p),
('props', c_int),
('mime_types', c_char_p),
('profiles', POINTER(AVProfile))
]
class AVCodecInternal(Structure): pass
class AVCodec(Structure):
_fields_ = [
('name', c_char_p),
('long_name', c_char_p),
('type', c_int),
('id', c_int),
('capabilities', c_int),
('supported_framerates', POINTER(AVRational)),
('pix_fmts', POINTER(c_int)),
('supported_samplerates', POINTER(c_int)),
('sample_fmts', POINTER(c_int)),
('channel_layouts', POINTER(c_uint64)),
('max_lowres', c_uint8),
]
class AVCodecContext(Structure): pass
class RcOverride(Structure): pass
class AVHWAccel(Structure): pass
AVClass = libavutil.AVClass
AVFrame = libavutil.AVFrame
AV_NUM_DATA_POINTERS = libavutil.AV_NUM_DATA_POINTERS
AVCodecContext._fields_ = [
('av_class', POINTER(AVClass)),
('log_level_offset', c_int),
('codec_type', c_int),
('codec', POINTER(AVCodec)),
('codec_id', c_int),
('codec_tag', c_uint),
('priv_data', c_void_p),
('internal', POINTER(AVCodecInternal)),
('opaque', c_void_p),
('bit_rate', c_int64),
('bit_rate_tolerance', c_int),
('global_quality', c_int),
('compression_level', c_int),
('flags', c_int),
('flags2', c_int),
('extradata', POINTER(c_uint8)),
('extradata_size', c_int),
('time_base', AVRational),
('ticks_per_frame', c_int),
('delay', c_int),
('width', c_int),
('height', c_int),
('coded_width', c_int),
('coded_height', c_int),
('gop_size', c_int),
('pix_fmt', c_int),
('draw_horiz_band', CFUNCTYPE(None,
POINTER(AVCodecContext), POINTER(AVFrame),
c_int*8, c_int, c_int, c_int)),
('get_format', CFUNCTYPE(c_int,
POINTER(AVCodecContext), POINTER(c_int))),
('max_b_frames', c_int),
('b_quant_factor', c_float),
('b_frame_strategy', c_int),
('b_quant_offset', c_float),
('has_b_frames', c_int),
('mpeg_quant', c_int),
('i_quant_factor', c_float),
('i_quant_offset', c_float),
('lumi_masking', c_float),
('temporal_cplx_masking', c_float),
('spatial_cplx_masking', c_float),
('p_masking', c_float),
('dark_masking', c_float),
('slice_count', c_int),
('prediction_method', c_int),
('slice_offset', POINTER(c_int)),
('sample_aspect_ratio', AVRational),
('me_cmp', c_int),
('me_sub_cmp', c_int),
('mb_cmp', c_int),
('ildct_cmp', c_int),
('dia_size', c_int),
('last_predictor_count', c_int),
('pre_me', c_int),
('me_pre_cmp', c_int),
('pre_dia_size', c_int),
('me_subpel_quality', c_int),
('me_range', c_int),
('slice_flags', c_int),
('mb_decision', c_int),
('intra_matrix', POINTER(c_uint16)),
('inter_matrix', POINTER(c_uint16)),
('scenechange_threshold', c_int),
('noise_reduction', c_int),
('intra_dc_precision', c_int),
('skip_top', c_int),
('skip_bottom', c_int),
('mb_lmin', c_int),
('mb_lmax', c_int),
('me_penalty_compensation', c_int),
('bidir_refine', c_int),
('brd_scale', c_int),
('keyint_min', c_int),
('refs', c_int),
('chromaoffset', c_int),
('mv0_threshold', c_int),
('b_sensitivity', c_int),
('color_primaries', c_int),
('color_trc', c_int),
('colorspace', c_int),
('color_range', c_int),
('chroma_sample_location', c_int),
('slices', c_int),
('field_order', c_int),
('sample_rate', c_int),
('channels', c_int),
('sample_fmt', c_int),
('frame_size', c_int),
('frame_number', c_int),
('block_align', c_int),
('cutoff', c_int),
('channel_layout', c_uint64),
('request_channel_layout', c_uint64),
('audio_service_type', c_int),
('request_sample_fmt', c_int),
('get_buffer2', CFUNCTYPE(c_int,
POINTER(AVCodecContext), POINTER(AVFrame), c_int)),
('refcounted_frames', c_int),
('qcompress', c_float),
('qblur', c_float),
('qmin', c_int),
('qmax', c_int),
('max_qdiff', c_int),
('rc_buffer_size', c_int),
('rc_override_count', c_int),
('rc_override', POINTER(RcOverride)),
('rc_max_rate', c_int64),
('rc_min_rate', c_int64),
('rc_max_available_vbv_use', c_float),
('rc_min_vbv_overflow_use', c_float),
('rc_initial_buffer_occupancy', c_int),
('coder_type', c_int),
('context_model', c_int),
('frame_skip_threshold', c_int),
('frame_skip_factor', c_int),
('frame_skip_exp', c_int),
('frame_skip_cmp', c_int),
('trellis', c_int),
('min_prediction_order', c_int),
('max_prediction_order', c_int),
('timecode_frame_start', c_int64),
('rtp_callback', CFUNCTYPE(None,
POINTER(AVCodecContext), c_void_p, c_int, c_int)),
('rtp_payload_size', c_int),
('mv_bits', c_int),
('header_bits', c_int),
('i_tex_bits', c_int),
('p_tex_bits', c_int),
('i_count', c_int),
('p_count', c_int),
('skip_count', c_int),
('misc_bits', c_int),
('frame_bits', c_int),
('stats_out', c_char_p),
('stats_in', c_char_p),
('workaround_bugs', c_int),
('strict_std_compliance', c_int),
('error_concealment', c_int),
('debug', c_int),
('err_recognition', c_int),
('reordered_opaque', c_int64),
('hwaccel', POINTER(AVHWAccel)),
('hwaccel_context', c_void_p),
('error', c_uint64 * AV_NUM_DATA_POINTERS),
('dct_algo', c_int),
('idct_algo', c_int),
('bits_per_coded_sample', c_int),
('bits_per_raw_sample', c_int),
('lowres', c_int),
('coded_frame', POINTER(AVFrame)),
('thread_count', c_int),
('thread_type', c_int),
('active_thread_type', c_int),
('thread_safe_callbacks', c_int),
('execute', CFUNCTYPE(c_int,
POINTER(AVCodecContext),
CFUNCTYPE(c_int, POINTER(AVCodecContext), c_void_p),
c_void_p, c_int, c_int, c_int)),
('execute2', CFUNCTYPE(c_int,
POINTER(AVCodecContext),
CFUNCTYPE(c_int, POINTER(AVCodecContext), c_void_p, c_int, c_int),
c_void_p, c_int, c_int)),
('nsse_weight', c_int),
('profile', c_int),
('level', c_int),
('skip_loop_filter', c_int),
('skip_idct', c_int),
('skip_frame', c_int),
('subtitle_header', POINTER(c_uint8)),
('subtitle_header_size', c_int),
('vbv_delay', c_uint64),
('side_data_only_packets', c_int),
('initial_padding', c_int),
('framerate', AVRational),
('sw_pix_fmt', c_int),
('pkt_timebase', AVRational),
('codec_dexcriptor', AVCodecDescriptor),
('pts_correction_num_faulty_pts', c_int64),
('pts_correction_num_faulty_dts', c_int64),
('pts_correction_last_pts', c_int64),
('pts_correction_last_dts', c_int64),
('sub_charenc', c_char_p),
('sub_charenc_mode', c_int),
('skip_alpha', c_int),
('seek_preroll', c_int),
('debug_mv', c_int),
('chroma_intra_matrix', POINTER(c_uint16)),
('dump_separator', POINTER(c_uint8)),
('codec_whitelist', c_char_p),
('properties', c_uint),
('coded_side_data', POINTER(AVPacketSideData)),
('nb_coded_side_data', c_int),
('hw_frames_ctx', POINTER(AVBufferRef)),
('sub_text_format', c_int),
('trailing_padding', c_int),
('max_pixels', c_int64),
('hw_device_ctx', POINTER(AVBufferRef)),
('hwaccel_flags', c_int),
('apply_cropping', c_int),
('extra_hw_frames', c_int)
]
AV_CODEC_ID_VP8 = 139
AV_CODEC_ID_VP9 = 167
avcodec.av_packet_unref.argtypes = [POINTER(AVPacket)]
avcodec.av_packet_free.argtypes = [POINTER(POINTER(AVPacket))]
avcodec.av_packet_clone.restype = POINTER(AVPacket)
avcodec.av_packet_clone.argtypes = [POINTER(AVPacket)]
avcodec.av_packet_move_ref.argtypes = [POINTER(AVPacket), POINTER(AVPacket)]
avcodec.avcodec_find_decoder.restype = POINTER(AVCodec)
avcodec.avcodec_find_decoder.argtypes = [c_int]
AVDictionary = libavutil.AVDictionary
avcodec.avcodec_open2.restype = c_int
avcodec.avcodec_open2.argtypes = [POINTER(AVCodecContext),
POINTER(AVCodec),
POINTER(POINTER(AVDictionary))]
avcodec.avcodec_free_context.argtypes = [POINTER(POINTER(AVCodecContext))]
avcodec.av_packet_alloc.restype = POINTER(AVPacket)
avcodec.av_init_packet.argtypes = [POINTER(AVPacket)]
avcodec.avcodec_decode_audio4.restype = c_int
avcodec.avcodec_decode_audio4.argtypes = [POINTER(AVCodecContext),
POINTER(AVFrame), POINTER(c_int),
POINTER(AVPacket)]
avcodec.avcodec_decode_video2.restype = c_int
avcodec.avcodec_decode_video2.argtypes = [POINTER(AVCodecContext),
POINTER(AVFrame), POINTER(c_int),
POINTER(AVPacket)]
avcodec.avcodec_flush_buffers.argtypes = [POINTER(AVCodecContext)]
avcodec.avcodec_alloc_context3.restype = POINTER(AVCodecContext)
avcodec.avcodec_alloc_context3.argtypes = [POINTER(AVCodec)]
avcodec.avcodec_free_context.argtypes = [POINTER(POINTER(AVCodecContext))]
avcodec.avcodec_parameters_to_context.restype = c_int
avcodec.avcodec_parameters_to_context.argtypes = [POINTER(AVCodecContext),
POINTER(AVCodecParameters)]
avcodec.avcodec_get_name.restype = c_char_p
avcodec.avcodec_get_name.argtypes = [c_int]
avcodec.avcodec_find_decoder_by_name.restype = POINTER(AVCodec)
avcodec.avcodec_find_decoder_by_name.argtypes = [c_char_p]
__all__ = [
'avcodec',
'FF_INPUT_BUFFER_PADDING_SIZE',
'AVPacket',
'AVCodecContext',
'AV_CODEC_ID_VP8',
'AV_CODEC_ID_VP9',
]
| true | true |
f7f89913ef61a19e920312701c7308a476710352 | 21,421 | py | Python | django/http/request.py | shinshin86/django | 5cc81cd9eb69f5f7a711412c02039b435c393135 | [
"PSF-2.0",
"BSD-3-Clause"
] | 1 | 2019-11-17T04:10:38.000Z | 2019-11-17T04:10:38.000Z | django/http/request.py | Blaahborgh/django | c591bc3ccece1514d6b419826c7fa36ada9d9213 | [
"PSF-2.0",
"BSD-3-Clause"
] | 1 | 2019-09-27T16:40:34.000Z | 2019-09-27T16:40:34.000Z | django/http/request.py | Blaahborgh/django | c591bc3ccece1514d6b419826c7fa36ada9d9213 | [
"PSF-2.0",
"BSD-3-Clause"
] | 1 | 2020-11-04T08:47:02.000Z | 2020-11-04T08:47:02.000Z | import copy
import re
import warnings
from io import BytesIO
from itertools import chain
from urllib.parse import quote, urlencode, urljoin, urlsplit
from django.conf import settings
from django.core import signing
from django.core.exceptions import (
DisallowedHost, ImproperlyConfigured, RequestDataTooBig,
)
from django.core.files import uploadhandler
from django.http.multipartparser import MultiPartParser, MultiPartParserError
from django.utils.datastructures import ImmutableList, MultiValueDict
from django.utils.deprecation import RemovedInDjango30Warning
from django.utils.encoding import escape_uri_path, iri_to_uri
from django.utils.functional import cached_property
from django.utils.http import is_same_domain, limited_parse_qsl
RAISE_ERROR = object()
host_validation_re = re.compile(r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9\.:]+\])(:\d+)?$")
class UnreadablePostError(IOError):
pass
class RawPostDataException(Exception):
"""
You cannot access raw_post_data from a request that has
multipart/* POST data if it has been accessed via POST,
FILES, etc..
"""
pass
class HttpRequest:
"""A basic HTTP request."""
# The encoding used in GET/POST dicts. None means use default setting.
_encoding = None
_upload_handlers = []
def __init__(self):
# WARNING: The `WSGIRequest` subclass doesn't call `super`.
# Any variable assignment made here should also happen in
# `WSGIRequest.__init__()`.
self.GET = QueryDict(mutable=True)
self.POST = QueryDict(mutable=True)
self.COOKIES = {}
self.META = {}
self.FILES = MultiValueDict()
self.path = ''
self.path_info = ''
self.method = None
self.resolver_match = None
self._post_parse_error = False
self.content_type = None
self.content_params = None
def __repr__(self):
if self.method is None or not self.get_full_path():
return '<%s>' % self.__class__.__name__
return '<%s: %s %r>' % (self.__class__.__name__, self.method, self.get_full_path())
def _get_raw_host(self):
"""
Return the HTTP host using the environment or request headers. Skip
allowed hosts protection, so may return an insecure host.
"""
# We try three options, in order of decreasing preference.
if settings.USE_X_FORWARDED_HOST and (
'HTTP_X_FORWARDED_HOST' in self.META):
host = self.META['HTTP_X_FORWARDED_HOST']
elif 'HTTP_HOST' in self.META:
host = self.META['HTTP_HOST']
else:
# Reconstruct the host using the algorithm from PEP 333.
host = self.META['SERVER_NAME']
server_port = self.get_port()
if server_port != ('443' if self.is_secure() else '80'):
host = '%s:%s' % (host, server_port)
return host
def get_host(self):
"""Return the HTTP host using the environment or request headers."""
host = self._get_raw_host()
# Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True.
allowed_hosts = settings.ALLOWED_HOSTS
if settings.DEBUG and not allowed_hosts:
allowed_hosts = ['localhost', '127.0.0.1', '[::1]']
domain, port = split_domain_port(host)
if domain and validate_host(domain, allowed_hosts):
return host
else:
msg = "Invalid HTTP_HOST header: %r." % host
if domain:
msg += " You may need to add %r to ALLOWED_HOSTS." % domain
else:
msg += " The domain name provided is not valid according to RFC 1034/1035."
raise DisallowedHost(msg)
def get_port(self):
"""Return the port number for the request as a string."""
if settings.USE_X_FORWARDED_PORT and 'HTTP_X_FORWARDED_PORT' in self.META:
port = self.META['HTTP_X_FORWARDED_PORT']
else:
port = self.META['SERVER_PORT']
return str(port)
def get_full_path(self, force_append_slash=False):
return self._get_full_path(self.path, force_append_slash)
def get_full_path_info(self, force_append_slash=False):
return self._get_full_path(self.path_info, force_append_slash)
def _get_full_path(self, path, force_append_slash):
# RFC 3986 requires query string arguments to be in the ASCII range.
# Rather than crash if this doesn't happen, we encode defensively.
return '%s%s%s' % (
escape_uri_path(path),
'/' if force_append_slash and not path.endswith('/') else '',
('?' + iri_to_uri(self.META.get('QUERY_STRING', ''))) if self.META.get('QUERY_STRING', '') else ''
)
def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
"""
Attempt to return a signed cookie. If the signature fails or the
cookie has expired, raise an exception, unless the `default` argument
is provided, in which case return that value.
"""
try:
cookie_value = self.COOKIES[key]
except KeyError:
if default is not RAISE_ERROR:
return default
else:
raise
try:
value = signing.get_cookie_signer(salt=key + salt).unsign(
cookie_value, max_age=max_age)
except signing.BadSignature:
if default is not RAISE_ERROR:
return default
else:
raise
return value
def get_raw_uri(self):
"""
Return an absolute URI from variables available in this request. Skip
allowed hosts protection, so may return insecure URI.
"""
return '{scheme}://{host}{path}'.format(
scheme=self.scheme,
host=self._get_raw_host(),
path=self.get_full_path(),
)
def build_absolute_uri(self, location=None):
"""
Build an absolute URI from the location and the variables available in
this request. If no ``location`` is specified, bulid the absolute URI
using request.get_full_path(). If the location is absolute, convert it
to an RFC 3987 compliant URI and return it. If location is relative or
is scheme-relative (i.e., ``//example.com/``), urljoin() it to a base
URL constructed from the request variables.
"""
if location is None:
# Make it an absolute url (but schemeless and domainless) for the
# edge case that the path starts with '//'.
location = '//%s' % self.get_full_path()
bits = urlsplit(location)
if not (bits.scheme and bits.netloc):
# Handle the simple, most common case. If the location is absolute
# and a scheme or host (netloc) isn't provided, skip an expensive
# urljoin() as long as no path segments are '.' or '..'.
if (bits.path.startswith('/') and not bits.scheme and not bits.netloc and
'/./' not in bits.path and '/../' not in bits.path):
# If location starts with '//' but has no netloc, reuse the
# schema and netloc from the current request. Strip the double
# slashes and continue as if it wasn't specified.
if location.startswith('//'):
location = location[2:]
location = self._current_scheme_host + location
else:
# Join the constructed URL with the provided location, which
# allows the provided location to apply query strings to the
# base path.
location = urljoin(self._current_scheme_host + self.path, location)
return iri_to_uri(location)
@cached_property
def _current_scheme_host(self):
return '{}://{}'.format(self.scheme, self.get_host())
def _get_scheme(self):
"""
Hook for subclasses like WSGIRequest to implement. Return 'http' by
default.
"""
return 'http'
@property
def scheme(self):
if settings.SECURE_PROXY_SSL_HEADER:
try:
header, value = settings.SECURE_PROXY_SSL_HEADER
except ValueError:
raise ImproperlyConfigured(
'The SECURE_PROXY_SSL_HEADER setting must be a tuple containing two values.'
)
if self.META.get(header) == value:
return 'https'
return self._get_scheme()
def is_secure(self):
return self.scheme == 'https'
def is_ajax(self):
return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
@property
def encoding(self):
return self._encoding
@encoding.setter
def encoding(self, val):
"""
Set the encoding used for GET/POST accesses. If the GET or POST
dictionary has already been created, remove and recreate it on the
next access (so that it is decoded correctly).
"""
self._encoding = val
if hasattr(self, 'GET'):
del self.GET
if hasattr(self, '_post'):
del self._post
def _initialize_handlers(self):
self._upload_handlers = [uploadhandler.load_handler(handler, self)
for handler in settings.FILE_UPLOAD_HANDLERS]
@property
def upload_handlers(self):
if not self._upload_handlers:
# If there are no upload handlers defined, initialize them from settings.
self._initialize_handlers()
return self._upload_handlers
@upload_handlers.setter
def upload_handlers(self, upload_handlers):
if hasattr(self, '_files'):
raise AttributeError("You cannot set the upload handlers after the upload has been processed.")
self._upload_handlers = upload_handlers
def parse_file_upload(self, META, post_data):
"""Return a tuple of (POST QueryDict, FILES MultiValueDict)."""
self.upload_handlers = ImmutableList(
self.upload_handlers,
warning="You cannot alter upload handlers after the upload has been processed."
)
parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
return parser.parse()
@property
def body(self):
if not hasattr(self, '_body'):
if self._read_started:
raise RawPostDataException("You cannot access body after reading from request's data stream")
# Limit the maximum request data size that will be handled in-memory.
if (settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None and
int(self.META.get('CONTENT_LENGTH') or 0) > settings.DATA_UPLOAD_MAX_MEMORY_SIZE):
raise RequestDataTooBig('Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE.')
try:
self._body = self.read()
except IOError as e:
raise UnreadablePostError(*e.args) from e
self._stream = BytesIO(self._body)
return self._body
def _mark_post_parse_error(self):
self._post = QueryDict()
self._files = MultiValueDict()
self._post_parse_error = True
def _load_post_and_files(self):
"""Populate self._post and self._files if the content-type is a form type"""
if self.method != 'POST':
self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict()
return
if self._read_started and not hasattr(self, '_body'):
self._mark_post_parse_error()
return
if self.content_type == 'multipart/form-data':
if hasattr(self, '_body'):
# Use already read data
data = BytesIO(self._body)
else:
data = self
try:
self._post, self._files = self.parse_file_upload(self.META, data)
except MultiPartParserError:
# An error occurred while parsing POST data. Since when
# formatting the error the request handler might access
# self.POST, set self._post and self._file to prevent
# attempts to parse POST data again.
# Mark that an error occurred. This allows self.__repr__ to
# be explicit about it instead of simply representing an
# empty POST
self._mark_post_parse_error()
raise
elif self.content_type == 'application/x-www-form-urlencoded':
self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()
else:
self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict()
def close(self):
if hasattr(self, '_files'):
for f in chain.from_iterable(l[1] for l in self._files.lists()):
f.close()
# File-like and iterator interface.
#
# Expects self._stream to be set to an appropriate source of bytes by
# a corresponding request subclass (e.g. WSGIRequest).
# Also when request data has already been read by request.POST or
# request.body, self._stream points to a BytesIO instance
# containing that data.
def read(self, *args, **kwargs):
self._read_started = True
try:
return self._stream.read(*args, **kwargs)
except IOError as e:
raise UnreadablePostError(*e.args) from e
def readline(self, *args, **kwargs):
self._read_started = True
try:
return self._stream.readline(*args, **kwargs)
except IOError as e:
raise UnreadablePostError(*e.args) from e
def __iter__(self):
while True:
buf = self.readline()
if not buf:
break
yield buf
def xreadlines(self):
warnings.warn(
'HttpRequest.xreadlines() is deprecated in favor of iterating the '
'request.', RemovedInDjango30Warning, stacklevel=2,
)
yield from self
def readlines(self):
return list(self)
class QueryDict(MultiValueDict):
"""
A specialized MultiValueDict which represents a query string.
A QueryDict can be used to represent GET or POST data. It subclasses
MultiValueDict since keys in such data can be repeated, for instance
in the data from a form with a <select multiple> field.
By default QueryDicts are immutable, though the copy() method
will always return a mutable copy.
Both keys and values set on this class are converted from the given encoding
(DEFAULT_CHARSET by default) to str.
"""
# These are both reset in __init__, but is specified here at the class
# level so that unpickling will have valid values
_mutable = True
_encoding = None
def __init__(self, query_string=None, mutable=False, encoding=None):
super().__init__()
self.encoding = encoding or settings.DEFAULT_CHARSET
query_string = query_string or ''
parse_qsl_kwargs = {
'keep_blank_values': True,
'fields_limit': settings.DATA_UPLOAD_MAX_NUMBER_FIELDS,
'encoding': self.encoding,
}
if isinstance(query_string, bytes):
# query_string normally contains URL-encoded data, a subset of ASCII.
try:
query_string = query_string.decode(self.encoding)
except UnicodeDecodeError:
# ... but some user agents are misbehaving :-(
query_string = query_string.decode('iso-8859-1')
for key, value in limited_parse_qsl(query_string, **parse_qsl_kwargs):
self.appendlist(key, value)
self._mutable = mutable
@classmethod
def fromkeys(cls, iterable, value='', mutable=False, encoding=None):
"""
Return a new QueryDict with keys (may be repeated) from an iterable and
values from value.
"""
q = cls('', mutable=True, encoding=encoding)
for key in iterable:
q.appendlist(key, value)
if not mutable:
q._mutable = False
return q
@property
def encoding(self):
if self._encoding is None:
self._encoding = settings.DEFAULT_CHARSET
return self._encoding
@encoding.setter
def encoding(self, value):
self._encoding = value
def _assert_mutable(self):
if not self._mutable:
raise AttributeError("This QueryDict instance is immutable")
def __setitem__(self, key, value):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
value = bytes_to_text(value, self.encoding)
super().__setitem__(key, value)
def __delitem__(self, key):
self._assert_mutable()
super().__delitem__(key)
def __copy__(self):
result = self.__class__('', mutable=True, encoding=self.encoding)
for key, value in self.lists():
result.setlist(key, value)
return result
def __deepcopy__(self, memo):
result = self.__class__('', mutable=True, encoding=self.encoding)
memo[id(self)] = result
for key, value in self.lists():
result.setlist(copy.deepcopy(key, memo), copy.deepcopy(value, memo))
return result
def setlist(self, key, list_):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
list_ = [bytes_to_text(elt, self.encoding) for elt in list_]
super().setlist(key, list_)
def setlistdefault(self, key, default_list=None):
self._assert_mutable()
return super().setlistdefault(key, default_list)
def appendlist(self, key, value):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
value = bytes_to_text(value, self.encoding)
super().appendlist(key, value)
def pop(self, key, *args):
self._assert_mutable()
return super().pop(key, *args)
def popitem(self):
self._assert_mutable()
return super().popitem()
def clear(self):
self._assert_mutable()
super().clear()
def setdefault(self, key, default=None):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
default = bytes_to_text(default, self.encoding)
return super().setdefault(key, default)
def copy(self):
"""Return a mutable copy of this object."""
return self.__deepcopy__({})
def urlencode(self, safe=None):
"""
Return an encoded string of all query string arguments.
`safe` specifies characters which don't require quoting, for example::
>>> q = QueryDict(mutable=True)
>>> q['next'] = '/a&b/'
>>> q.urlencode()
'next=%2Fa%26b%2F'
>>> q.urlencode(safe='/')
'next=/a%26b/'
"""
output = []
if safe:
safe = safe.encode(self.encoding)
def encode(k, v):
return '%s=%s' % ((quote(k, safe), quote(v, safe)))
else:
def encode(k, v):
return urlencode({k: v})
for k, list_ in self.lists():
output.extend(
encode(k.encode(self.encoding), v.encode(self.encoding))
for v in list_
)
return '&'.join(output)
# It's neither necessary nor appropriate to use
# django.utils.encoding.force_text for parsing URLs and form inputs. Thus,
# this slightly more restricted function, used by QueryDict.
def bytes_to_text(s, encoding):
"""
Convert bytes objects to strings, using the given encoding. Illegally
encoded input characters are replaced with Unicode "unknown" codepoint
(\ufffd).
Return any non-bytes objects without change.
"""
if isinstance(s, bytes):
return str(s, encoding, 'replace')
else:
return s
def split_domain_port(host):
"""
Return a (domain, port) tuple from a given host.
Returned domain is lower-cased. If the host is invalid, the domain will be
empty.
"""
host = host.lower()
if not host_validation_re.match(host):
return '', ''
if host[-1] == ']':
# It's an IPv6 address without a port.
return host, ''
bits = host.rsplit(':', 1)
domain, port = bits if len(bits) == 2 else (bits[0], '')
# Remove a trailing dot (if present) from the domain.
domain = domain[:-1] if domain.endswith('.') else domain
return domain, port
def validate_host(host, allowed_hosts):
"""
Validate the given host for this site.
Check that the host looks valid and matches a host or host pattern in the
given list of ``allowed_hosts``. Any pattern beginning with a period
matches a domain and all its subdomains (e.g. ``.example.com`` matches
``example.com`` and any subdomain), ``*`` matches anything, and anything
else must match exactly.
Note: This function assumes that the given host is lower-cased and has
already had the port, if any, stripped off.
Return ``True`` for a valid host, ``False`` otherwise.
"""
return any(pattern == '*' or is_same_domain(host, pattern) for pattern in allowed_hosts)
| 36.679795 | 110 | 0.617151 | import copy
import re
import warnings
from io import BytesIO
from itertools import chain
from urllib.parse import quote, urlencode, urljoin, urlsplit
from django.conf import settings
from django.core import signing
from django.core.exceptions import (
DisallowedHost, ImproperlyConfigured, RequestDataTooBig,
)
from django.core.files import uploadhandler
from django.http.multipartparser import MultiPartParser, MultiPartParserError
from django.utils.datastructures import ImmutableList, MultiValueDict
from django.utils.deprecation import RemovedInDjango30Warning
from django.utils.encoding import escape_uri_path, iri_to_uri
from django.utils.functional import cached_property
from django.utils.http import is_same_domain, limited_parse_qsl
RAISE_ERROR = object()
host_validation_re = re.compile(r"^([a-z0-9.-]+|\[[a-f0-9]*:[a-f0-9\.:]+\])(:\d+)?$")
class UnreadablePostError(IOError):
pass
class RawPostDataException(Exception):
pass
class HttpRequest:
_encoding = None
_upload_handlers = []
def __init__(self):
# Any variable assignment made here should also happen in
# `WSGIRequest.__init__()`.
self.GET = QueryDict(mutable=True)
self.POST = QueryDict(mutable=True)
self.COOKIES = {}
self.META = {}
self.FILES = MultiValueDict()
self.path = ''
self.path_info = ''
self.method = None
self.resolver_match = None
self._post_parse_error = False
self.content_type = None
self.content_params = None
def __repr__(self):
if self.method is None or not self.get_full_path():
return '<%s>' % self.__class__.__name__
return '<%s: %s %r>' % (self.__class__.__name__, self.method, self.get_full_path())
def _get_raw_host(self):
# We try three options, in order of decreasing preference.
if settings.USE_X_FORWARDED_HOST and (
'HTTP_X_FORWARDED_HOST' in self.META):
host = self.META['HTTP_X_FORWARDED_HOST']
elif 'HTTP_HOST' in self.META:
host = self.META['HTTP_HOST']
else:
# Reconstruct the host using the algorithm from PEP 333.
host = self.META['SERVER_NAME']
server_port = self.get_port()
if server_port != ('443' if self.is_secure() else '80'):
host = '%s:%s' % (host, server_port)
return host
def get_host(self):
host = self._get_raw_host()
# Allow variants of localhost if ALLOWED_HOSTS is empty and DEBUG=True.
allowed_hosts = settings.ALLOWED_HOSTS
if settings.DEBUG and not allowed_hosts:
allowed_hosts = ['localhost', '127.0.0.1', '[::1]']
domain, port = split_domain_port(host)
if domain and validate_host(domain, allowed_hosts):
return host
else:
msg = "Invalid HTTP_HOST header: %r." % host
if domain:
msg += " You may need to add %r to ALLOWED_HOSTS." % domain
else:
msg += " The domain name provided is not valid according to RFC 1034/1035."
raise DisallowedHost(msg)
def get_port(self):
if settings.USE_X_FORWARDED_PORT and 'HTTP_X_FORWARDED_PORT' in self.META:
port = self.META['HTTP_X_FORWARDED_PORT']
else:
port = self.META['SERVER_PORT']
return str(port)
def get_full_path(self, force_append_slash=False):
return self._get_full_path(self.path, force_append_slash)
def get_full_path_info(self, force_append_slash=False):
return self._get_full_path(self.path_info, force_append_slash)
def _get_full_path(self, path, force_append_slash):
# RFC 3986 requires query string arguments to be in the ASCII range.
# Rather than crash if this doesn't happen, we encode defensively.
return '%s%s%s' % (
escape_uri_path(path),
'/' if force_append_slash and not path.endswith('/') else '',
('?' + iri_to_uri(self.META.get('QUERY_STRING', ''))) if self.META.get('QUERY_STRING', '') else ''
)
def get_signed_cookie(self, key, default=RAISE_ERROR, salt='', max_age=None):
try:
cookie_value = self.COOKIES[key]
except KeyError:
if default is not RAISE_ERROR:
return default
else:
raise
try:
value = signing.get_cookie_signer(salt=key + salt).unsign(
cookie_value, max_age=max_age)
except signing.BadSignature:
if default is not RAISE_ERROR:
return default
else:
raise
return value
def get_raw_uri(self):
return '{scheme}://{host}{path}'.format(
scheme=self.scheme,
host=self._get_raw_host(),
path=self.get_full_path(),
)
def build_absolute_uri(self, location=None):
if location is None:
location = '//%s' % self.get_full_path()
bits = urlsplit(location)
if not (bits.scheme and bits.netloc):
# urljoin() as long as no path segments are '.' or '..'.
if (bits.path.startswith('/') and not bits.scheme and not bits.netloc and
'/./' not in bits.path and '/../' not in bits.path):
# If location starts with '//' but has no netloc, reuse the
# schema and netloc from the current request. Strip the double
# slashes and continue as if it wasn't specified.
if location.startswith('//'):
location = location[2:]
location = self._current_scheme_host + location
else:
location = urljoin(self._current_scheme_host + self.path, location)
return iri_to_uri(location)
@cached_property
def _current_scheme_host(self):
return '{}://{}'.format(self.scheme, self.get_host())
def _get_scheme(self):
return 'http'
@property
def scheme(self):
if settings.SECURE_PROXY_SSL_HEADER:
try:
header, value = settings.SECURE_PROXY_SSL_HEADER
except ValueError:
raise ImproperlyConfigured(
'The SECURE_PROXY_SSL_HEADER setting must be a tuple containing two values.'
)
if self.META.get(header) == value:
return 'https'
return self._get_scheme()
def is_secure(self):
return self.scheme == 'https'
def is_ajax(self):
return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
@property
def encoding(self):
return self._encoding
@encoding.setter
def encoding(self, val):
self._encoding = val
if hasattr(self, 'GET'):
del self.GET
if hasattr(self, '_post'):
del self._post
def _initialize_handlers(self):
self._upload_handlers = [uploadhandler.load_handler(handler, self)
for handler in settings.FILE_UPLOAD_HANDLERS]
@property
def upload_handlers(self):
if not self._upload_handlers:
self._initialize_handlers()
return self._upload_handlers
@upload_handlers.setter
def upload_handlers(self, upload_handlers):
if hasattr(self, '_files'):
raise AttributeError("You cannot set the upload handlers after the upload has been processed.")
self._upload_handlers = upload_handlers
def parse_file_upload(self, META, post_data):
self.upload_handlers = ImmutableList(
self.upload_handlers,
warning="You cannot alter upload handlers after the upload has been processed."
)
parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
return parser.parse()
@property
def body(self):
if not hasattr(self, '_body'):
if self._read_started:
raise RawPostDataException("You cannot access body after reading from request's data stream")
# Limit the maximum request data size that will be handled in-memory.
if (settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None and
int(self.META.get('CONTENT_LENGTH') or 0) > settings.DATA_UPLOAD_MAX_MEMORY_SIZE):
raise RequestDataTooBig('Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE.')
try:
self._body = self.read()
except IOError as e:
raise UnreadablePostError(*e.args) from e
self._stream = BytesIO(self._body)
return self._body
def _mark_post_parse_error(self):
self._post = QueryDict()
self._files = MultiValueDict()
self._post_parse_error = True
def _load_post_and_files(self):
if self.method != 'POST':
self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict()
return
if self._read_started and not hasattr(self, '_body'):
self._mark_post_parse_error()
return
if self.content_type == 'multipart/form-data':
if hasattr(self, '_body'):
# Use already read data
data = BytesIO(self._body)
else:
data = self
try:
self._post, self._files = self.parse_file_upload(self.META, data)
except MultiPartParserError:
# An error occurred while parsing POST data. Since when
# formatting the error the request handler might access
# self.POST, set self._post and self._file to prevent
# attempts to parse POST data again.
# Mark that an error occurred. This allows self.__repr__ to
# be explicit about it instead of simply representing an
# empty POST
self._mark_post_parse_error()
raise
elif self.content_type == 'application/x-www-form-urlencoded':
self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()
else:
self._post, self._files = QueryDict(encoding=self._encoding), MultiValueDict()
def close(self):
if hasattr(self, '_files'):
for f in chain.from_iterable(l[1] for l in self._files.lists()):
f.close()
# File-like and iterator interface.
#
# Expects self._stream to be set to an appropriate source of bytes by
# a corresponding request subclass (e.g. WSGIRequest).
# Also when request data has already been read by request.POST or
# request.body, self._stream points to a BytesIO instance
# containing that data.
def read(self, *args, **kwargs):
self._read_started = True
try:
return self._stream.read(*args, **kwargs)
except IOError as e:
raise UnreadablePostError(*e.args) from e
def readline(self, *args, **kwargs):
self._read_started = True
try:
return self._stream.readline(*args, **kwargs)
except IOError as e:
raise UnreadablePostError(*e.args) from e
def __iter__(self):
while True:
buf = self.readline()
if not buf:
break
yield buf
def xreadlines(self):
warnings.warn(
'HttpRequest.xreadlines() is deprecated in favor of iterating the '
'request.', RemovedInDjango30Warning, stacklevel=2,
)
yield from self
def readlines(self):
return list(self)
class QueryDict(MultiValueDict):
# These are both reset in __init__, but is specified here at the class
# level so that unpickling will have valid values
_mutable = True
_encoding = None
def __init__(self, query_string=None, mutable=False, encoding=None):
super().__init__()
self.encoding = encoding or settings.DEFAULT_CHARSET
query_string = query_string or ''
parse_qsl_kwargs = {
'keep_blank_values': True,
'fields_limit': settings.DATA_UPLOAD_MAX_NUMBER_FIELDS,
'encoding': self.encoding,
}
if isinstance(query_string, bytes):
# query_string normally contains URL-encoded data, a subset of ASCII.
try:
query_string = query_string.decode(self.encoding)
except UnicodeDecodeError:
# ... but some user agents are misbehaving :-(
query_string = query_string.decode('iso-8859-1')
for key, value in limited_parse_qsl(query_string, **parse_qsl_kwargs):
self.appendlist(key, value)
self._mutable = mutable
@classmethod
def fromkeys(cls, iterable, value='', mutable=False, encoding=None):
q = cls('', mutable=True, encoding=encoding)
for key in iterable:
q.appendlist(key, value)
if not mutable:
q._mutable = False
return q
@property
def encoding(self):
if self._encoding is None:
self._encoding = settings.DEFAULT_CHARSET
return self._encoding
@encoding.setter
def encoding(self, value):
self._encoding = value
def _assert_mutable(self):
if not self._mutable:
raise AttributeError("This QueryDict instance is immutable")
def __setitem__(self, key, value):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
value = bytes_to_text(value, self.encoding)
super().__setitem__(key, value)
def __delitem__(self, key):
self._assert_mutable()
super().__delitem__(key)
def __copy__(self):
result = self.__class__('', mutable=True, encoding=self.encoding)
for key, value in self.lists():
result.setlist(key, value)
return result
def __deepcopy__(self, memo):
result = self.__class__('', mutable=True, encoding=self.encoding)
memo[id(self)] = result
for key, value in self.lists():
result.setlist(copy.deepcopy(key, memo), copy.deepcopy(value, memo))
return result
def setlist(self, key, list_):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
list_ = [bytes_to_text(elt, self.encoding) for elt in list_]
super().setlist(key, list_)
def setlistdefault(self, key, default_list=None):
self._assert_mutable()
return super().setlistdefault(key, default_list)
def appendlist(self, key, value):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
value = bytes_to_text(value, self.encoding)
super().appendlist(key, value)
def pop(self, key, *args):
self._assert_mutable()
return super().pop(key, *args)
def popitem(self):
self._assert_mutable()
return super().popitem()
def clear(self):
self._assert_mutable()
super().clear()
def setdefault(self, key, default=None):
self._assert_mutable()
key = bytes_to_text(key, self.encoding)
default = bytes_to_text(default, self.encoding)
return super().setdefault(key, default)
def copy(self):
return self.__deepcopy__({})
def urlencode(self, safe=None):
output = []
if safe:
safe = safe.encode(self.encoding)
def encode(k, v):
return '%s=%s' % ((quote(k, safe), quote(v, safe)))
else:
def encode(k, v):
return urlencode({k: v})
for k, list_ in self.lists():
output.extend(
encode(k.encode(self.encoding), v.encode(self.encoding))
for v in list_
)
return '&'.join(output)
# It's neither necessary nor appropriate to use
def bytes_to_text(s, encoding):
if isinstance(s, bytes):
return str(s, encoding, 'replace')
else:
return s
def split_domain_port(host):
host = host.lower()
if not host_validation_re.match(host):
return '', ''
if host[-1] == ']':
return host, ''
bits = host.rsplit(':', 1)
domain, port = bits if len(bits) == 2 else (bits[0], '')
# Remove a trailing dot (if present) from the domain.
domain = domain[:-1] if domain.endswith('.') else domain
return domain, port
def validate_host(host, allowed_hosts):
return any(pattern == '*' or is_same_domain(host, pattern) for pattern in allowed_hosts)
| true | true |
f7f899b571678f51066371b9a5513d9439a051fd | 424 | py | Python | meta_blocks/models/base.py | alshedivat/meta-blocks | 6f6d93dfaab75766e8afdf9eb2fad17dc79218f2 | [
"BSD-3-Clause"
] | 124 | 2020-04-10T00:55:19.000Z | 2022-03-12T13:11:01.000Z | meta_blocks/models/base.py | meteozay/meta-blocks | 6f6d93dfaab75766e8afdf9eb2fad17dc79218f2 | [
"BSD-3-Clause"
] | 2 | 2020-04-10T17:28:42.000Z | 2020-05-12T16:07:38.000Z | meta_blocks/models/base.py | meteozay/meta-blocks | 6f6d93dfaab75766e8afdf9eb2fad17dc79218f2 | [
"BSD-3-Clause"
] | 8 | 2020-04-11T04:40:47.000Z | 2021-02-17T23:52:21.000Z | """Base classes for models."""
class Model:
"""The base class for models.
Models consist of a collection of internally built :class:`Network` objects
and define methods for building outputs (e.g., logits) and losses.
The specific outputs and losses the model builds depend on the type
of the model (i.e., classifier, regressor, policy, etc.).
This base class is used for typing purposes.
"""
| 30.285714 | 79 | 0.698113 |
class Model:
| true | true |
f7f89a07942a5e41d6650d1635029d9c61398cc3 | 2,455 | py | Python | py/buck/zip/munger.py | illicitonion/buck | 0336e37a5d9da94b6dcdf6ab78711c1788616ad0 | [
"Apache-2.0"
] | 1 | 2022-01-25T13:13:09.000Z | 2022-01-25T13:13:09.000Z | py/buck/zip/munger.py | monaka/buck | 5bf0591e649158237fe7d8523f11380e4f54bdf4 | [
"Apache-2.0"
] | null | null | null | py/buck/zip/munger.py | monaka/buck | 5bf0591e649158237fe7d8523f11380e4f54bdf4 | [
"Apache-2.0"
] | 1 | 2019-03-18T15:21:47.000Z | 2019-03-18T15:21:47.000Z | # Copyright 2015-present Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import contextlib
import os
import optparse
import shutil
import sys
import tempfile
import zipfile
def main():
parser = optparse.OptionParser()
parser.add_option('--input')
parser.add_option('--output')
parser.add_option(
'--include-path',
action='append',
default=[])
parser.add_option(
'--exclude-path',
action='append',
default=[])
options, _ = parser.parse_args()
process_jar(options.input, options.output, options.include_path, options.exclude_path)
def process_jar(infile, outfile, include_paths, exclude_paths):
with tempdir() as temp_dir:
# First extract all the files we need from the jar.
with contextlib.closing(zipfile.ZipFile(infile)) as input:
for info in input.infolist():
include = len(include_paths) == 0
for path in include_paths:
include = include or info.filename.startswith(path)
exclude = False
for path in exclude_paths:
exclude = exclude or info.filename.startswith(path)
if include and not exclude:
input.extract(info, temp_dir)
# Now we can package the files we extracted into our specified destination.
with contextlib.closing(zipfile.ZipFile(outfile, 'w')) as output:
for root, _, files in os.walk(temp_dir):
for file in files:
file = os.path.join(root, file)
output.write(file, os.path.relpath(file, temp_dir))
@contextlib.contextmanager
def tempdir():
path = tempfile.mkdtemp()
try:
yield path
finally:
try:
shutil.rmtree(path)
except IOError:
sys.stderr.write('Failed to remove {0}'.format(path))
if __name__ == '__main__':
main()
| 32.302632 | 90 | 0.641141 |
import contextlib
import os
import optparse
import shutil
import sys
import tempfile
import zipfile
def main():
parser = optparse.OptionParser()
parser.add_option('--input')
parser.add_option('--output')
parser.add_option(
'--include-path',
action='append',
default=[])
parser.add_option(
'--exclude-path',
action='append',
default=[])
options, _ = parser.parse_args()
process_jar(options.input, options.output, options.include_path, options.exclude_path)
def process_jar(infile, outfile, include_paths, exclude_paths):
with tempdir() as temp_dir:
with contextlib.closing(zipfile.ZipFile(infile)) as input:
for info in input.infolist():
include = len(include_paths) == 0
for path in include_paths:
include = include or info.filename.startswith(path)
exclude = False
for path in exclude_paths:
exclude = exclude or info.filename.startswith(path)
if include and not exclude:
input.extract(info, temp_dir)
with contextlib.closing(zipfile.ZipFile(outfile, 'w')) as output:
for root, _, files in os.walk(temp_dir):
for file in files:
file = os.path.join(root, file)
output.write(file, os.path.relpath(file, temp_dir))
@contextlib.contextmanager
def tempdir():
path = tempfile.mkdtemp()
try:
yield path
finally:
try:
shutil.rmtree(path)
except IOError:
sys.stderr.write('Failed to remove {0}'.format(path))
if __name__ == '__main__':
main()
| true | true |
f7f89b1cfec17faba8f91e789c27f4751ac40c48 | 540 | py | Python | djstripe/exceptions.py | ComFreight/cmft-stripe-integration | 85a2e14dcd6fffd24e999b1f383dd7eb006606e0 | [
"MIT"
] | null | null | null | djstripe/exceptions.py | ComFreight/cmft-stripe-integration | 85a2e14dcd6fffd24e999b1f383dd7eb006606e0 | [
"MIT"
] | null | null | null | djstripe/exceptions.py | ComFreight/cmft-stripe-integration | 85a2e14dcd6fffd24e999b1f383dd7eb006606e0 | [
"MIT"
] | 1 | 2018-09-11T10:49:32.000Z | 2018-09-11T10:49:32.000Z | # -*- coding: utf-8 -*-
"""
.. module:: djstripe.exceptions.
:synopsis: dj-stripe Exceptions.
.. moduleauthor:: @kavdev
"""
from __future__ import absolute_import, division, print_function, unicode_literals
class MultipleSubscriptionException(Exception):
"""Raised when a Customer has multiple Subscriptions and only one is expected."""
pass
class StripeObjectManipulationException(Exception):
"""Raised when an attempt to manipulate a non-standalone stripe object is made not through its parent object."""
pass
| 23.478261 | 116 | 0.740741 |
from __future__ import absolute_import, division, print_function, unicode_literals
class MultipleSubscriptionException(Exception):
pass
class StripeObjectManipulationException(Exception):
pass
| true | true |
f7f89d3db4407aadfac4bf3f45810ddbc900a023 | 1,156 | py | Python | permuta/misc/union_find.py | quintant/Permuta | 4cdc7990e3dc298d0089ba8c48cd8967acd9b81f | [
"BSD-3-Clause"
] | 12 | 2015-09-09T02:40:50.000Z | 2021-06-02T13:40:25.000Z | permuta/misc/union_find.py | quintant/Permuta | 4cdc7990e3dc298d0089ba8c48cd8967acd9b81f | [
"BSD-3-Clause"
] | 80 | 2015-12-17T15:00:17.000Z | 2022-01-25T20:31:54.000Z | permuta/misc/union_find.py | quintant/Permuta | 4cdc7990e3dc298d0089ba8c48cd8967acd9b81f | [
"BSD-3-Clause"
] | 19 | 2015-12-16T13:16:10.000Z | 2021-06-01T14:37:33.000Z | class UnionFind:
"""A collection of distjoint sets."""
def __init__(self, size: int) -> None:
"""Creates a collection of size disjoint unit sets."""
self._parent = [-1] * size
def find(self, idx: int) -> int:
"""Return the identifier of a representative element for the set
containing the element with identifier idx."""
if self._parent[idx] < 0:
return idx
self._parent[idx] = self.find(self._parent[idx])
return self._parent[idx]
def size(self, idx: int) -> int:
"""Return the number of elements in the set containing the element with
identifier idx."""
return -self._parent[self.find(idx)]
def unite(self, idx1: int, idx2: int) -> bool:
"""Unite the two sets containing the elements with identifiers idx1 and idx2,
respectively."""
idx1, idx2 = self.find(idx1), self.find(idx2)
if idx1 == idx2:
return False
if self.size(idx1) > self.size(idx2):
idx1, idx2 = idx2, idx1
self._parent[idx2] += self._parent[idx1]
self._parent[idx1] = idx2
return True
| 36.125 | 85 | 0.596021 | class UnionFind:
def __init__(self, size: int) -> None:
self._parent = [-1] * size
def find(self, idx: int) -> int:
if self._parent[idx] < 0:
return idx
self._parent[idx] = self.find(self._parent[idx])
return self._parent[idx]
def size(self, idx: int) -> int:
return -self._parent[self.find(idx)]
def unite(self, idx1: int, idx2: int) -> bool:
idx1, idx2 = self.find(idx1), self.find(idx2)
if idx1 == idx2:
return False
if self.size(idx1) > self.size(idx2):
idx1, idx2 = idx2, idx1
self._parent[idx2] += self._parent[idx1]
self._parent[idx1] = idx2
return True
| true | true |
f7f89d3e371f830dec8c5a72be9e2fbf032c7be0 | 214 | py | Python | setup.py | justanr/aiohttp_docker_webapp_example | cfc65bf2fbbe048d2e2bbee854a0bfdb00544b54 | [
"MIT"
] | null | null | null | setup.py | justanr/aiohttp_docker_webapp_example | cfc65bf2fbbe048d2e2bbee854a0bfdb00544b54 | [
"MIT"
] | null | null | null | setup.py | justanr/aiohttp_docker_webapp_example | cfc65bf2fbbe048d2e2bbee854a0bfdb00544b54 | [
"MIT"
] | null | null | null | from setuptools import setup, find_packages
setup(
name="myapp",
packages=find_packages('src'),
package_dir={'': 'src'},
entry_points='''
[console_scripts]
myapp=myapp.cli:myapp
'''
)
| 16.461538 | 43 | 0.630841 | from setuptools import setup, find_packages
setup(
name="myapp",
packages=find_packages('src'),
package_dir={'': 'src'},
entry_points='''
[console_scripts]
myapp=myapp.cli:myapp
'''
)
| true | true |
f7f89d63c577fc8bd2f6f1bfb38fae46adaa35e9 | 375 | py | Python | fabrikApi/plugins/CIR/views/plots/ARCHIV/pybeeswarm.py | demokratiefabrik/fabrikApi | a56bb57d59a5e7cbbeeb77889c02d82f2a04c682 | [
"MIT"
] | null | null | null | fabrikApi/plugins/CIR/views/plots/ARCHIV/pybeeswarm.py | demokratiefabrik/fabrikApi | a56bb57d59a5e7cbbeeb77889c02d82f2a04c682 | [
"MIT"
] | null | null | null | fabrikApi/plugins/CIR/views/plots/ARCHIV/pybeeswarm.py | demokratiefabrik/fabrikApi | a56bb57d59a5e7cbbeeb77889c02d82f2a04c682 | [
"MIT"
] | null | null | null | # # %%
# # NOT WORKING
# # from beeswarm import *
# # import numpy as np
# from pybeeswarm import *
# # import beeswarm
# import matplotlib.pyplot as plt
# import numpy as np
# d1 = np.random.uniform(low=-3, high=3, size=100)
# d2 = np.random.normal(size=100)
# # bs, ax = pybeeswarm([d1,d2], method="swarm", labels=["sample 1", "sample 2"], col=["blue","red"])
# # %%
| 19.736842 | 101 | 0.624 | true | true | |
f7f89e7579494b0c1876d7d2f08829f845946c16 | 1,371 | py | Python | jnx_bits/mdrop/bitfields.py | Japannext/jnx_bits | cfc7bea15a37be659c4262c134902f72db2afc94 | [
"Apache-2.0"
] | null | null | null | jnx_bits/mdrop/bitfields.py | Japannext/jnx_bits | cfc7bea15a37be659c4262c134902f72db2afc94 | [
"Apache-2.0"
] | null | null | null | jnx_bits/mdrop/bitfields.py | Japannext/jnx_bits | cfc7bea15a37be659c4262c134902f72db2afc94 | [
"Apache-2.0"
] | 1 | 2022-03-31T05:56:00.000Z | 2022-03-31T05:56:00.000Z | #
# Copyright: Japannext Co., Ltd. <https://www.japannext.co.jp/>
# SPDX-License-Identifier: Apache-2.0
#
# TODO: check whether it's faster with BitStream.
from dataclasses import dataclass
ORDER_VERB = {
'00': 'B',
'01': 'S',
'10': 'T',
'11': 'E',
}
STR_TO_BOOL = { # Override non empty strings being truey in python.
'0': False,
'1': True,
}
DISPLAY = {
'0': '',
'1': 'P',
}
CAPACITY = {
'0': 'P',
'1': 'A',
}
AGGRESSOR = {
'0': 'S',
'1': 'B',
}
@dataclass
class MdOrderDetailsField:
expired_on_entry: bool
display: str
capacity: str
reserved: str
order_verb: str
@classmethod
def from_bytes(cls, bytes_):
bitstr = format(ord(bytes_), '08b')
return cls(
STR_TO_BOOL[bitstr[0]],
DISPLAY[bitstr[1]],
CAPACITY[bitstr[2]],
bitstr[3:6],
ORDER_VERB[bitstr[6:]],
)
@dataclass
class MdTradeDetailsField:
aggressor: str
reserved: str
sell_is_fix: bool
buy_is_fix: bool
@classmethod
def from_bytes(cls, bytes_):
bitstr = format(ord(bytes_), '08b')
return cls(
AGGRESSOR[bitstr[0]],
bitstr[1:6],
STR_TO_BOOL[bitstr[6]],
STR_TO_BOOL[bitstr[7]],
)
class MdStpdReportDetailsField(MdTradeDetailsField):
pass
| 17.576923 | 68 | 0.55434 |
from dataclasses import dataclass
ORDER_VERB = {
'00': 'B',
'01': 'S',
'10': 'T',
'11': 'E',
}
STR_TO_BOOL = { # Override non empty strings being truey in python.
'0': False,
'1': True,
}
DISPLAY = {
'0': '',
'1': 'P',
}
CAPACITY = {
'0': 'P',
'1': 'A',
}
AGGRESSOR = {
'0': 'S',
'1': 'B',
}
@dataclass
class MdOrderDetailsField:
expired_on_entry: bool
display: str
capacity: str
reserved: str
order_verb: str
@classmethod
def from_bytes(cls, bytes_):
bitstr = format(ord(bytes_), '08b')
return cls(
STR_TO_BOOL[bitstr[0]],
DISPLAY[bitstr[1]],
CAPACITY[bitstr[2]],
bitstr[3:6],
ORDER_VERB[bitstr[6:]],
)
@dataclass
class MdTradeDetailsField:
aggressor: str
reserved: str
sell_is_fix: bool
buy_is_fix: bool
@classmethod
def from_bytes(cls, bytes_):
bitstr = format(ord(bytes_), '08b')
return cls(
AGGRESSOR[bitstr[0]],
bitstr[1:6],
STR_TO_BOOL[bitstr[6]],
STR_TO_BOOL[bitstr[7]],
)
class MdStpdReportDetailsField(MdTradeDetailsField):
pass
| true | true |
f7f89ed39b44783ea524d53e34efe8f1f0ac095e | 5,876 | py | Python | hypergbm/sklearn/sklearn_ops.py | lixfz/HyperGBM | a7b929f2665c590afff5eae5dd4f14d8cd20bb70 | [
"Apache-2.0"
] | null | null | null | hypergbm/sklearn/sklearn_ops.py | lixfz/HyperGBM | a7b929f2665c590afff5eae5dd4f14d8cd20bb70 | [
"Apache-2.0"
] | null | null | null | hypergbm/sklearn/sklearn_ops.py | lixfz/HyperGBM | a7b929f2665c590afff5eae5dd4f14d8cd20bb70 | [
"Apache-2.0"
] | null | null | null | # -*- coding:utf-8 -*-
"""
"""
import numpy as np
from hypergbm.cfg import HyperGBMCfg as cfg
from hypernets.core.ops import ModuleChoice, Optional, Choice
from hypernets.pipeline.base import Pipeline
from hypernets.pipeline.transformers import SimpleImputer, SafeOneHotEncoder, TruncatedSVD, \
StandardScaler, MinMaxScaler, MaxAbsScaler, RobustScaler, SafeOrdinalEncoder, \
LogStandardScaler, DatetimeEncoder, TfidfEncoder, AsTypeTransformer
from hypernets.tabular import column_selector
def categorical_pipeline_simple(impute_strategy='constant', seq_no=0):
steps = [
SimpleImputer(missing_values=np.nan, strategy=impute_strategy, name=f'categorical_imputer_{seq_no}'),
SafeOrdinalEncoder(name=f'categorical_label_encoder_{seq_no}', dtype='int32')
]
if cfg.category_pipeline_auto_detect:
cs = column_selector.AutoCategoryColumnSelector(
dtype_include=column_selector.column_object_category_bool.dtype_include,
cat_exponent=cfg.category_pipeline_auto_detect_exponent)
steps.insert(0, AsTypeTransformer(dtype='str', name=f'categorical_as_object_{seq_no}'))
else:
cs = column_selector.column_object_category_bool
pipeline = Pipeline(steps, columns=cs, name=f'categorical_pipeline_simple_{seq_no}')
return pipeline
def categorical_pipeline_complex(impute_strategy=None, svd_components=3, seq_no=0):
if impute_strategy is None:
impute_strategy = Choice(['constant', 'most_frequent'])
elif isinstance(impute_strategy, list):
impute_strategy = Choice(impute_strategy)
if isinstance(svd_components, list):
svd_components = Choice(svd_components)
def onehot_svd():
onehot = SafeOneHotEncoder(name=f'categorical_onehot_{seq_no}')
optional_svd = Optional(TruncatedSVD(n_components=svd_components, name=f'categorical_svd_{seq_no}'),
name=f'categorical_optional_svd_{seq_no}',
keep_link=True)(onehot)
return optional_svd
imputer = SimpleImputer(missing_values=np.nan, strategy=impute_strategy, name=f'categorical_imputer_{seq_no}')
label_encoder = SafeOrdinalEncoder(name=f'categorical_label_encoder_{seq_no}')
onehot = onehot_svd()
le_or_onehot_pca = ModuleChoice([label_encoder, onehot], name=f'categorical_le_or_onehot_pca_{seq_no}')
steps = [imputer, le_or_onehot_pca]
if cfg.category_pipeline_auto_detect:
cs = column_selector.AutoCategoryColumnSelector(
dtype_include=column_selector.column_object_category_bool.dtype_include,
cat_exponent=cfg.category_pipeline_auto_detect_exponent)
steps.insert(0, AsTypeTransformer(dtype='str', name=f'categorical_as_object_{seq_no}'))
else:
cs = column_selector.column_object_category_bool
pipeline = Pipeline(steps, columns=cs, name=f'categorical_pipeline_complex_{seq_no}')
return pipeline
def numeric_pipeline_simple(impute_strategy='mean', seq_no=0):
pipeline = Pipeline([
SimpleImputer(missing_values=np.nan, strategy=impute_strategy,
name=f'numeric_imputer_{seq_no}', force_output_as_float=True),
StandardScaler(name=f'numeric_standard_scaler_{seq_no}')
],
columns=column_selector.column_number_exclude_timedelta,
name=f'numeric_pipeline_simple_{seq_no}',
)
return pipeline
def numeric_pipeline_complex(impute_strategy=None, seq_no=0):
if impute_strategy is None:
impute_strategy = Choice(['mean', 'median', 'constant', 'most_frequent'])
elif isinstance(impute_strategy, list):
impute_strategy = Choice(impute_strategy)
imputer = SimpleImputer(missing_values=np.nan, strategy=impute_strategy, name=f'numeric_imputer_{seq_no}',
force_output_as_float=True)
scaler_options = ModuleChoice(
[
LogStandardScaler(name=f'numeric_log_standard_scaler_{seq_no}'),
StandardScaler(name=f'numeric_standard_scaler_{seq_no}'),
MinMaxScaler(name=f'numeric_minmax_scaler_{seq_no}'),
MaxAbsScaler(name=f'numeric_maxabs_scaler_{seq_no}'),
RobustScaler(name=f'numeric_robust_scaler_{seq_no}')
], name=f'numeric_or_scaler_{seq_no}'
)
scaler_optional = Optional(scaler_options, keep_link=True, name=f'numeric_scaler_optional_{seq_no}')
pipeline = Pipeline([imputer, scaler_optional],
name=f'numeric_pipeline_complex_{seq_no}',
columns=column_selector.column_number_exclude_timedelta)
return pipeline
def datetime_pipeline_simple(impute_strategy='constant', seq_no=0):
pipeline = Pipeline([
DatetimeEncoder(name=f'datetime_encoder_{seq_no}'),
SimpleImputer(missing_values=np.nan, strategy=impute_strategy, fill_value=0,
name=f'datetime_imputer_{seq_no}'),
],
columns=column_selector.column_all_datetime,
name=f'datetime_pipeline_simple_{seq_no}',
)
return pipeline
def text_pipeline_simple(impute_strategy='constant', svd_components=3, seq_no=0):
if isinstance(impute_strategy, list):
impute_strategy = Choice(impute_strategy)
if isinstance(svd_components, list):
svd_components = Choice(svd_components)
cs = column_selector.TextColumnSelector(dtype_include=column_selector.column_text.dtype_include,
word_count_threshold=cfg.text_pipeline_word_count_threshold)
pipeline = Pipeline([
SimpleImputer(missing_values=np.nan, strategy=impute_strategy, name=f'text_imputer_{seq_no}'),
TfidfEncoder(name='text_tfidf_{seq_no}'),
TruncatedSVD(n_components=svd_components, name=f'text_svd_{seq_no}'),
],
columns=cs,
name=f'a_text_pipeline_simple_{seq_no}',
)
return pipeline
| 44.854962 | 114 | 0.723281 |
import numpy as np
from hypergbm.cfg import HyperGBMCfg as cfg
from hypernets.core.ops import ModuleChoice, Optional, Choice
from hypernets.pipeline.base import Pipeline
from hypernets.pipeline.transformers import SimpleImputer, SafeOneHotEncoder, TruncatedSVD, \
StandardScaler, MinMaxScaler, MaxAbsScaler, RobustScaler, SafeOrdinalEncoder, \
LogStandardScaler, DatetimeEncoder, TfidfEncoder, AsTypeTransformer
from hypernets.tabular import column_selector
def categorical_pipeline_simple(impute_strategy='constant', seq_no=0):
steps = [
SimpleImputer(missing_values=np.nan, strategy=impute_strategy, name=f'categorical_imputer_{seq_no}'),
SafeOrdinalEncoder(name=f'categorical_label_encoder_{seq_no}', dtype='int32')
]
if cfg.category_pipeline_auto_detect:
cs = column_selector.AutoCategoryColumnSelector(
dtype_include=column_selector.column_object_category_bool.dtype_include,
cat_exponent=cfg.category_pipeline_auto_detect_exponent)
steps.insert(0, AsTypeTransformer(dtype='str', name=f'categorical_as_object_{seq_no}'))
else:
cs = column_selector.column_object_category_bool
pipeline = Pipeline(steps, columns=cs, name=f'categorical_pipeline_simple_{seq_no}')
return pipeline
def categorical_pipeline_complex(impute_strategy=None, svd_components=3, seq_no=0):
if impute_strategy is None:
impute_strategy = Choice(['constant', 'most_frequent'])
elif isinstance(impute_strategy, list):
impute_strategy = Choice(impute_strategy)
if isinstance(svd_components, list):
svd_components = Choice(svd_components)
def onehot_svd():
onehot = SafeOneHotEncoder(name=f'categorical_onehot_{seq_no}')
optional_svd = Optional(TruncatedSVD(n_components=svd_components, name=f'categorical_svd_{seq_no}'),
name=f'categorical_optional_svd_{seq_no}',
keep_link=True)(onehot)
return optional_svd
imputer = SimpleImputer(missing_values=np.nan, strategy=impute_strategy, name=f'categorical_imputer_{seq_no}')
label_encoder = SafeOrdinalEncoder(name=f'categorical_label_encoder_{seq_no}')
onehot = onehot_svd()
le_or_onehot_pca = ModuleChoice([label_encoder, onehot], name=f'categorical_le_or_onehot_pca_{seq_no}')
steps = [imputer, le_or_onehot_pca]
if cfg.category_pipeline_auto_detect:
cs = column_selector.AutoCategoryColumnSelector(
dtype_include=column_selector.column_object_category_bool.dtype_include,
cat_exponent=cfg.category_pipeline_auto_detect_exponent)
steps.insert(0, AsTypeTransformer(dtype='str', name=f'categorical_as_object_{seq_no}'))
else:
cs = column_selector.column_object_category_bool
pipeline = Pipeline(steps, columns=cs, name=f'categorical_pipeline_complex_{seq_no}')
return pipeline
def numeric_pipeline_simple(impute_strategy='mean', seq_no=0):
pipeline = Pipeline([
SimpleImputer(missing_values=np.nan, strategy=impute_strategy,
name=f'numeric_imputer_{seq_no}', force_output_as_float=True),
StandardScaler(name=f'numeric_standard_scaler_{seq_no}')
],
columns=column_selector.column_number_exclude_timedelta,
name=f'numeric_pipeline_simple_{seq_no}',
)
return pipeline
def numeric_pipeline_complex(impute_strategy=None, seq_no=0):
if impute_strategy is None:
impute_strategy = Choice(['mean', 'median', 'constant', 'most_frequent'])
elif isinstance(impute_strategy, list):
impute_strategy = Choice(impute_strategy)
imputer = SimpleImputer(missing_values=np.nan, strategy=impute_strategy, name=f'numeric_imputer_{seq_no}',
force_output_as_float=True)
scaler_options = ModuleChoice(
[
LogStandardScaler(name=f'numeric_log_standard_scaler_{seq_no}'),
StandardScaler(name=f'numeric_standard_scaler_{seq_no}'),
MinMaxScaler(name=f'numeric_minmax_scaler_{seq_no}'),
MaxAbsScaler(name=f'numeric_maxabs_scaler_{seq_no}'),
RobustScaler(name=f'numeric_robust_scaler_{seq_no}')
], name=f'numeric_or_scaler_{seq_no}'
)
scaler_optional = Optional(scaler_options, keep_link=True, name=f'numeric_scaler_optional_{seq_no}')
pipeline = Pipeline([imputer, scaler_optional],
name=f'numeric_pipeline_complex_{seq_no}',
columns=column_selector.column_number_exclude_timedelta)
return pipeline
def datetime_pipeline_simple(impute_strategy='constant', seq_no=0):
pipeline = Pipeline([
DatetimeEncoder(name=f'datetime_encoder_{seq_no}'),
SimpleImputer(missing_values=np.nan, strategy=impute_strategy, fill_value=0,
name=f'datetime_imputer_{seq_no}'),
],
columns=column_selector.column_all_datetime,
name=f'datetime_pipeline_simple_{seq_no}',
)
return pipeline
def text_pipeline_simple(impute_strategy='constant', svd_components=3, seq_no=0):
if isinstance(impute_strategy, list):
impute_strategy = Choice(impute_strategy)
if isinstance(svd_components, list):
svd_components = Choice(svd_components)
cs = column_selector.TextColumnSelector(dtype_include=column_selector.column_text.dtype_include,
word_count_threshold=cfg.text_pipeline_word_count_threshold)
pipeline = Pipeline([
SimpleImputer(missing_values=np.nan, strategy=impute_strategy, name=f'text_imputer_{seq_no}'),
TfidfEncoder(name='text_tfidf_{seq_no}'),
TruncatedSVD(n_components=svd_components, name=f'text_svd_{seq_no}'),
],
columns=cs,
name=f'a_text_pipeline_simple_{seq_no}',
)
return pipeline
| true | true |
f7f8a17ebfd27f34f8aa117364ba663b7d43e9f6 | 691 | py | Python | verification/constants.py | pratik-vii/snet-marketplace-service | 482d4c37596c2608aa7fca586bfb54d19783b419 | [
"MIT"
] | null | null | null | verification/constants.py | pratik-vii/snet-marketplace-service | 482d4c37596c2608aa7fca586bfb54d19783b419 | [
"MIT"
] | null | null | null | verification/constants.py | pratik-vii/snet-marketplace-service | 482d4c37596c2608aa7fca586bfb54d19783b419 | [
"MIT"
] | null | null | null | from enum import Enum
class DUNSVerificationStatus(Enum):
PENDING = "PENDING"
APPROVED = "APPROVED"
REJECTED = "REJECTED"
CHANGE_REQUESTED = "CHANGE_REQUESTED"
class IndividualVerificationStatus(Enum):
PENDING = "PENDING"
APPROVED = "APPROVED"
REJECTED = "REJECTED"
CHANGE_REQUESTED = "CHANGE_REQUESTED"
class VerificationStatus(Enum):
PENDING = "PENDING"
APPROVED = "APPROVED"
REJECTED = "REJECTED"
FAILED = "FAILED"
ERROR = "ERROR"
CHANGE_REQUESTED = "CHANGE_REQUESTED"
class VerificationType(Enum):
JUMIO = "JUMIO"
DUNS = "DUNS"
INDIVIDUAL = "INDIVIDUAL"
OPEN_SLACK_VIEW_URL = "https://slack.com/api/views.open"
| 21.59375 | 56 | 0.688857 | from enum import Enum
class DUNSVerificationStatus(Enum):
PENDING = "PENDING"
APPROVED = "APPROVED"
REJECTED = "REJECTED"
CHANGE_REQUESTED = "CHANGE_REQUESTED"
class IndividualVerificationStatus(Enum):
PENDING = "PENDING"
APPROVED = "APPROVED"
REJECTED = "REJECTED"
CHANGE_REQUESTED = "CHANGE_REQUESTED"
class VerificationStatus(Enum):
PENDING = "PENDING"
APPROVED = "APPROVED"
REJECTED = "REJECTED"
FAILED = "FAILED"
ERROR = "ERROR"
CHANGE_REQUESTED = "CHANGE_REQUESTED"
class VerificationType(Enum):
JUMIO = "JUMIO"
DUNS = "DUNS"
INDIVIDUAL = "INDIVIDUAL"
OPEN_SLACK_VIEW_URL = "https://slack.com/api/views.open"
| true | true |
f7f8a1f2d35be36185aeb2811015b22c19f4b9b9 | 18,467 | py | Python | main.py | marcelooyaneder/Arboretum_Antumapu | bc1d850ea0c6d45368b3bdb8b834b05dd49f9a57 | [
"MIT"
] | null | null | null | main.py | marcelooyaneder/Arboretum_Antumapu | bc1d850ea0c6d45368b3bdb8b834b05dd49f9a57 | [
"MIT"
] | null | null | null | main.py | marcelooyaneder/Arboretum_Antumapu | bc1d850ea0c6d45368b3bdb8b834b05dd49f9a57 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
""" # CRÉDITOS
Software desarrllado en el laboratorio de biología de plantas ubicado en el campus Antumapu perteneciente a la Universidad de Chile.
- Autores:
- Paulette Naulin Gysling.
- Marcelo Oyaneder Labarca.
- Contacto:
- marcelo.oyaneder.l@gmail.com
- pnaulin@uchile.cl """
#package imports
import pandas as pd
import os
import errno
import pyqrcode
from pathlib import Path
import filecmp
import shutil
from python_firebase_url_shortener.url_shortener import UrlShortener
import time
import sys
import easygui as eg
import numpy
from PIL import Image
#autoidenficar el separator en csv ; o ,
class file_manager:
def file_opener(self):
#search if a csv file has been created previusly
try:
data=pd.read_csv('dataframe.csv',header=0,sep=';') #ver como variar de ; o ,
except:
file_path=eg.fileopenbox(msg='pick the file wish contain your data',title='directory',default='*',filetypes=None,multiple=False)
if file_path.endswith('.xlsx') or file_path.endswith('.xls'):
data=pd.read_excel(file_path,sheet_name='Hoja1',header=0)
elif file_path.endswith('.csv'):
data=pd.read_csv(file_path,header=0,sep=';') #ver como variar de ; o ,
columns_df=data.columns.tolist()
msg='select a column to be the index of the dataframe'
title='select index'
indexo=eg.choicebox(msg,title,columns_df)
data=data.set_index(indexo, drop = True)
og_data=data.copy()
og_columns_df=og_data.columns.tolist()
columns_dwc=pd.read_csv('documents\dwc_terms\simple_dwc_horizontal.csv',header=0,sep=';').columns.tolist() #ver como variar de ; o ,
columns_difference=list(set(columns_df)-set(columns_dwc))
if not columns_difference:
pass
else:
msg='the followings columns do not belong to DwC, select the ones you wish to delete'
title='select to delete'
choicebox=eg.multchoicebox(msg,title,columns_difference)
try:
for label in choicebox:
data.drop(label,axis=1,inplace=True)
except:
pass
empty_columns_drop_answer=eg.ynbox(msg='Do you wish to delete the empty columns?...',title='Drop empty columns') #a way to drop fully empty columns
if empty_columns_drop_answer==True:
data.dropna(axis=1, how='all',inplace=True)
og_data.dropna(axis=1, how='all',inplace=True)
og_data.to_csv('online_dataframe.csv',sep=',')
else:
pass
return og_data,data,indexo,og_columns_df
def file_creation(self):
Record_level=pd.read_csv('documents\dwc_terms\Record_level.csv',header=0,sep=';',encoding = 'unicode_escape')
Ocurrence=pd.read_csv('documents\dwc_terms\Ocurrence.csv',header=0,sep=';',encoding = 'unicode_escape')
Organism=pd.read_csv('documents\dwc_terms\organism.csv',header=0,sep=';',encoding = 'unicode_escape')
Material_sample=pd.read_csv('documents\dwc_terms\MaterialSample.csv',header=0,sep=';',encoding = 'unicode_escape')
Event=pd.read_csv('documents\dwc_terms\event.csv',header=0,sep=';',encoding = 'unicode_escape')
Location=pd.read_csv('documents\dwc_terms\location.csv',header=0,sep=';',encoding = 'unicode_escape')
Geological_Context=pd.read_csv('documents\dwc_terms\GeologicalContext.csv',header=0,sep=';',encoding = 'unicode_escape')
Identification=pd.read_csv('documents\dwc_terms\identification.csv',header=0,sep=';',encoding = 'unicode_escape')
Taxon=pd.read_csv('documents\dwc_terms\Taxon.csv',header=0,sep=';',encoding = 'unicode_escape')
columns_dwc=[Record_level,Ocurrence,Organism,Material_sample,Event,Location,Geological_Context,Identification,Taxon]
dwc_columns=[]
for dataframe in columns_dwc:
level_list=[]
for rows in dataframe.itertuples():
# Create list for the current row
my_list =f'{rows.standardFieldName}-{rows.verbatimFieldName}-{rows.uri}'
# append the list to the final list
level_list.append(my_list)
msg='select the terms for your custom dwc dataframe'
title='select terms'
choicebox=eg.multchoicebox(msg,title,level_list)
try:
for elements in choicebox:
try:
indice=level_list.index(elements)
value=dataframe['standardFieldName'][indice]
dwc_columns.append(value)
except:
pass
except:
pass
dataframe=pd.DataFrame(columns=dwc_columns)
return dataframe
class subject:
def __init__(self,data):
self.data=data
def datafiltering(self,data):
columns_df=data.columns.tolist()
msg='select a value to query'
title='select'
choicebox=eg.choicebox(msg,title,columns_df)
querys=data[choicebox].unique()
query_choicebox=eg.choicebox(msg,title,querys)
data.query(f"{choicebox}=='{query_choicebox}'",inplace=True)
return data
def datafiltering_predef(self,data,column):
msg='select a value to query'
title='select'
querys=data[column].unique()
query_choicebox=eg.choicebox(msg,title,querys)
data.query(f"{column}=='{query_choicebox}'",inplace=True)
return data
def change_values(self,data,og_data,subjects):
IDs_for_change=eg.multchoicebox(msg='Select the subject(s) for a change: ',title='Select...',choices=subjects)
columns=data.columns.tolist()
new_value_change=True
while new_value_change==True:
values_to_change=eg.choicebox(msg='The following values are available for change: ',title='Select...',choices=columns)
set_value=eg.enterbox(msg=f'Enter a new value for {values_to_change}: ',title='New value...')
for values in IDs_for_change:
try:
data.at[values,values_to_change]=set_value
data.at[values,'acceptedNameUsage']= '{0} {1} {2}'.format(data.at[values,'genus'],data.at[values,'specificEpithet'],data.at[values,'nameAcordingTo'])
og_data.at[values,values_to_change]=set_value
og_data.at[values,'acceptedNameUsage']= '{0} {1} {2}'.format(data.at[values,'genus'],data.at[values,'specificEpithet'],data.at[values,'nameAcordingTo'])
except:
print('The changes can not be made')
pass
new_value_change=eg.ynbox(msg='Do you want to change another values in this subjects?',title='Value change')
return data
def add_values(self,data):
msg = "Enter information about the new subject"
title = "New subject entry "
last_indexo =data.index[-1]
new = int(last_indexo, 36) + 1
new_id=numpy.base_repr(new, 36)
fieldNames = data.columns.tolist()[1:]
fieldValues = []
fieldValues = eg.multenterbox(msg,title, fieldNames)
fieldValues.insert(0,new_id)
data.loc[fieldValues[0]]=fieldValues
return data
def save_values(self,data): #programar para que tire a csv
path_choice=eg.diropenbox(msg='choose a folder to save a file',title='select a path')
folder_name=eg.enterbox(msg='Enter the filename', title='Filename', default='DataFrame', strip=True, image=None, root=None)
with pd.ExcelWriter(f"{path_choice}\{folder_name}.xlsx") as writer:
data.to_excel(writer, sheet_name='DataFrame')
def comparefiles(ID,info,option): #option 1 for showroom, 0 files
filename1 = f"temp/{ID}.txt"
if option==1:
filename2= f"showroom_files/{ID}.txt"
elif option==0:
filename2= f"files/{ID}.txt"
os.makedirs(os.path.dirname(filename1), exist_ok=True)
with open(filename1,'w') as fil:
fil.write(str(info))
if os.path.isfile(filename2)==True:
if filecmp.cmp(filename1,filename2)==False:
print(f'ive found some changes since the last time, on file... {ID}.txt')
print('changes has been saved')
shutil.move(filename1,filename2)
else:
pass
else:
print(f'a new entry has been found, file... {ID}.txt has been created.')
os.makedirs(os.path.dirname(filename2), exist_ok=True)
with open(filename2,'w') as fil:
fil.write(str(info))
shutil.rmtree('temp/', ignore_errors=False, onerror=None)
return
def infowriting(ID,info,option): #option 1 for showroom, 0 files
try:
if option ==0:
filename = f"files/{ID}.txt"
elif option==1:
filename = f"showroom_files/{ID}.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename,'w') as fil:
fil.write(str(info))
print(f'a new entry has been found, file...{ID}.txt has been created.')
except:
print(f'permission to write in {filename} has been denied...')
return
def dynamiclinks(longurl):
user_info=pd.read_csv("documents\dynamiclinks_user_info.csv",header=0,sep=';')
api_key=user_info['api_key'][0] #this need to be created on the firebase webpage
sub_domain=user_info['sub_domain'][0] #this need to be created on firebase webpage
try:
url_shortener = UrlShortener(api_key,sub_domain)
shorturl=url_shortener.get_short_link(longurl)
except:
print('Oops! you have reached the limit of urls')
time.sleep(0.2) #to not break the limits of firebase
return shorturl
#crear un Qr para showroom
#Crear un Qr para manejo del lab
def qr_manager(ID,short_url,option): #option 1 for showroom, 0 files
try:
if option ==0:
filename = f"qrs/{ID}.png"
elif option==1:
filename = f"qrs_showroom/{ID}.png"
os.makedirs(os.path.dirname(filename), exist_ok=True)
quick_response_code= pyqrcode.create(short_url)
with open(filename, 'wb') as f:
quick_response_code.png(f, scale=8,module_color=(0,102,0,255),background=(255, 255, 255, 255))
try:
img = Image.open(filename)
width, height = img.size
logo_size =50
logo = Image.open('documents\logo.png')
xmin = ymin = int((width / 2) - (logo_size / 2))
xmax = ymax = int((width / 2) + (logo_size / 2))
logo = logo.resize((xmax - xmin, ymax - ymin))
img.paste(logo, (xmin, ymin, xmax, ymax))
img.save(filename)
except:
pass
except:
print(f'permission to write in {filename} has been denied...')
####################################################################
##############################MAIN##################################
####################################################################
#######################################
########FILE MANAGEMENT SECTION########
#######################################
dataframe=file_manager()
file_mng_button=eg.buttonbox(msg='select an option',title='select an option',choices=['Open a file','Create a custom dwc file'])
if file_mng_button=='Open a file':
og_data,data,indexo,og_columns_df=dataframe.file_opener() #no considerar para file_creation
IDs=data.index.tolist() #no considerar para file_creation
showroom_option_button=eg.buttonbox(msg='do you wish to create files for a showroom',title='select a option',choices=['Yes','No'])
if showroom_option_button=='Yes':
data_showroom=og_data.copy()
msg='select the columns to keep on your showroom dataframe'
title='select'
choicebox=eg.multchoicebox(msg,title,og_columns_df)
try:
data_showroom=data_showroom[choicebox]
except:
pass
elif showroom_option_button=='No':
pass
elif file_mng_button=='Create a custom dwc file':
data=dataframe.file_creation() #no considerar para file_opener
data.to_csv('custom_dwc_frame.csv',sep=';', encoding='utf-8') #considerar para file opener
print ('your file is ready....')
print(data)
exit()
print(data)
##################################
########QUERY DATA SECTION########
##################################
query_choicebox_options=['Yes...Custom query','Query by: order-family-genus-specificEpithet','Query by: Class-order-family-genus-specificEpithet','No']
query_choicebox=eg.choicebox(msg='Do you wish to query your data...',title='Query options',choices=query_choicebox_options)
if query_choicebox==query_choicebox_options[0]:
data_for_query=data.copy()
r1=subject(data_for_query)
answer_query_choicebox=True
while answer_query_choicebox==True:
r1.datafiltering(data_for_query)
print(data_for_query)
answer_query_choicebox=eg.ynbox(msg='Do you wish to make a new query?',title='Select an option')
print('Your query has been finished....')
print(data_for_query)
elif query_choicebox==query_choicebox_options[1]:
data_for_query=data.copy()
r1=subject(data_for_query)
column_query_predef=['order','family','genus','specificEpithet']
for columns_predef in column_query_predef:
r1.datafiltering_predef(data_for_query,columns_predef)
print('Your query has been finished....')
print(data_for_query)
elif query_choicebox==query_choicebox_options[2]:
data_for_query=data.copy()
r1=subject(data_for_query)
column_query_predef=['Class','order','family','genus','specificEpithet']
for columns_predef in column_query_predef:
r1.datafiltering_predef(data_for_query,columns_predef)
print('Your query has been finished....')
print(data_for_query)
else:
pass
""" DEBO DECIDIR SI HARE LA FUNCION PARA OBTENER UN CSV O EXCEL
ADEMAS DE REOBTENER EL VALOR SUBJECTS DE DATA_FOR_QUERY PARA CAMBIAR LOS VALORES SI ES QUE SE QUIERE
DAR OPCION DE GUARDAR, CAMBIAR VALORES O MOSTRAR SUJETOS QUE CUMPLEN LOS REQUISITOS
SECCION EN DESARROLLO
"""
if not query_choicebox==query_choicebox_options[3] or query_choicebox==None:
choicebox_for_after_query_options=['export your query to a xlsx file (readable for excel)','make changes on your query and export them to a xlsx file (this changes will be saved on your original file)','show the subjects wich match your query']
choicebox_for_after_query=eg.choicebox(msg='Choose an option for your query...',title='Query options',choices=choicebox_for_after_query_options)
if choicebox_for_after_query==choicebox_for_after_query_options[0]:
#export your query to a xlsx file (readable for excel)
r1.save_values(data_for_query)
elif choicebox_for_after_query==choicebox_for_after_query_options[1]:
#make changes on your query and export them to a xlsx file (this changes will be saved on your original file)
query_subjects=data_for_query[indexo].tolist()
r1.change_values(data,og_data,query_subjects)
r1.save_values(og_data) #for saving original data
elif choicebox_for_after_query==choicebox_for_after_query_options[2]:
#show the subjects wich match your query
query_subjects=data_for_query[indexo].tolist()
for values in query_subjects:
print(values)
else:
pass
#Add values
#r1.add_values(data)
#compare files or create them
print('compare/create files...')
if os.path.isdir('files')==True:
for id in IDs:
comparefiles(id,data.loc[id],0)
else:
for id in IDs:
infowriting(id,data.loc[id],0)
if showroom_option_button=='Yes':
if os.path.isdir('showroom_files')==True:
for id in IDs:
comparefiles(id,data_showroom.loc[id],1)
else:
for id in IDs:
infowriting(id,data_showroom.loc[id],1)
print ('there is nothing more to do here...')
#compare qr files or create them
user_info=pd.read_csv("documents\dynamiclinks_user_info.csv",header=0,sep=';')
GitHub_username=user_info['GitHub_username'][0] #this need to be created on the GitHub webpage
Repository_name=user_info['Repository_name'][0] #this need to be created on the firebase webpage
print('create non existing qrs files...')
if os.path.isdir('qrs')==True:
for id in IDs:
print(f'file {id} of file {IDs[-1]}',end='\r', flush=True)
path=f"qrs/{id}.png"
if os.path.isfile(path)==False:
longurl=f'https://raw.githubusercontent.com/{GitHub_username}/{Repository_name}/master/files/{id}.txt'
shorturl=dynamiclinks(longurl)
qr_manager(id,shorturl,0)
else:
pass
else:
for id in IDs:
print(f'file {id} of file {IDs[-1]}',end='\r', flush=True)
longurl=f'https://raw.githubusercontent.com/{GitHub_username}/{Repository_name}/master/files/{id}.txt'
shorturl=dynamiclinks(longurl)
qr_manager(id,shorturl,0)
if showroom_option_button=='Yes':
print('create non existing qrs shorwoom files...')
if os.path.isdir('qrs_showroom')==True:
for id in IDs:
print(f'file {id} of file {IDs[-1]}',end='\r', flush=True)
path=f"qrs_showroom/{id}.png"
if os.path.isfile(path)==False:
longurl=f'https://raw.githubusercontent.com/{GitHub_username}/{Repository_name}/master/showroom_files/{id}.txt'
shorturl=dynamiclinks(longurl)
qr_manager(id,shorturl,1)
else:
pass
else:
for id in IDs:
print(f'file {id} of file {IDs[-1]}',end='\r', flush=True)
longurl=f'https://raw.githubusercontent.com/{GitHub_username}/{Repository_name}/master/showroom_files/{id}.txt'
shorturl=dynamiclinks(longurl)
qr_manager(id,shorturl,1)
else:
pass
print ('there is nothing more to do here...') | 46.399497 | 249 | 0.629772 |
import pandas as pd
import os
import errno
import pyqrcode
from pathlib import Path
import filecmp
import shutil
from python_firebase_url_shortener.url_shortener import UrlShortener
import time
import sys
import easygui as eg
import numpy
from PIL import Image
class file_manager:
def file_opener(self):
try:
data=pd.read_csv('dataframe.csv',header=0,sep=';')
except:
file_path=eg.fileopenbox(msg='pick the file wish contain your data',title='directory',default='*',filetypes=None,multiple=False)
if file_path.endswith('.xlsx') or file_path.endswith('.xls'):
data=pd.read_excel(file_path,sheet_name='Hoja1',header=0)
elif file_path.endswith('.csv'):
data=pd.read_csv(file_path,header=0,sep=';')
columns_df=data.columns.tolist()
msg='select a column to be the index of the dataframe'
title='select index'
indexo=eg.choicebox(msg,title,columns_df)
data=data.set_index(indexo, drop = True)
og_data=data.copy()
og_columns_df=og_data.columns.tolist()
columns_dwc=pd.read_csv('documents\dwc_terms\simple_dwc_horizontal.csv',header=0,sep=';').columns.tolist()
columns_difference=list(set(columns_df)-set(columns_dwc))
if not columns_difference:
pass
else:
msg='the followings columns do not belong to DwC, select the ones you wish to delete'
title='select to delete'
choicebox=eg.multchoicebox(msg,title,columns_difference)
try:
for label in choicebox:
data.drop(label,axis=1,inplace=True)
except:
pass
empty_columns_drop_answer=eg.ynbox(msg='Do you wish to delete the empty columns?...',title='Drop empty columns')
if empty_columns_drop_answer==True:
data.dropna(axis=1, how='all',inplace=True)
og_data.dropna(axis=1, how='all',inplace=True)
og_data.to_csv('online_dataframe.csv',sep=',')
else:
pass
return og_data,data,indexo,og_columns_df
def file_creation(self):
Record_level=pd.read_csv('documents\dwc_terms\Record_level.csv',header=0,sep=';',encoding = 'unicode_escape')
Ocurrence=pd.read_csv('documents\dwc_terms\Ocurrence.csv',header=0,sep=';',encoding = 'unicode_escape')
Organism=pd.read_csv('documents\dwc_terms\organism.csv',header=0,sep=';',encoding = 'unicode_escape')
Material_sample=pd.read_csv('documents\dwc_terms\MaterialSample.csv',header=0,sep=';',encoding = 'unicode_escape')
Event=pd.read_csv('documents\dwc_terms\event.csv',header=0,sep=';',encoding = 'unicode_escape')
Location=pd.read_csv('documents\dwc_terms\location.csv',header=0,sep=';',encoding = 'unicode_escape')
Geological_Context=pd.read_csv('documents\dwc_terms\GeologicalContext.csv',header=0,sep=';',encoding = 'unicode_escape')
Identification=pd.read_csv('documents\dwc_terms\identification.csv',header=0,sep=';',encoding = 'unicode_escape')
Taxon=pd.read_csv('documents\dwc_terms\Taxon.csv',header=0,sep=';',encoding = 'unicode_escape')
columns_dwc=[Record_level,Ocurrence,Organism,Material_sample,Event,Location,Geological_Context,Identification,Taxon]
dwc_columns=[]
for dataframe in columns_dwc:
level_list=[]
for rows in dataframe.itertuples():
my_list =f'{rows.standardFieldName}-{rows.verbatimFieldName}-{rows.uri}'
level_list.append(my_list)
msg='select the terms for your custom dwc dataframe'
title='select terms'
choicebox=eg.multchoicebox(msg,title,level_list)
try:
for elements in choicebox:
try:
indice=level_list.index(elements)
value=dataframe['standardFieldName'][indice]
dwc_columns.append(value)
except:
pass
except:
pass
dataframe=pd.DataFrame(columns=dwc_columns)
return dataframe
class subject:
def __init__(self,data):
self.data=data
def datafiltering(self,data):
columns_df=data.columns.tolist()
msg='select a value to query'
title='select'
choicebox=eg.choicebox(msg,title,columns_df)
querys=data[choicebox].unique()
query_choicebox=eg.choicebox(msg,title,querys)
data.query(f"{choicebox}=='{query_choicebox}'",inplace=True)
return data
def datafiltering_predef(self,data,column):
msg='select a value to query'
title='select'
querys=data[column].unique()
query_choicebox=eg.choicebox(msg,title,querys)
data.query(f"{column}=='{query_choicebox}'",inplace=True)
return data
def change_values(self,data,og_data,subjects):
IDs_for_change=eg.multchoicebox(msg='Select the subject(s) for a change: ',title='Select...',choices=subjects)
columns=data.columns.tolist()
new_value_change=True
while new_value_change==True:
values_to_change=eg.choicebox(msg='The following values are available for change: ',title='Select...',choices=columns)
set_value=eg.enterbox(msg=f'Enter a new value for {values_to_change}: ',title='New value...')
for values in IDs_for_change:
try:
data.at[values,values_to_change]=set_value
data.at[values,'acceptedNameUsage']= '{0} {1} {2}'.format(data.at[values,'genus'],data.at[values,'specificEpithet'],data.at[values,'nameAcordingTo'])
og_data.at[values,values_to_change]=set_value
og_data.at[values,'acceptedNameUsage']= '{0} {1} {2}'.format(data.at[values,'genus'],data.at[values,'specificEpithet'],data.at[values,'nameAcordingTo'])
except:
print('The changes can not be made')
pass
new_value_change=eg.ynbox(msg='Do you want to change another values in this subjects?',title='Value change')
return data
def add_values(self,data):
msg = "Enter information about the new subject"
title = "New subject entry "
last_indexo =data.index[-1]
new = int(last_indexo, 36) + 1
new_id=numpy.base_repr(new, 36)
fieldNames = data.columns.tolist()[1:]
fieldValues = []
fieldValues = eg.multenterbox(msg,title, fieldNames)
fieldValues.insert(0,new_id)
data.loc[fieldValues[0]]=fieldValues
return data
def save_values(self,data):
path_choice=eg.diropenbox(msg='choose a folder to save a file',title='select a path')
folder_name=eg.enterbox(msg='Enter the filename', title='Filename', default='DataFrame', strip=True, image=None, root=None)
with pd.ExcelWriter(f"{path_choice}\{folder_name}.xlsx") as writer:
data.to_excel(writer, sheet_name='DataFrame')
def comparefiles(ID,info,option):
filename1 = f"temp/{ID}.txt"
if option==1:
filename2= f"showroom_files/{ID}.txt"
elif option==0:
filename2= f"files/{ID}.txt"
os.makedirs(os.path.dirname(filename1), exist_ok=True)
with open(filename1,'w') as fil:
fil.write(str(info))
if os.path.isfile(filename2)==True:
if filecmp.cmp(filename1,filename2)==False:
print(f'ive found some changes since the last time, on file... {ID}.txt')
print('changes has been saved')
shutil.move(filename1,filename2)
else:
pass
else:
print(f'a new entry has been found, file... {ID}.txt has been created.')
os.makedirs(os.path.dirname(filename2), exist_ok=True)
with open(filename2,'w') as fil:
fil.write(str(info))
shutil.rmtree('temp/', ignore_errors=False, onerror=None)
return
def infowriting(ID,info,option):
try:
if option ==0:
filename = f"files/{ID}.txt"
elif option==1:
filename = f"showroom_files/{ID}.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename,'w') as fil:
fil.write(str(info))
print(f'a new entry has been found, file...{ID}.txt has been created.')
except:
print(f'permission to write in {filename} has been denied...')
return
def dynamiclinks(longurl):
user_info=pd.read_csv("documents\dynamiclinks_user_info.csv",header=0,sep=';')
api_key=user_info['api_key'][0]
sub_domain=user_info['sub_domain'][0]
try:
url_shortener = UrlShortener(api_key,sub_domain)
shorturl=url_shortener.get_short_link(longurl)
except:
print('Oops! you have reached the limit of urls')
time.sleep(0.2)
return shorturl
def qr_manager(ID,short_url,option):
try:
if option ==0:
filename = f"qrs/{ID}.png"
elif option==1:
filename = f"qrs_showroom/{ID}.png"
os.makedirs(os.path.dirname(filename), exist_ok=True)
quick_response_code= pyqrcode.create(short_url)
with open(filename, 'wb') as f:
quick_response_code.png(f, scale=8,module_color=(0,102,0,255),background=(255, 255, 255, 255))
try:
img = Image.open(filename)
width, height = img.size
logo_size =50
logo = Image.open('documents\logo.png')
xmin = ymin = int((width / 2) - (logo_size / 2))
xmax = ymax = int((width / 2) + (logo_size / 2))
logo = logo.resize((xmax - xmin, ymax - ymin))
img.paste(logo, (xmin, ymin, xmax, ymax))
img.save(filename)
except:
pass
except:
print(f'permission to write in {filename} has been denied...')
| true | true |
f7f8a20aa8d4a4dbeff72085b26439ab923bdb33 | 1,195 | py | Python | boa3/builtin/interop/storage/storagemap.py | DanPopa46/neo3-boa | e4ef340744b5bd25ade26f847eac50789b97f3e9 | [
"Apache-2.0"
] | null | null | null | boa3/builtin/interop/storage/storagemap.py | DanPopa46/neo3-boa | e4ef340744b5bd25ade26f847eac50789b97f3e9 | [
"Apache-2.0"
] | null | null | null | boa3/builtin/interop/storage/storagemap.py | DanPopa46/neo3-boa | e4ef340744b5bd25ade26f847eac50789b97f3e9 | [
"Apache-2.0"
] | null | null | null | from typing import Union
class StorageMap:
def __init__(self, context, prefix: Union[bytes, str]):
from boa3.builtin.interop.storage.storagecontext import StorageContext
self._context: StorageContext
self._prefix: Union[bytes, str]
def get(self, key: Union[str, bytes]) -> bytes:
"""
Gets a value from the map based on the given key.
:param key: value identifier in the store
:type key: str or bytes
:return: the value corresponding to given key for current storage context
:rtype: bytes
"""
pass
def put(self, key: Union[str, bytes], value: Union[int, str, bytes]):
"""
Inserts a given value in the key-value format into the map.
:param key: the identifier in the store for the new value
:type key: str or bytes
:param value: value to be stored
:type value: int or str or bytes
"""
pass
def delete(self, key: Union[str, bytes]):
"""
Removes a given key from the map if exists.
:param key: the identifier in the store for the new value
:type key: str or bytes
"""
pass
| 28.452381 | 81 | 0.604184 | from typing import Union
class StorageMap:
def __init__(self, context, prefix: Union[bytes, str]):
from boa3.builtin.interop.storage.storagecontext import StorageContext
self._context: StorageContext
self._prefix: Union[bytes, str]
def get(self, key: Union[str, bytes]) -> bytes:
pass
def put(self, key: Union[str, bytes], value: Union[int, str, bytes]):
pass
def delete(self, key: Union[str, bytes]):
pass
| true | true |
f7f8a309031f6ed4c64517ed477088dc0125d88d | 1,138 | py | Python | StarNavi/api/urls.py | vlsh1n/StarNaviTestApp | 57662644ede3d3bb395354035ce7e2e5582d5cb5 | [
"MIT"
] | null | null | null | StarNavi/api/urls.py | vlsh1n/StarNaviTestApp | 57662644ede3d3bb395354035ce7e2e5582d5cb5 | [
"MIT"
] | null | null | null | StarNavi/api/urls.py | vlsh1n/StarNaviTestApp | 57662644ede3d3bb395354035ce7e2e5582d5cb5 | [
"MIT"
] | null | null | null | from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework.routers import DefaultRouter
from .views import GenreListView, GenreDetailView, MovieViewSet, UserViewSet
router = DefaultRouter()
router.register('users', UserViewSet, basename='users')
movie_list = MovieViewSet.as_view({
'get': 'list',
'post': 'create'
})
movie_detail = MovieViewSet.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy'
})
movie_like = MovieViewSet.as_view({
'post': 'like',
'get': 'fans'
})
movie_dislike = MovieViewSet.as_view({
'post': 'unlike',
'get': 'fans'
})
urlpatterns = [
path('movies/', movie_list),
path('movies/<int:pk>/', movie_detail, name='movie_detail'),
path('movies/<int:pk>/like/', movie_like, name='movie_like'),
path('movies/<int:pk>/dislike/', movie_dislike, name='movie_dislike'),
path('genres/', GenreListView.as_view()),
path('genres/<int:pk>', GenreDetailView.as_view(), name='genre_detail')
]
urlpatterns = format_suffix_patterns(urlpatterns)
urlpatterns += router.urls
| 27.756098 | 76 | 0.695958 | from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework.routers import DefaultRouter
from .views import GenreListView, GenreDetailView, MovieViewSet, UserViewSet
router = DefaultRouter()
router.register('users', UserViewSet, basename='users')
movie_list = MovieViewSet.as_view({
'get': 'list',
'post': 'create'
})
movie_detail = MovieViewSet.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy'
})
movie_like = MovieViewSet.as_view({
'post': 'like',
'get': 'fans'
})
movie_dislike = MovieViewSet.as_view({
'post': 'unlike',
'get': 'fans'
})
urlpatterns = [
path('movies/', movie_list),
path('movies/<int:pk>/', movie_detail, name='movie_detail'),
path('movies/<int:pk>/like/', movie_like, name='movie_like'),
path('movies/<int:pk>/dislike/', movie_dislike, name='movie_dislike'),
path('genres/', GenreListView.as_view()),
path('genres/<int:pk>', GenreDetailView.as_view(), name='genre_detail')
]
urlpatterns = format_suffix_patterns(urlpatterns)
urlpatterns += router.urls
| true | true |
f7f8a370b32c4b49958b368f8292eaba7f39dda2 | 125 | py | Python | portfolio/apps.py | Yubisel/webpersonal | 03000f9a9b4f94a9150ea3b930821c3d48727f95 | [
"MIT"
] | null | null | null | portfolio/apps.py | Yubisel/webpersonal | 03000f9a9b4f94a9150ea3b930821c3d48727f95 | [
"MIT"
] | null | null | null | portfolio/apps.py | Yubisel/webpersonal | 03000f9a9b4f94a9150ea3b930821c3d48727f95 | [
"MIT"
] | null | null | null | from django.apps import AppConfig
class PortfolioConfig(AppConfig):
name = 'portfolio'
verbose_name = 'portafolio'
| 17.857143 | 33 | 0.744 | from django.apps import AppConfig
class PortfolioConfig(AppConfig):
name = 'portfolio'
verbose_name = 'portafolio'
| true | true |
f7f8a40bad2aba5102dfb033ac70a29fc37e27e7 | 4,420 | py | Python | news_topic_server/trainer/cleaner.py | yanyang729/news-recommendation | 0cd2e2e84f94507a339077753e367cf8bef9e36e | [
"MIT"
] | 4 | 2017-11-16T15:00:23.000Z | 2018-03-08T16:28:26.000Z | news_topic_server/trainer/cleaner.py | yanyang729/news-recommendation | 0cd2e2e84f94507a339077753e367cf8bef9e36e | [
"MIT"
] | null | null | null | news_topic_server/trainer/cleaner.py | yanyang729/news-recommendation | 0cd2e2e84f94507a339077753e367cf8bef9e36e | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import warnings
warnings.filterwarnings('ignore')
import re
import string
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
# a map of contractions we may have and want to expand
CONTRACTION_MAP = {
"ain't": "is not",
"aren't": "are not",
"can't": "cannot",
"can't've": "cannot have",
"'cause": "because",
"could've": "could have",
"couldn't": "could not",
"couldn't've": "could not have",
"didn't": "did not",
"doesn't": "does not",
"don't": "do not",
"hadn't": "had not",
"hadn't've": "had not have",
"hasn't": "has not",
"haven't": "have not",
"he'd": "he would",
"he'd've": "he would have",
"he'll": "he will",
"he'll've": "he he will have",
"he's": "he is",
"how'd": "how did",
"how'd'y": "how do you",
"how'll": "how will",
"how's": "how is",
"I'd": "I would",
"I'd've": "I would have",
"I'll": "I will",
"I'll've": "I will have",
"I'm": "I am",
"I've": "I have",
"i'd": "i would",
"i'd've": "i would have",
"i'll": "i will",
"i'll've": "i will have",
"i'm": "i am",
"i've": "i have",
"isn't": "is not",
"it'd": "it would",
"it'd've": "it would have",
"it'll": "it will",
"it'll've": "it will have",
"it's": "it is",
"let's": "let us",
"ma'am": "madam",
"mayn't": "may not",
"might've": "might have",
"mightn't": "might not",
"mightn't've": "might not have",
"must've": "must have",
"mustn't": "must not",
"mustn't've": "must not have",
"needn't": "need not",
"needn't've": "need not have",
"o'clock": "of the clock",
"oughtn't": "ought not",
"oughtn't've": "ought not have",
"shan't": "shall not",
"sha'n't": "shall not",
"shan't've": "shall not have",
"she'd": "she would",
"she'd've": "she would have",
"she'll": "she will",
"she'll've": "she will have",
"she's": "she is",
"should've": "should have",
"shouldn't": "should not",
"shouldn't've": "should not have",
"so've": "so have",
"so's": "so as",
"that'd": "that would",
"that'd've": "that would have",
"that's": "that is",
"there'd": "there would",
"there'd've": "there would have",
"there's": "there is",
"they'd": "they would",
"they'd've": "they would have",
"they'll": "they will",
"they'll've": "they will have",
"they're": "they are",
"they've": "they have",
"to've": "to have",
"wasn't": "was not",
"we'd": "we would",
"we'd've": "we would have",
"we'll": "we will",
"we'll've": "we will have",
"we're": "we are",
"we've": "we have",
"weren't": "were not",
"what'll": "what will",
"what'll've": "what will have",
"what're": "what are",
"what's": "what is",
"what've": "what have",
"when's": "when is",
"when've": "when have",
"where'd": "where did",
"where's": "where is",
"where've": "where have",
"who'll": "who will",
"who'll've": "who will have",
"who's": "who is",
"who've": "who have",
"why's": "why is",
"why've": "why have",
"will've": "will have",
"won't": "will not",
"won't've": "will not have",
"would've": "would have",
"wouldn't": "would not",
"wouldn't've": "would not have",
"y'all": "you all",
"y'all'd": "you all would",
"y'all'd've": "you all would have",
"y'all're": "you all are",
"y'all've": "you all have",
"you'd": "you would",
"you'd've": "you would have",
"you'll": "you will",
"you'll've": "you will have",
"you're": "you are",
"you've": "you have"
}
def lemmatize_text(text):
"""
lemmatize text based on POS tags
:param text: a sentence
:return: lemmatized text
"""
wnl = WordNetLemmatizer()
lemmatized_tokens = [wnl.lemmatize(x) for x in text.split()]
lemmatized_text = ' '.join(lemmatized_tokens)
return lemmatized_text
def remove_special_characters(text):
"""
remove special character
:param text: a sentence
:return:
"""
# before remove " ' " , expand it!
tokens = text.split()
for i,t in enumerate(tokens):
if t in CONTRACTION_MAP:
tokens[i] = CONTRACTION_MAP[t]
pattern = re.compile('[{}]'.format(re.escape(string.punctuation)))
filtered_tokens = filter(None, [pattern.sub('', token) for token in tokens])
filtered_text = ' '.join(filtered_tokens)
return filtered_text
def myclean(text):
text = text.replace("‘", "'").replace("’","'")
text = remove_special_characters(text)
text = lemmatize_text(text)
text = [w for w in text.split() if w not in stopwords.words('english')]
text = ' '.join([word.lower() for word in text])
return text
if __name__ == "__main__":
print myclean(" van jones the moment trump became president")
| 24.692737 | 80 | 0.594118 |
import warnings
warnings.filterwarnings('ignore')
import re
import string
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
CONTRACTION_MAP = {
"ain't": "is not",
"aren't": "are not",
"can't": "cannot",
"can't've": "cannot have",
"'cause": "because",
"could've": "could have",
"couldn't": "could not",
"couldn't've": "could not have",
"didn't": "did not",
"doesn't": "does not",
"don't": "do not",
"hadn't": "had not",
"hadn't've": "had not have",
"hasn't": "has not",
"haven't": "have not",
"he'd": "he would",
"he'd've": "he would have",
"he'll": "he will",
"he'll've": "he he will have",
"he's": "he is",
"how'd": "how did",
"how'd'y": "how do you",
"how'll": "how will",
"how's": "how is",
"I'd": "I would",
"I'd've": "I would have",
"I'll": "I will",
"I'll've": "I will have",
"I'm": "I am",
"I've": "I have",
"i'd": "i would",
"i'd've": "i would have",
"i'll": "i will",
"i'll've": "i will have",
"i'm": "i am",
"i've": "i have",
"isn't": "is not",
"it'd": "it would",
"it'd've": "it would have",
"it'll": "it will",
"it'll've": "it will have",
"it's": "it is",
"let's": "let us",
"ma'am": "madam",
"mayn't": "may not",
"might've": "might have",
"mightn't": "might not",
"mightn't've": "might not have",
"must've": "must have",
"mustn't": "must not",
"mustn't've": "must not have",
"needn't": "need not",
"needn't've": "need not have",
"o'clock": "of the clock",
"oughtn't": "ought not",
"oughtn't've": "ought not have",
"shan't": "shall not",
"sha'n't": "shall not",
"shan't've": "shall not have",
"she'd": "she would",
"she'd've": "she would have",
"she'll": "she will",
"she'll've": "she will have",
"she's": "she is",
"should've": "should have",
"shouldn't": "should not",
"shouldn't've": "should not have",
"so've": "so have",
"so's": "so as",
"that'd": "that would",
"that'd've": "that would have",
"that's": "that is",
"there'd": "there would",
"there'd've": "there would have",
"there's": "there is",
"they'd": "they would",
"they'd've": "they would have",
"they'll": "they will",
"they'll've": "they will have",
"they're": "they are",
"they've": "they have",
"to've": "to have",
"wasn't": "was not",
"we'd": "we would",
"we'd've": "we would have",
"we'll": "we will",
"we'll've": "we will have",
"we're": "we are",
"we've": "we have",
"weren't": "were not",
"what'll": "what will",
"what'll've": "what will have",
"what're": "what are",
"what's": "what is",
"what've": "what have",
"when's": "when is",
"when've": "when have",
"where'd": "where did",
"where's": "where is",
"where've": "where have",
"who'll": "who will",
"who'll've": "who will have",
"who's": "who is",
"who've": "who have",
"why's": "why is",
"why've": "why have",
"will've": "will have",
"won't": "will not",
"won't've": "will not have",
"would've": "would have",
"wouldn't": "would not",
"wouldn't've": "would not have",
"y'all": "you all",
"y'all'd": "you all would",
"y'all'd've": "you all would have",
"y'all're": "you all are",
"y'all've": "you all have",
"you'd": "you would",
"you'd've": "you would have",
"you'll": "you will",
"you'll've": "you will have",
"you're": "you are",
"you've": "you have"
}
def lemmatize_text(text):
"""
lemmatize text based on POS tags
:param text: a sentence
:return: lemmatized text
"""
wnl = WordNetLemmatizer()
lemmatized_tokens = [wnl.lemmatize(x) for x in text.split()]
lemmatized_text = ' '.join(lemmatized_tokens)
return lemmatized_text
def remove_special_characters(text):
"""
remove special character
:param text: a sentence
:return:
"""
# before remove " ' " , expand it!
tokens = text.split()
for i,t in enumerate(tokens):
if t in CONTRACTION_MAP:
tokens[i] = CONTRACTION_MAP[t]
pattern = re.compile('[{}]'.format(re.escape(string.punctuation)))
filtered_tokens = filter(None, [pattern.sub('', token) for token in tokens])
filtered_text = ' '.join(filtered_tokens)
return filtered_text
def myclean(text):
text = text.replace("‘", "'").replace("’","'")
text = remove_special_characters(text)
text = lemmatize_text(text)
text = [w for w in text.split() if w not in stopwords.words('english')]
text = ' '.join([word.lower() for word in text])
return text
if __name__ == "__main__":
print myclean(" van jones the moment trump became president")
| false | true |
f7f8a46a6b5896cb42015e3502528ebdc299ff68 | 2,641 | py | Python | config/settings/local.py | theodor85/easy-expenses | 88cbe4289f9c060c23ff9b2e62d47facb479b6fb | [
"MIT"
] | null | null | null | config/settings/local.py | theodor85/easy-expenses | 88cbe4289f9c060c23ff9b2e62d47facb479b6fb | [
"MIT"
] | 4 | 2021-03-10T19:50:32.000Z | 2022-02-27T05:29:55.000Z | config/settings/local.py | theodor85/easy-expenses | 88cbe4289f9c060c23ff9b2e62d47facb479b6fb | [
"MIT"
] | null | null | null | from .base import * # noqa
from .base import env
# GENERAL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = True
# https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
SECRET_KEY = env(
"DJANGO_SECRET_KEY",
default="YwTzzzAIA07heIHH4AqxDS7jkQGSaTnOCb1eZemxjuA7jKkuEe8vTVvGU1Ps7Dxw",
)
# https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ["localhost", "0.0.0.0", "127.0.0.1"]
# CACHES
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#caches
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "",
}
}
# EMAIL
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = env(
"DJANGO_EMAIL_BACKEND", default="django.core.mail.backends.console.EmailBackend"
)
# WhiteNoise
# ------------------------------------------------------------------------------
# http://whitenoise.evans.io/en/latest/django.html#using-whitenoise-in-development
INSTALLED_APPS = ["whitenoise.runserver_nostatic"] + INSTALLED_APPS # noqa F405
# django-debug-toolbar
# ------------------------------------------------------------------------------
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#prerequisites
INSTALLED_APPS += ["debug_toolbar"] # noqa F405
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#middleware
MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"] # noqa F405
# https://django-debug-toolbar.readthedocs.io/en/latest/configuration.html#debug-toolbar-config
DEBUG_TOOLBAR_CONFIG = {
"DISABLE_PANELS": ["debug_toolbar.panels.redirects.RedirectsPanel"],
"SHOW_TEMPLATE_CONTEXT": True,
}
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#internal-ips
INTERNAL_IPS = ["127.0.0.1", "10.0.2.2"]
if env("USE_DOCKER") == "yes":
import socket
hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
INTERNAL_IPS += [".".join(ip.split(".")[:-1] + ["1"]) for ip in ips]
# django-extensions
# ------------------------------------------------------------------------------
# https://django-extensions.readthedocs.io/en/latest/installation_instructions.html#configuration
INSTALLED_APPS += ["django_extensions"] # noqa F405
# Your stuff...
# ------------------------------------------------------------------------------
| 40.630769 | 97 | 0.580841 | from .base import *
from .base import env
= True
= env(
"DJANGO_SECRET_KEY",
default="YwTzzzAIA07heIHH4AqxDS7jkQGSaTnOCb1eZemxjuA7jKkuEe8vTVvGU1Ps7Dxw",
)
= ["localhost", "0.0.0.0", "127.0.0.1"]
= {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "",
}
}
= env(
"DJANGO_EMAIL_BACKEND", default="django.core.mail.backends.console.EmailBackend"
)
unserver_nostatic"] + INSTALLED_APPS
S += ["debug_toolbar"]
+= ["debug_toolbar.middleware.DebugToolbarMiddleware"]
= {
"DISABLE_PANELS": ["debug_toolbar.panels.redirects.RedirectsPanel"],
"SHOW_TEMPLATE_CONTEXT": True,
}
= ["127.0.0.1", "10.0.2.2"]
if env("USE_DOCKER") == "yes":
import socket
hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
INTERNAL_IPS += [".".join(ip.split(".")[:-1] + ["1"]) for ip in ips]
S += ["django_extensions"]
| true | true |
f7f8a60687bf64d2c8fab73d44bac0018eff50f2 | 1,079 | py | Python | Metodos funcoes classes/televisao.py | PaulaRegal/Python | dc00eb4d714e989e86be89a48a3633a819d7ee9f | [
"MIT"
] | null | null | null | Metodos funcoes classes/televisao.py | PaulaRegal/Python | dc00eb4d714e989e86be89a48a3633a819d7ee9f | [
"MIT"
] | null | null | null | Metodos funcoes classes/televisao.py | PaulaRegal/Python | dc00eb4d714e989e86be89a48a3633a819d7ee9f | [
"MIT"
] | null | null | null | class Televisao:
def __init__(self):
self.ligada = False #tv vai começar desligada
self.canal = 5 #canal vai começar no 5
#metodo para ligar a tv
def power(self):
if self.ligada:
self.ligada = False
else:
self.ligada = True
def aumenta_canal(self):
if self.ligada:
self.canal += 1
def diminui_canal(self):
if self.ligada:
self.canal -= 1
if __name__ == '__main__':
televisao = Televisao()
print('Televisão está ligada: {}'.format(televisao.ligada))
televisao.power()
print('Televisão está ligada: {}'.format(televisao.ligada))
televisao.power()
print('Televisão está ligada: {}'.format(televisao.ligada))
print('Canal: {}'.format(televisao.canal))
televisao.power() # para ligar a tv
print('Televisão está ligada: {}'.format(televisao.ligada))
televisao.aumenta_canal()
televisao.aumenta_canal()
print('Canal: {}'.format(televisao.canal))
televisao.diminui_canal()
print('Canal: {}'.format(televisao.canal)) | 30.828571 | 63 | 0.62836 | class Televisao:
def __init__(self):
self.ligada = False
self.canal = 5
def power(self):
if self.ligada:
self.ligada = False
else:
self.ligada = True
def aumenta_canal(self):
if self.ligada:
self.canal += 1
def diminui_canal(self):
if self.ligada:
self.canal -= 1
if __name__ == '__main__':
televisao = Televisao()
print('Televisão está ligada: {}'.format(televisao.ligada))
televisao.power()
print('Televisão está ligada: {}'.format(televisao.ligada))
televisao.power()
print('Televisão está ligada: {}'.format(televisao.ligada))
print('Canal: {}'.format(televisao.canal))
televisao.power()
print('Televisão está ligada: {}'.format(televisao.ligada))
televisao.aumenta_canal()
televisao.aumenta_canal()
print('Canal: {}'.format(televisao.canal))
televisao.diminui_canal()
print('Canal: {}'.format(televisao.canal)) | true | true |
f7f8a68d4cb31bdd2c8a0e63bee14c2004285ae5 | 81,870 | py | Python | tests/migrations/test_commands.py | marload/django | 0ce8c15033c95931e5abd36cf071b76a0b19771a | [
"CNRI-Python-GPL-Compatible",
"BSD-3-Clause"
] | 2 | 2016-07-16T23:12:49.000Z | 2017-11-14T21:43:10.000Z | tests/migrations/test_commands.py | marload/django | 0ce8c15033c95931e5abd36cf071b76a0b19771a | [
"CNRI-Python-GPL-Compatible",
"BSD-3-Clause"
] | 3 | 2016-05-15T22:05:14.000Z | 2019-11-02T15:58:14.000Z | tests/migrations/test_commands.py | marload/django | 0ce8c15033c95931e5abd36cf071b76a0b19771a | [
"CNRI-Python-GPL-Compatible",
"BSD-3-Clause"
] | 2 | 2016-01-19T18:29:21.000Z | 2021-12-23T18:17:39.000Z | import datetime
import importlib
import io
import os
import sys
from unittest import mock
from django.apps import apps
from django.core.management import CommandError, call_command
from django.db import (
ConnectionHandler, DatabaseError, connection, connections, models,
)
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.backends.utils import truncate_name
from django.db.migrations.exceptions import InconsistentMigrationHistory
from django.db.migrations.recorder import MigrationRecorder
from django.test import TestCase, override_settings, skipUnlessDBFeature
from .models import UnicodeModel, UnserializableModel
from .routers import TestRouter
from .test_base import MigrationTestBase
class MigrateTests(MigrationTestBase):
"""
Tests running the migrate command.
"""
databases = {'default', 'other'}
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
def test_migrate(self):
"""
Tests basic usage of the migrate command.
"""
# No tables are created
self.assertTableNotExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
self.assertTableNotExists("migrations_book")
# Run the migrations to 0001 only
stdout = io.StringIO()
call_command('migrate', 'migrations', '0001', verbosity=1, stdout=stdout, no_color=True)
stdout = stdout.getvalue()
self.assertIn('Target specific migration: 0001_initial, from migrations', stdout)
self.assertIn('Applying migrations.0001_initial... OK', stdout)
# The correct tables exist
self.assertTableExists("migrations_author")
self.assertTableExists("migrations_tribble")
self.assertTableNotExists("migrations_book")
# Run migrations all the way
call_command("migrate", verbosity=0)
# The correct tables exist
self.assertTableExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
self.assertTableExists("migrations_book")
# Unmigrate everything
stdout = io.StringIO()
call_command('migrate', 'migrations', 'zero', verbosity=1, stdout=stdout, no_color=True)
stdout = stdout.getvalue()
self.assertIn('Unapply all migrations: migrations', stdout)
self.assertIn('Unapplying migrations.0002_second... OK', stdout)
# Tables are gone
self.assertTableNotExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
self.assertTableNotExists("migrations_book")
@override_settings(INSTALLED_APPS=[
'django.contrib.auth',
'django.contrib.contenttypes',
'migrations.migrations_test_apps.migrated_app',
])
def test_migrate_with_system_checks(self):
out = io.StringIO()
call_command('migrate', skip_checks=False, no_color=True, stdout=out)
self.assertIn('Apply all migrations: migrated_app', out.getvalue())
@override_settings(INSTALLED_APPS=['migrations', 'migrations.migrations_test_apps.unmigrated_app_syncdb'])
def test_app_without_migrations(self):
msg = "App 'unmigrated_app_syncdb' does not have migrations."
with self.assertRaisesMessage(CommandError, msg):
call_command('migrate', app_label='unmigrated_app_syncdb')
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_clashing_prefix'})
def test_ambiguous_prefix(self):
msg = (
"More than one migration matches 'a' in app 'migrations'. Please "
"be more specific."
)
with self.assertRaisesMessage(CommandError, msg):
call_command('migrate', app_label='migrations', migration_name='a')
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations'})
def test_unknown_prefix(self):
msg = "Cannot find a migration matching 'nonexistent' from app 'migrations'."
with self.assertRaisesMessage(CommandError, msg):
call_command('migrate', app_label='migrations', migration_name='nonexistent')
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_initial_false"})
def test_migrate_initial_false(self):
"""
`Migration.initial = False` skips fake-initial detection.
"""
# Make sure no tables are created
self.assertTableNotExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
# Run the migrations to 0001 only
call_command("migrate", "migrations", "0001", verbosity=0)
# Fake rollback
call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
# Make sure fake-initial detection does not run
with self.assertRaises(DatabaseError):
call_command("migrate", "migrations", "0001", fake_initial=True, verbosity=0)
call_command("migrate", "migrations", "0001", fake=True, verbosity=0)
# Real rollback
call_command("migrate", "migrations", "zero", verbosity=0)
# Make sure it's all gone
self.assertTableNotExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
self.assertTableNotExists("migrations_book")
@override_settings(
MIGRATION_MODULES={"migrations": "migrations.test_migrations"},
DATABASE_ROUTERS=['migrations.routers.TestRouter'],
)
def test_migrate_fake_initial(self):
"""
--fake-initial only works if all tables created in the initial
migration of an app exists. Database routers must be obeyed when doing
that check.
"""
# Make sure no tables are created
for db in self.databases:
self.assertTableNotExists("migrations_author", using=db)
self.assertTableNotExists("migrations_tribble", using=db)
# Run the migrations to 0001 only
call_command("migrate", "migrations", "0001", verbosity=0)
call_command("migrate", "migrations", "0001", verbosity=0, database="other")
# Make sure the right tables exist
self.assertTableExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
# Also check the "other" database
self.assertTableNotExists("migrations_author", using="other")
self.assertTableExists("migrations_tribble", using="other")
# Fake a roll-back
call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
call_command("migrate", "migrations", "zero", fake=True, verbosity=0, database="other")
# Make sure the tables still exist
self.assertTableExists("migrations_author")
self.assertTableExists("migrations_tribble", using="other")
# Try to run initial migration
with self.assertRaises(DatabaseError):
call_command("migrate", "migrations", "0001", verbosity=0)
# Run initial migration with an explicit --fake-initial
out = io.StringIO()
with mock.patch('django.core.management.color.supports_color', lambda *args: False):
call_command("migrate", "migrations", "0001", fake_initial=True, stdout=out, verbosity=1)
call_command("migrate", "migrations", "0001", fake_initial=True, verbosity=0, database="other")
self.assertIn(
"migrations.0001_initial... faked",
out.getvalue().lower()
)
# Run migrations all the way
call_command("migrate", verbosity=0)
call_command("migrate", verbosity=0, database="other")
# Make sure the right tables exist
self.assertTableExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
self.assertTableExists("migrations_book")
self.assertTableNotExists("migrations_author", using="other")
self.assertTableNotExists("migrations_tribble", using="other")
self.assertTableNotExists("migrations_book", using="other")
# Fake a roll-back
call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
call_command("migrate", "migrations", "zero", fake=True, verbosity=0, database="other")
# Make sure the tables still exist
self.assertTableExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
self.assertTableExists("migrations_book")
# Try to run initial migration
with self.assertRaises(DatabaseError):
call_command("migrate", "migrations", verbosity=0)
# Run initial migration with an explicit --fake-initial
with self.assertRaises(DatabaseError):
# Fails because "migrations_tribble" does not exist but needs to in
# order to make --fake-initial work.
call_command("migrate", "migrations", fake_initial=True, verbosity=0)
# Fake an apply
call_command("migrate", "migrations", fake=True, verbosity=0)
call_command("migrate", "migrations", fake=True, verbosity=0, database="other")
# Unmigrate everything
call_command("migrate", "migrations", "zero", verbosity=0)
call_command("migrate", "migrations", "zero", verbosity=0, database="other")
# Make sure it's all gone
for db in self.databases:
self.assertTableNotExists("migrations_author", using=db)
self.assertTableNotExists("migrations_tribble", using=db)
self.assertTableNotExists("migrations_book", using=db)
@skipUnlessDBFeature('ignores_table_name_case')
def test_migrate_fake_initial_case_insensitive(self):
with override_settings(MIGRATION_MODULES={
'migrations': 'migrations.test_fake_initial_case_insensitive.initial',
}):
call_command('migrate', 'migrations', '0001', verbosity=0)
call_command('migrate', 'migrations', 'zero', fake=True, verbosity=0)
with override_settings(MIGRATION_MODULES={
'migrations': 'migrations.test_fake_initial_case_insensitive.fake_initial',
}):
out = io.StringIO()
call_command(
'migrate',
'migrations',
'0001',
fake_initial=True,
stdout=out,
verbosity=1,
no_color=True,
)
self.assertIn(
'migrations.0001_initial... faked',
out.getvalue().lower(),
)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_fake_split_initial"})
def test_migrate_fake_split_initial(self):
"""
Split initial migrations can be faked with --fake-initial.
"""
call_command("migrate", "migrations", "0002", verbosity=0)
call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
out = io.StringIO()
with mock.patch('django.core.management.color.supports_color', lambda *args: False):
call_command("migrate", "migrations", "0002", fake_initial=True, stdout=out, verbosity=1)
value = out.getvalue().lower()
self.assertIn("migrations.0001_initial... faked", value)
self.assertIn("migrations.0002_second... faked", value)
# Fake an apply
call_command("migrate", "migrations", fake=True, verbosity=0)
# Unmigrate everything
call_command("migrate", "migrations", "zero", verbosity=0)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_conflict"})
def test_migrate_conflict_exit(self):
"""
migrate exits if it detects a conflict.
"""
with self.assertRaisesMessage(CommandError, "Conflicting migrations detected"):
call_command("migrate", "migrations")
@override_settings(MIGRATION_MODULES={
'migrations': 'migrations.test_migrations',
})
def test_migrate_check(self):
with self.assertRaises(SystemExit):
call_command('migrate', 'migrations', '0001', check_unapplied=True, verbosity=0)
self.assertTableNotExists('migrations_author')
self.assertTableNotExists('migrations_tribble')
self.assertTableNotExists('migrations_book')
@override_settings(MIGRATION_MODULES={
'migrations': 'migrations.test_migrations_plan',
})
def test_migrate_check_plan(self):
out = io.StringIO()
with self.assertRaises(SystemExit):
call_command(
'migrate',
'migrations',
'0001',
check_unapplied=True,
plan=True,
stdout=out,
no_color=True,
)
self.assertEqual(
'Planned operations:\n'
'migrations.0001_initial\n'
' Create model Salamander\n'
' Raw Python operation -> Grow salamander tail.\n',
out.getvalue(),
)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
def test_showmigrations_list(self):
"""
showmigrations --list displays migrations and whether or not they're
applied.
"""
out = io.StringIO()
with mock.patch('django.core.management.color.supports_color', lambda *args: True):
call_command("showmigrations", format='list', stdout=out, verbosity=0, no_color=False)
self.assertEqual(
'\x1b[1mmigrations\n\x1b[0m'
' [ ] 0001_initial\n'
' [ ] 0002_second\n',
out.getvalue().lower()
)
call_command("migrate", "migrations", "0001", verbosity=0)
out = io.StringIO()
# Giving the explicit app_label tests for selective `show_list` in the command
call_command("showmigrations", "migrations", format='list', stdout=out, verbosity=0, no_color=True)
self.assertEqual(
'migrations\n'
' [x] 0001_initial\n'
' [ ] 0002_second\n',
out.getvalue().lower()
)
out = io.StringIO()
# Applied datetimes are displayed at verbosity 2+.
call_command('showmigrations', 'migrations', stdout=out, verbosity=2, no_color=True)
migration1 = MigrationRecorder(connection).migration_qs.get(app='migrations', name='0001_initial')
self.assertEqual(
'migrations\n'
' [x] 0001_initial (applied at %s)\n'
' [ ] 0002_second\n' % migration1.applied.strftime('%Y-%m-%d %H:%M:%S'),
out.getvalue().lower()
)
# Cleanup by unmigrating everything
call_command("migrate", "migrations", "zero", verbosity=0)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_run_before"})
def test_showmigrations_plan(self):
"""
Tests --plan output of showmigrations command
"""
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out)
self.assertEqual(
"[ ] migrations.0001_initial\n"
"[ ] migrations.0003_third\n"
"[ ] migrations.0002_second\n",
out.getvalue().lower()
)
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out, verbosity=2)
self.assertEqual(
"[ ] migrations.0001_initial\n"
"[ ] migrations.0003_third ... (migrations.0001_initial)\n"
"[ ] migrations.0002_second ... (migrations.0001_initial, migrations.0003_third)\n",
out.getvalue().lower()
)
call_command("migrate", "migrations", "0003", verbosity=0)
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out)
self.assertEqual(
"[x] migrations.0001_initial\n"
"[x] migrations.0003_third\n"
"[ ] migrations.0002_second\n",
out.getvalue().lower()
)
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out, verbosity=2)
self.assertEqual(
"[x] migrations.0001_initial\n"
"[x] migrations.0003_third ... (migrations.0001_initial)\n"
"[ ] migrations.0002_second ... (migrations.0001_initial, migrations.0003_third)\n",
out.getvalue().lower()
)
# Cleanup by unmigrating everything
call_command("migrate", "migrations", "zero", verbosity=0)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_plan'})
def test_migrate_plan(self):
"""Tests migrate --plan output."""
out = io.StringIO()
# Show the plan up to the third migration.
call_command('migrate', 'migrations', '0003', plan=True, stdout=out, no_color=True)
self.assertEqual(
'Planned operations:\n'
'migrations.0001_initial\n'
' Create model Salamander\n'
' Raw Python operation -> Grow salamander tail.\n'
'migrations.0002_second\n'
' Create model Book\n'
" Raw SQL operation -> ['SELECT * FROM migrations_book']\n"
'migrations.0003_third\n'
' Create model Author\n'
" Raw SQL operation -> ['SELECT * FROM migrations_author']\n",
out.getvalue()
)
try:
# Migrate to the third migration.
call_command('migrate', 'migrations', '0003', verbosity=0)
out = io.StringIO()
# Show the plan for when there is nothing to apply.
call_command('migrate', 'migrations', '0003', plan=True, stdout=out, no_color=True)
self.assertEqual(
'Planned operations:\n'
' No planned migration operations.\n',
out.getvalue()
)
out = io.StringIO()
# Show the plan for reverse migration back to 0001.
call_command('migrate', 'migrations', '0001', plan=True, stdout=out, no_color=True)
self.assertEqual(
'Planned operations:\n'
'migrations.0003_third\n'
' Undo Create model Author\n'
" Raw SQL operation -> ['SELECT * FROM migrations_book']\n"
'migrations.0002_second\n'
' Undo Create model Book\n'
" Raw SQL operation -> ['SELECT * FROM migrations_salamand…\n",
out.getvalue()
)
out = io.StringIO()
# Show the migration plan to fourth, with truncated details.
call_command('migrate', 'migrations', '0004', plan=True, stdout=out, no_color=True)
self.assertEqual(
'Planned operations:\n'
'migrations.0004_fourth\n'
' Raw SQL operation -> SELECT * FROM migrations_author WHE…\n',
out.getvalue()
)
# Show the plan when an operation is irreversible.
# Migrate to the fourth migration.
call_command('migrate', 'migrations', '0004', verbosity=0)
out = io.StringIO()
call_command('migrate', 'migrations', '0003', plan=True, stdout=out, no_color=True)
self.assertEqual(
'Planned operations:\n'
'migrations.0004_fourth\n'
' Raw SQL operation -> IRREVERSIBLE\n',
out.getvalue()
)
out = io.StringIO()
call_command('migrate', 'migrations', '0005', plan=True, stdout=out, no_color=True)
# Operation is marked as irreversible only in the revert plan.
self.assertEqual(
'Planned operations:\n'
'migrations.0005_fifth\n'
' Raw Python operation\n'
' Raw Python operation\n'
' Raw Python operation -> Feed salamander.\n',
out.getvalue()
)
call_command('migrate', 'migrations', '0005', verbosity=0)
out = io.StringIO()
call_command('migrate', 'migrations', '0004', plan=True, stdout=out, no_color=True)
self.assertEqual(
'Planned operations:\n'
'migrations.0005_fifth\n'
' Raw Python operation -> IRREVERSIBLE\n'
' Raw Python operation -> IRREVERSIBLE\n'
' Raw Python operation\n',
out.getvalue()
)
finally:
# Cleanup by unmigrating everything: fake the irreversible, then
# migrate all to zero.
call_command('migrate', 'migrations', '0003', fake=True, verbosity=0)
call_command('migrate', 'migrations', 'zero', verbosity=0)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_empty'})
def test_showmigrations_no_migrations(self):
out = io.StringIO()
call_command('showmigrations', stdout=out, no_color=True)
self.assertEqual('migrations\n (no migrations)\n', out.getvalue().lower())
@override_settings(INSTALLED_APPS=['migrations.migrations_test_apps.unmigrated_app'])
def test_showmigrations_unmigrated_app(self):
out = io.StringIO()
call_command('showmigrations', 'unmigrated_app', stdout=out, no_color=True)
self.assertEqual('unmigrated_app\n (no migrations)\n', out.getvalue().lower())
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_empty"})
def test_showmigrations_plan_no_migrations(self):
"""
Tests --plan output of showmigrations command without migrations
"""
out = io.StringIO()
call_command('showmigrations', format='plan', stdout=out, no_color=True)
self.assertEqual('(no migrations)\n', out.getvalue().lower())
out = io.StringIO()
call_command('showmigrations', format='plan', stdout=out, verbosity=2, no_color=True)
self.assertEqual('(no migrations)\n', out.getvalue().lower())
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed_complex"})
def test_showmigrations_plan_squashed(self):
"""
Tests --plan output of showmigrations command with squashed migrations.
"""
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out)
self.assertEqual(
"[ ] migrations.1_auto\n"
"[ ] migrations.2_auto\n"
"[ ] migrations.3_squashed_5\n"
"[ ] migrations.6_auto\n"
"[ ] migrations.7_auto\n",
out.getvalue().lower()
)
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out, verbosity=2)
self.assertEqual(
"[ ] migrations.1_auto\n"
"[ ] migrations.2_auto ... (migrations.1_auto)\n"
"[ ] migrations.3_squashed_5 ... (migrations.2_auto)\n"
"[ ] migrations.6_auto ... (migrations.3_squashed_5)\n"
"[ ] migrations.7_auto ... (migrations.6_auto)\n",
out.getvalue().lower()
)
call_command("migrate", "migrations", "3_squashed_5", verbosity=0)
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out)
self.assertEqual(
"[x] migrations.1_auto\n"
"[x] migrations.2_auto\n"
"[x] migrations.3_squashed_5\n"
"[ ] migrations.6_auto\n"
"[ ] migrations.7_auto\n",
out.getvalue().lower()
)
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out, verbosity=2)
self.assertEqual(
"[x] migrations.1_auto\n"
"[x] migrations.2_auto ... (migrations.1_auto)\n"
"[x] migrations.3_squashed_5 ... (migrations.2_auto)\n"
"[ ] migrations.6_auto ... (migrations.3_squashed_5)\n"
"[ ] migrations.7_auto ... (migrations.6_auto)\n",
out.getvalue().lower()
)
@override_settings(INSTALLED_APPS=[
'migrations.migrations_test_apps.mutate_state_b',
'migrations.migrations_test_apps.alter_fk.author_app',
'migrations.migrations_test_apps.alter_fk.book_app',
])
def test_showmigrations_plan_single_app_label(self):
"""
`showmigrations --plan app_label` output with a single app_label.
"""
# Single app with no dependencies on other apps.
out = io.StringIO()
call_command('showmigrations', 'mutate_state_b', format='plan', stdout=out)
self.assertEqual(
'[ ] mutate_state_b.0001_initial\n'
'[ ] mutate_state_b.0002_add_field\n',
out.getvalue()
)
# Single app with dependencies.
out = io.StringIO()
call_command('showmigrations', 'author_app', format='plan', stdout=out)
self.assertEqual(
'[ ] author_app.0001_initial\n'
'[ ] book_app.0001_initial\n'
'[ ] author_app.0002_alter_id\n',
out.getvalue()
)
# Some migrations already applied.
call_command('migrate', 'author_app', '0001', verbosity=0)
out = io.StringIO()
call_command('showmigrations', 'author_app', format='plan', stdout=out)
self.assertEqual(
'[X] author_app.0001_initial\n'
'[ ] book_app.0001_initial\n'
'[ ] author_app.0002_alter_id\n',
out.getvalue()
)
# Cleanup by unmigrating author_app.
call_command('migrate', 'author_app', 'zero', verbosity=0)
@override_settings(INSTALLED_APPS=[
'migrations.migrations_test_apps.mutate_state_b',
'migrations.migrations_test_apps.alter_fk.author_app',
'migrations.migrations_test_apps.alter_fk.book_app',
])
def test_showmigrations_plan_multiple_app_labels(self):
"""
`showmigrations --plan app_label` output with multiple app_labels.
"""
# Multiple apps: author_app depends on book_app; mutate_state_b doesn't
# depend on other apps.
out = io.StringIO()
call_command('showmigrations', 'mutate_state_b', 'author_app', format='plan', stdout=out)
self.assertEqual(
'[ ] author_app.0001_initial\n'
'[ ] book_app.0001_initial\n'
'[ ] author_app.0002_alter_id\n'
'[ ] mutate_state_b.0001_initial\n'
'[ ] mutate_state_b.0002_add_field\n',
out.getvalue()
)
# Multiple apps: args order shouldn't matter (the same result is
# expected as above).
out = io.StringIO()
call_command('showmigrations', 'author_app', 'mutate_state_b', format='plan', stdout=out)
self.assertEqual(
'[ ] author_app.0001_initial\n'
'[ ] book_app.0001_initial\n'
'[ ] author_app.0002_alter_id\n'
'[ ] mutate_state_b.0001_initial\n'
'[ ] mutate_state_b.0002_add_field\n',
out.getvalue()
)
@override_settings(INSTALLED_APPS=['migrations.migrations_test_apps.unmigrated_app'])
def test_showmigrations_plan_app_label_no_migrations(self):
out = io.StringIO()
call_command('showmigrations', 'unmigrated_app', format='plan', stdout=out, no_color=True)
self.assertEqual('(no migrations)\n', out.getvalue())
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
def test_sqlmigrate_forwards(self):
"""
sqlmigrate outputs forward looking SQL.
"""
out = io.StringIO()
call_command("sqlmigrate", "migrations", "0001", stdout=out)
output = out.getvalue().lower()
index_tx_start = output.find(connection.ops.start_transaction_sql().lower())
index_op_desc_author = output.find('-- create model author')
index_create_table = output.find('create table')
index_op_desc_tribble = output.find('-- create model tribble')
index_op_desc_unique_together = output.find('-- alter unique_together')
index_tx_end = output.find(connection.ops.end_transaction_sql().lower())
if connection.features.can_rollback_ddl:
self.assertGreater(index_tx_start, -1, "Transaction start not found")
self.assertGreater(
index_tx_end, index_op_desc_unique_together,
"Transaction end not found or found before operation description (unique_together)"
)
self.assertGreater(
index_op_desc_author, index_tx_start,
"Operation description (author) not found or found before transaction start"
)
self.assertGreater(
index_create_table, index_op_desc_author,
"CREATE TABLE not found or found before operation description (author)"
)
self.assertGreater(
index_op_desc_tribble, index_create_table,
"Operation description (tribble) not found or found before CREATE TABLE (author)"
)
self.assertGreater(
index_op_desc_unique_together, index_op_desc_tribble,
"Operation description (unique_together) not found or found before operation description (tribble)"
)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
def test_sqlmigrate_backwards(self):
"""
sqlmigrate outputs reverse looking SQL.
"""
# Cannot generate the reverse SQL unless we've applied the migration.
call_command("migrate", "migrations", verbosity=0)
out = io.StringIO()
call_command("sqlmigrate", "migrations", "0001", stdout=out, backwards=True)
output = out.getvalue().lower()
index_tx_start = output.find(connection.ops.start_transaction_sql().lower())
index_op_desc_unique_together = output.find('-- alter unique_together')
index_op_desc_tribble = output.find('-- create model tribble')
index_op_desc_author = output.find('-- create model author')
index_drop_table = output.rfind('drop table')
index_tx_end = output.find(connection.ops.end_transaction_sql().lower())
if connection.features.can_rollback_ddl:
self.assertGreater(index_tx_start, -1, "Transaction start not found")
self.assertGreater(
index_tx_end, index_op_desc_unique_together,
"Transaction end not found or found before DROP TABLE"
)
self.assertGreater(
index_op_desc_unique_together, index_tx_start,
"Operation description (unique_together) not found or found before transaction start"
)
self.assertGreater(
index_op_desc_tribble, index_op_desc_unique_together,
"Operation description (tribble) not found or found before operation description (unique_together)"
)
self.assertGreater(
index_op_desc_author, index_op_desc_tribble,
"Operation description (author) not found or found before operation description (tribble)"
)
self.assertGreater(
index_drop_table, index_op_desc_author,
"DROP TABLE not found or found before operation description (author)"
)
# Cleanup by unmigrating everything
call_command("migrate", "migrations", "zero", verbosity=0)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_non_atomic"})
def test_sqlmigrate_for_non_atomic_migration(self):
"""
Transaction wrappers aren't shown for non-atomic migrations.
"""
out = io.StringIO()
call_command("sqlmigrate", "migrations", "0001", stdout=out)
output = out.getvalue().lower()
queries = [q.strip() for q in output.splitlines()]
if connection.ops.start_transaction_sql():
self.assertNotIn(connection.ops.start_transaction_sql().lower(), queries)
self.assertNotIn(connection.ops.end_transaction_sql().lower(), queries)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations'})
def test_sqlmigrate_for_non_transactional_databases(self):
"""
Transaction wrappers aren't shown for databases that don't support
transactional DDL.
"""
out = io.StringIO()
with mock.patch.object(connection.features, 'can_rollback_ddl', False):
call_command('sqlmigrate', 'migrations', '0001', stdout=out)
output = out.getvalue().lower()
queries = [q.strip() for q in output.splitlines()]
start_transaction_sql = connection.ops.start_transaction_sql()
if start_transaction_sql:
self.assertNotIn(start_transaction_sql.lower(), queries)
self.assertNotIn(connection.ops.end_transaction_sql().lower(), queries)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_squashed'})
def test_sqlmigrate_ambiguous_prefix_squashed_migrations(self):
msg = (
"More than one migration matches '0001' in app 'migrations'. "
"Please be more specific."
)
with self.assertRaisesMessage(CommandError, msg):
call_command('sqlmigrate', 'migrations', '0001')
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_squashed'})
def test_sqlmigrate_squashed_migration(self):
out = io.StringIO()
call_command('sqlmigrate', 'migrations', '0001_squashed_0002', stdout=out)
output = out.getvalue().lower()
self.assertIn('-- create model author', output)
self.assertIn('-- create model book', output)
self.assertNotIn('-- create model tribble', output)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_squashed'})
def test_sqlmigrate_replaced_migration(self):
out = io.StringIO()
call_command('sqlmigrate', 'migrations', '0001_initial', stdout=out)
output = out.getvalue().lower()
self.assertIn('-- create model author', output)
self.assertIn('-- create model tribble', output)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_no_operations'})
def test_migrations_no_operations(self):
err = io.StringIO()
call_command('sqlmigrate', 'migrations', '0001_initial', stderr=err)
self.assertEqual(err.getvalue(), 'No operations found.\n')
@override_settings(
INSTALLED_APPS=[
"migrations.migrations_test_apps.migrated_app",
"migrations.migrations_test_apps.migrated_unapplied_app",
"migrations.migrations_test_apps.unmigrated_app",
],
)
def test_regression_22823_unmigrated_fk_to_migrated_model(self):
"""
Assuming you have 3 apps, `A`, `B`, and `C`, such that:
* `A` has migrations
* `B` has a migration we want to apply
* `C` has no migrations, but has an FK to `A`
When we try to migrate "B", an exception occurs because the
"B" was not included in the ProjectState that is used to detect
soft-applied migrations (#22823).
"""
call_command("migrate", "migrated_unapplied_app", stdout=io.StringIO())
# unmigrated_app.SillyModel has a foreign key to 'migrations.Tribble',
# but that model is only defined in a migration, so the global app
# registry never sees it and the reference is left dangling. Remove it
# to avoid problems in subsequent tests.
del apps._pending_operations[('migrations', 'tribble')]
@override_settings(INSTALLED_APPS=['migrations.migrations_test_apps.unmigrated_app_syncdb'])
def test_migrate_syncdb_deferred_sql_executed_with_schemaeditor(self):
"""
For an app without migrations, editor.execute() is used for executing
the syncdb deferred SQL.
"""
stdout = io.StringIO()
with mock.patch.object(BaseDatabaseSchemaEditor, 'execute') as execute:
call_command('migrate', run_syncdb=True, verbosity=1, stdout=stdout, no_color=True)
create_table_count = len([call for call in execute.mock_calls if 'CREATE TABLE' in str(call)])
self.assertEqual(create_table_count, 2)
# There's at least one deferred SQL for creating the foreign key
# index.
self.assertGreater(len(execute.mock_calls), 2)
stdout = stdout.getvalue()
self.assertIn('Synchronize unmigrated apps: unmigrated_app_syncdb', stdout)
self.assertIn('Creating tables...', stdout)
table_name = truncate_name('unmigrated_app_syncdb_classroom', connection.ops.max_name_length())
self.assertIn('Creating table %s' % table_name, stdout)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations'})
def test_migrate_syncdb_app_with_migrations(self):
msg = "Can't use run_syncdb with app 'migrations' as it has migrations."
with self.assertRaisesMessage(CommandError, msg):
call_command('migrate', 'migrations', run_syncdb=True, verbosity=0)
@override_settings(INSTALLED_APPS=[
'migrations.migrations_test_apps.unmigrated_app_syncdb',
'migrations.migrations_test_apps.unmigrated_app_simple',
])
def test_migrate_syncdb_app_label(self):
"""
Running migrate --run-syncdb with an app_label only creates tables for
the specified app.
"""
stdout = io.StringIO()
with mock.patch.object(BaseDatabaseSchemaEditor, 'execute') as execute:
call_command('migrate', 'unmigrated_app_syncdb', run_syncdb=True, stdout=stdout)
create_table_count = len([call for call in execute.mock_calls if 'CREATE TABLE' in str(call)])
self.assertEqual(create_table_count, 2)
self.assertGreater(len(execute.mock_calls), 2)
self.assertIn('Synchronize unmigrated app: unmigrated_app_syncdb', stdout.getvalue())
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"})
def test_migrate_record_replaced(self):
"""
Running a single squashed migration should record all of the original
replaced migrations as run.
"""
recorder = MigrationRecorder(connection)
out = io.StringIO()
call_command("migrate", "migrations", verbosity=0)
call_command("showmigrations", "migrations", stdout=out, no_color=True)
self.assertEqual(
'migrations\n'
' [x] 0001_squashed_0002 (2 squashed migrations)\n',
out.getvalue().lower()
)
applied_migrations = recorder.applied_migrations()
self.assertIn(("migrations", "0001_initial"), applied_migrations)
self.assertIn(("migrations", "0002_second"), applied_migrations)
self.assertIn(("migrations", "0001_squashed_0002"), applied_migrations)
# Rollback changes
call_command("migrate", "migrations", "zero", verbosity=0)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"})
def test_migrate_record_squashed(self):
"""
Running migrate for a squashed migration should record as run
if all of the replaced migrations have been run (#25231).
"""
recorder = MigrationRecorder(connection)
recorder.record_applied("migrations", "0001_initial")
recorder.record_applied("migrations", "0002_second")
out = io.StringIO()
call_command("migrate", "migrations", verbosity=0)
call_command("showmigrations", "migrations", stdout=out, no_color=True)
self.assertEqual(
'migrations\n'
' [x] 0001_squashed_0002 (2 squashed migrations)\n',
out.getvalue().lower()
)
self.assertIn(
("migrations", "0001_squashed_0002"),
recorder.applied_migrations()
)
# No changes were actually applied so there is nothing to rollback
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations'})
def test_migrate_inconsistent_history(self):
"""
Running migrate with some migrations applied before their dependencies
should not be allowed.
"""
recorder = MigrationRecorder(connection)
recorder.record_applied("migrations", "0002_second")
msg = "Migration migrations.0002_second is applied before its dependency migrations.0001_initial"
with self.assertRaisesMessage(InconsistentMigrationHistory, msg):
call_command("migrate")
applied_migrations = recorder.applied_migrations()
self.assertNotIn(("migrations", "0001_initial"), applied_migrations)
class MakeMigrationsTests(MigrationTestBase):
"""
Tests running the makemigrations command.
"""
def setUp(self):
super().setUp()
self._old_models = apps.app_configs['migrations'].models.copy()
def tearDown(self):
apps.app_configs['migrations'].models = self._old_models
apps.all_models['migrations'] = self._old_models
apps.clear_cache()
super().tearDown()
def test_files_content(self):
self.assertTableNotExists("migrations_unicodemodel")
apps.register_model('migrations', UnicodeModel)
with self.temporary_migration_module() as migration_dir:
call_command("makemigrations", "migrations", verbosity=0)
# Check for empty __init__.py file in migrations folder
init_file = os.path.join(migration_dir, "__init__.py")
self.assertTrue(os.path.exists(init_file))
with open(init_file) as fp:
content = fp.read()
self.assertEqual(content, '')
# Check for existing 0001_initial.py file in migration folder
initial_file = os.path.join(migration_dir, "0001_initial.py")
self.assertTrue(os.path.exists(initial_file))
with open(initial_file, encoding='utf-8') as fp:
content = fp.read()
self.assertIn('migrations.CreateModel', content)
self.assertIn('initial = True', content)
self.assertIn('úñí©óðé µóðéø', content) # Meta.verbose_name
self.assertIn('úñí©óðé µóðéøß', content) # Meta.verbose_name_plural
self.assertIn('ÚÑÍ¢ÓÐÉ', content) # title.verbose_name
self.assertIn('“Ðjáñgó”', content) # title.default
def test_makemigrations_order(self):
"""
makemigrations should recognize number-only migrations (0001.py).
"""
module = 'migrations.test_migrations_order'
with self.temporary_migration_module(module=module) as migration_dir:
if hasattr(importlib, 'invalidate_caches'):
# importlib caches os.listdir() on some platforms like macOS
# (#23850).
importlib.invalidate_caches()
call_command('makemigrations', 'migrations', '--empty', '-n', 'a', '-v', '0')
self.assertTrue(os.path.exists(os.path.join(migration_dir, '0002_a.py')))
def test_makemigrations_empty_connections(self):
empty_connections = ConnectionHandler({'default': {}})
with mock.patch('django.core.management.commands.makemigrations.connections', new=empty_connections):
# with no apps
out = io.StringIO()
call_command('makemigrations', stdout=out)
self.assertIn('No changes detected', out.getvalue())
# with an app
with self.temporary_migration_module() as migration_dir:
call_command('makemigrations', 'migrations', verbosity=0)
init_file = os.path.join(migration_dir, '__init__.py')
self.assertTrue(os.path.exists(init_file))
@override_settings(INSTALLED_APPS=['migrations', 'migrations2'])
def test_makemigrations_consistency_checks_respect_routers(self):
"""
The history consistency checks in makemigrations respect
settings.DATABASE_ROUTERS.
"""
def patched_has_table(migration_recorder):
if migration_recorder.connection is connections['other']:
raise Exception('Other connection')
else:
return mock.DEFAULT
self.assertTableNotExists('migrations_unicodemodel')
apps.register_model('migrations', UnicodeModel)
with mock.patch.object(
MigrationRecorder, 'has_table',
autospec=True, side_effect=patched_has_table) as has_table:
with self.temporary_migration_module() as migration_dir:
call_command("makemigrations", "migrations", verbosity=0)
initial_file = os.path.join(migration_dir, "0001_initial.py")
self.assertTrue(os.path.exists(initial_file))
self.assertEqual(has_table.call_count, 1) # 'default' is checked
# Router says not to migrate 'other' so consistency shouldn't
# be checked.
with self.settings(DATABASE_ROUTERS=['migrations.routers.TestRouter']):
call_command('makemigrations', 'migrations', verbosity=0)
self.assertEqual(has_table.call_count, 2) # 'default' again
# With a router that doesn't prohibit migrating 'other',
# consistency is checked.
with self.settings(DATABASE_ROUTERS=['migrations.routers.DefaultOtherRouter']):
with self.assertRaisesMessage(Exception, 'Other connection'):
call_command('makemigrations', 'migrations', verbosity=0)
self.assertEqual(has_table.call_count, 4) # 'default' and 'other'
# With a router that doesn't allow migrating on any database,
# no consistency checks are made.
with self.settings(DATABASE_ROUTERS=['migrations.routers.TestRouter']):
with mock.patch.object(TestRouter, 'allow_migrate', return_value=False) as allow_migrate:
call_command('makemigrations', 'migrations', verbosity=0)
allow_migrate.assert_any_call('other', 'migrations', model_name='UnicodeModel')
# allow_migrate() is called with the correct arguments.
self.assertGreater(len(allow_migrate.mock_calls), 0)
called_aliases = set()
for mock_call in allow_migrate.mock_calls:
_, call_args, call_kwargs = mock_call
connection_alias, app_name = call_args
called_aliases.add(connection_alias)
# Raises an error if invalid app_name/model_name occurs.
apps.get_app_config(app_name).get_model(call_kwargs['model_name'])
self.assertEqual(called_aliases, set(connections))
self.assertEqual(has_table.call_count, 4)
def test_failing_migration(self):
# If a migration fails to serialize, it shouldn't generate an empty file. #21280
apps.register_model('migrations', UnserializableModel)
with self.temporary_migration_module() as migration_dir:
with self.assertRaisesMessage(ValueError, 'Cannot serialize'):
call_command("makemigrations", "migrations", verbosity=0)
initial_file = os.path.join(migration_dir, "0001_initial.py")
self.assertFalse(os.path.exists(initial_file))
def test_makemigrations_conflict_exit(self):
"""
makemigrations exits if it detects a conflict.
"""
with self.temporary_migration_module(module="migrations.test_migrations_conflict"):
with self.assertRaises(CommandError) as context:
call_command("makemigrations")
exception_message = str(context.exception)
self.assertIn(
'Conflicting migrations detected; multiple leaf nodes '
'in the migration graph:',
exception_message
)
self.assertIn('0002_second', exception_message)
self.assertIn('0002_conflicting_second', exception_message)
self.assertIn('in migrations', exception_message)
self.assertIn("To fix them run 'python manage.py makemigrations --merge'", exception_message)
def test_makemigrations_merge_no_conflict(self):
"""
makemigrations exits if in merge mode with no conflicts.
"""
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations"):
call_command("makemigrations", merge=True, stdout=out)
self.assertIn("No conflicts detected to merge.", out.getvalue())
def test_makemigrations_empty_no_app_specified(self):
"""
makemigrations exits if no app is specified with 'empty' mode.
"""
msg = 'You must supply at least one app label when using --empty.'
with self.assertRaisesMessage(CommandError, msg):
call_command("makemigrations", empty=True)
def test_makemigrations_empty_migration(self):
"""
makemigrations properly constructs an empty migration.
"""
with self.temporary_migration_module() as migration_dir:
call_command("makemigrations", "migrations", empty=True, verbosity=0)
# Check for existing 0001_initial.py file in migration folder
initial_file = os.path.join(migration_dir, "0001_initial.py")
self.assertTrue(os.path.exists(initial_file))
with open(initial_file, encoding='utf-8') as fp:
content = fp.read()
# Remove all whitespace to check for empty dependencies and operations
content = content.replace(' ', '')
self.assertIn('dependencies=[\n]', content)
self.assertIn('operations=[\n]', content)
@override_settings(MIGRATION_MODULES={"migrations": None})
def test_makemigrations_disabled_migrations_for_app(self):
"""
makemigrations raises a nice error when migrations are disabled for an
app.
"""
msg = (
"Django can't create migrations for app 'migrations' because migrations "
"have been disabled via the MIGRATION_MODULES setting."
)
with self.assertRaisesMessage(ValueError, msg):
call_command("makemigrations", "migrations", empty=True, verbosity=0)
def test_makemigrations_no_changes_no_apps(self):
"""
makemigrations exits when there are no changes and no apps are specified.
"""
out = io.StringIO()
call_command("makemigrations", stdout=out)
self.assertIn("No changes detected", out.getvalue())
def test_makemigrations_no_changes(self):
"""
makemigrations exits when there are no changes to an app.
"""
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
call_command("makemigrations", "migrations", stdout=out)
self.assertIn("No changes detected in app 'migrations'", out.getvalue())
def test_makemigrations_no_apps_initial(self):
"""
makemigrations should detect initial is needed on empty migration
modules if no app provided.
"""
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_empty"):
call_command("makemigrations", stdout=out)
self.assertIn("0001_initial.py", out.getvalue())
def test_makemigrations_no_init(self):
"""Migration directories without an __init__.py file are allowed."""
out = io.StringIO()
with self.temporary_migration_module(module='migrations.test_migrations_no_init'):
call_command('makemigrations', stdout=out)
self.assertIn('0001_initial.py', out.getvalue())
def test_makemigrations_migrations_announce(self):
"""
makemigrations announces the migration at the default verbosity level.
"""
out = io.StringIO()
with self.temporary_migration_module():
call_command("makemigrations", "migrations", stdout=out)
self.assertIn("Migrations for 'migrations'", out.getvalue())
def test_makemigrations_no_common_ancestor(self):
"""
makemigrations fails to merge migrations with no common ancestor.
"""
with self.assertRaises(ValueError) as context:
with self.temporary_migration_module(module="migrations.test_migrations_no_ancestor"):
call_command("makemigrations", "migrations", merge=True)
exception_message = str(context.exception)
self.assertIn("Could not find common ancestor of", exception_message)
self.assertIn("0002_second", exception_message)
self.assertIn("0002_conflicting_second", exception_message)
def test_makemigrations_interactive_reject(self):
"""
makemigrations enters and exits interactive mode properly.
"""
# Monkeypatch interactive questioner to auto reject
with mock.patch('builtins.input', mock.Mock(return_value='N')):
with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
call_command("makemigrations", "migrations", name="merge", merge=True, interactive=True, verbosity=0)
merge_file = os.path.join(migration_dir, '0003_merge.py')
self.assertFalse(os.path.exists(merge_file))
def test_makemigrations_interactive_accept(self):
"""
makemigrations enters interactive mode and merges properly.
"""
# Monkeypatch interactive questioner to auto accept
with mock.patch('builtins.input', mock.Mock(return_value='y')):
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
call_command("makemigrations", "migrations", name="merge", merge=True, interactive=True, stdout=out)
merge_file = os.path.join(migration_dir, '0003_merge.py')
self.assertTrue(os.path.exists(merge_file))
self.assertIn("Created new merge migration", out.getvalue())
@mock.patch('django.db.migrations.utils.datetime')
def test_makemigrations_default_merge_name(self, mock_datetime):
mock_datetime.datetime.now.return_value = datetime.datetime(2016, 1, 2, 3, 4)
with mock.patch('builtins.input', mock.Mock(return_value='y')):
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
call_command("makemigrations", "migrations", merge=True, interactive=True, stdout=out)
merge_file = os.path.join(migration_dir, '0003_merge_20160102_0304.py')
self.assertTrue(os.path.exists(merge_file))
self.assertIn("Created new merge migration", out.getvalue())
def test_makemigrations_non_interactive_not_null_addition(self):
"""
Non-interactive makemigrations fails when a default is missing on a
new not-null field.
"""
class SillyModel(models.Model):
silly_field = models.BooleanField(default=False)
silly_int = models.IntegerField()
class Meta:
app_label = "migrations"
out = io.StringIO()
with self.assertRaises(SystemExit):
with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
call_command("makemigrations", "migrations", interactive=False, stdout=out)
def test_makemigrations_non_interactive_not_null_alteration(self):
"""
Non-interactive makemigrations fails when a default is missing on a
field changed to not-null.
"""
class Author(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField()
age = models.IntegerField(default=0)
class Meta:
app_label = "migrations"
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations"):
call_command("makemigrations", "migrations", interactive=False, stdout=out)
self.assertIn("Alter field slug on author", out.getvalue())
def test_makemigrations_non_interactive_no_model_rename(self):
"""
makemigrations adds and removes a possible model rename in
non-interactive mode.
"""
class RenamedModel(models.Model):
silly_field = models.BooleanField(default=False)
class Meta:
app_label = "migrations"
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
call_command("makemigrations", "migrations", interactive=False, stdout=out)
self.assertIn("Delete model SillyModel", out.getvalue())
self.assertIn("Create model RenamedModel", out.getvalue())
def test_makemigrations_non_interactive_no_field_rename(self):
"""
makemigrations adds and removes a possible field rename in
non-interactive mode.
"""
class SillyModel(models.Model):
silly_rename = models.BooleanField(default=False)
class Meta:
app_label = "migrations"
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
call_command("makemigrations", "migrations", interactive=False, stdout=out)
self.assertIn("Remove field silly_field from sillymodel", out.getvalue())
self.assertIn("Add field silly_rename to sillymodel", out.getvalue())
def test_makemigrations_handle_merge(self):
"""
makemigrations properly merges the conflicting migrations with --noinput.
"""
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
call_command("makemigrations", "migrations", name="merge", merge=True, interactive=False, stdout=out)
merge_file = os.path.join(migration_dir, '0003_merge.py')
self.assertTrue(os.path.exists(merge_file))
output = out.getvalue()
self.assertIn("Merging migrations", output)
self.assertIn("Branch 0002_second", output)
self.assertIn("Branch 0002_conflicting_second", output)
self.assertIn("Created new merge migration", output)
def test_makemigration_merge_dry_run(self):
"""
makemigrations respects --dry-run option when fixing migration
conflicts (#24427).
"""
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
call_command(
"makemigrations", "migrations", name="merge", dry_run=True,
merge=True, interactive=False, stdout=out,
)
merge_file = os.path.join(migration_dir, '0003_merge.py')
self.assertFalse(os.path.exists(merge_file))
output = out.getvalue()
self.assertIn("Merging migrations", output)
self.assertIn("Branch 0002_second", output)
self.assertIn("Branch 0002_conflicting_second", output)
self.assertNotIn("Created new merge migration", output)
def test_makemigration_merge_dry_run_verbosity_3(self):
"""
`makemigrations --merge --dry-run` writes the merge migration file to
stdout with `verbosity == 3` (#24427).
"""
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
call_command(
"makemigrations", "migrations", name="merge", dry_run=True,
merge=True, interactive=False, stdout=out, verbosity=3,
)
merge_file = os.path.join(migration_dir, '0003_merge.py')
self.assertFalse(os.path.exists(merge_file))
output = out.getvalue()
self.assertIn("Merging migrations", output)
self.assertIn("Branch 0002_second", output)
self.assertIn("Branch 0002_conflicting_second", output)
self.assertNotIn("Created new merge migration", output)
# Additional output caused by verbosity 3
# The complete merge migration file that would be written
self.assertIn("class Migration(migrations.Migration):", output)
self.assertIn("dependencies = [", output)
self.assertIn("('migrations', '0002_second')", output)
self.assertIn("('migrations', '0002_conflicting_second')", output)
self.assertIn("operations = [", output)
self.assertIn("]", output)
def test_makemigrations_dry_run(self):
"""
`makemigrations --dry-run` should not ask for defaults.
"""
class SillyModel(models.Model):
silly_field = models.BooleanField(default=False)
silly_date = models.DateField() # Added field without a default
class Meta:
app_label = "migrations"
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
call_command("makemigrations", "migrations", dry_run=True, stdout=out)
# Output the expected changes directly, without asking for defaults
self.assertIn("Add field silly_date to sillymodel", out.getvalue())
def test_makemigrations_dry_run_verbosity_3(self):
"""
Allow `makemigrations --dry-run` to output the migrations file to
stdout (with verbosity == 3).
"""
class SillyModel(models.Model):
silly_field = models.BooleanField(default=False)
silly_char = models.CharField(default="")
class Meta:
app_label = "migrations"
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
call_command("makemigrations", "migrations", dry_run=True, stdout=out, verbosity=3)
# Normal --dry-run output
self.assertIn("- Add field silly_char to sillymodel", out.getvalue())
# Additional output caused by verbosity 3
# The complete migrations file that would be written
self.assertIn("class Migration(migrations.Migration):", out.getvalue())
self.assertIn("dependencies = [", out.getvalue())
self.assertIn("('migrations', '0001_initial'),", out.getvalue())
self.assertIn("migrations.AddField(", out.getvalue())
self.assertIn("model_name='sillymodel',", out.getvalue())
self.assertIn("name='silly_char',", out.getvalue())
def test_makemigrations_migrations_modules_path_not_exist(self):
"""
makemigrations creates migrations when specifying a custom location
for migration files using MIGRATION_MODULES if the custom path
doesn't already exist.
"""
class SillyModel(models.Model):
silly_field = models.BooleanField(default=False)
class Meta:
app_label = "migrations"
out = io.StringIO()
migration_module = "migrations.test_migrations_path_doesnt_exist.foo.bar"
with self.temporary_migration_module(module=migration_module) as migration_dir:
call_command("makemigrations", "migrations", stdout=out)
# Migrations file is actually created in the expected path.
initial_file = os.path.join(migration_dir, "0001_initial.py")
self.assertTrue(os.path.exists(initial_file))
# Command output indicates the migration is created.
self.assertIn(" - Create model SillyModel", out.getvalue())
@override_settings(MIGRATION_MODULES={'migrations': 'some.nonexistent.path'})
def test_makemigrations_migrations_modules_nonexistent_toplevel_package(self):
msg = (
'Could not locate an appropriate location to create migrations '
'package some.nonexistent.path. Make sure the toplevel package '
'exists and can be imported.'
)
with self.assertRaisesMessage(ValueError, msg):
call_command('makemigrations', 'migrations', empty=True, verbosity=0)
def test_makemigrations_interactive_by_default(self):
"""
The user is prompted to merge by default if there are conflicts and
merge is True. Answer negative to differentiate it from behavior when
--noinput is specified.
"""
# Monkeypatch interactive questioner to auto reject
out = io.StringIO()
with mock.patch('builtins.input', mock.Mock(return_value='N')):
with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
call_command("makemigrations", "migrations", name="merge", merge=True, stdout=out)
merge_file = os.path.join(migration_dir, '0003_merge.py')
# This will fail if interactive is False by default
self.assertFalse(os.path.exists(merge_file))
self.assertNotIn("Created new merge migration", out.getvalue())
@override_settings(
INSTALLED_APPS=[
"migrations",
"migrations.migrations_test_apps.unspecified_app_with_conflict"])
def test_makemigrations_unspecified_app_with_conflict_no_merge(self):
"""
makemigrations does not raise a CommandError when an unspecified app
has conflicting migrations.
"""
with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
call_command("makemigrations", "migrations", merge=False, verbosity=0)
@override_settings(
INSTALLED_APPS=[
"migrations.migrations_test_apps.migrated_app",
"migrations.migrations_test_apps.unspecified_app_with_conflict"])
def test_makemigrations_unspecified_app_with_conflict_merge(self):
"""
makemigrations does not create a merge for an unspecified app even if
it has conflicting migrations.
"""
# Monkeypatch interactive questioner to auto accept
with mock.patch('builtins.input', mock.Mock(return_value='y')):
out = io.StringIO()
with self.temporary_migration_module(app_label="migrated_app") as migration_dir:
call_command("makemigrations", "migrated_app", name="merge", merge=True, interactive=True, stdout=out)
merge_file = os.path.join(migration_dir, '0003_merge.py')
self.assertFalse(os.path.exists(merge_file))
self.assertIn("No conflicts detected to merge.", out.getvalue())
@override_settings(
INSTALLED_APPS=[
"migrations.migrations_test_apps.migrated_app",
"migrations.migrations_test_apps.conflicting_app_with_dependencies"])
def test_makemigrations_merge_dont_output_dependency_operations(self):
"""
makemigrations --merge does not output any operations from apps that
don't belong to a given app.
"""
# Monkeypatch interactive questioner to auto accept
with mock.patch('builtins.input', mock.Mock(return_value='N')):
out = io.StringIO()
with mock.patch('django.core.management.color.supports_color', lambda *args: False):
call_command(
"makemigrations", "conflicting_app_with_dependencies",
merge=True, interactive=True, stdout=out
)
val = out.getvalue().lower()
self.assertIn('merging conflicting_app_with_dependencies\n', val)
self.assertIn(
' branch 0002_conflicting_second\n'
' - create model something\n',
val
)
self.assertIn(
' branch 0002_second\n'
' - delete model tribble\n'
' - remove field silly_field from author\n'
' - add field rating to author\n'
' - create model book\n',
val
)
def test_makemigrations_with_custom_name(self):
"""
makemigrations --name generate a custom migration name.
"""
with self.temporary_migration_module() as migration_dir:
def cmd(migration_count, migration_name, *args):
call_command("makemigrations", "migrations", "--verbosity", "0", "--name", migration_name, *args)
migration_file = os.path.join(migration_dir, "%s_%s.py" % (migration_count, migration_name))
# Check for existing migration file in migration folder
self.assertTrue(os.path.exists(migration_file))
with open(migration_file, encoding='utf-8') as fp:
content = fp.read()
content = content.replace(" ", "")
return content
# generate an initial migration
migration_name_0001 = "my_initial_migration"
content = cmd("0001", migration_name_0001)
self.assertIn("dependencies=[\n]", content)
# importlib caches os.listdir() on some platforms like macOS
# (#23850).
if hasattr(importlib, 'invalidate_caches'):
importlib.invalidate_caches()
# generate an empty migration
migration_name_0002 = "my_custom_migration"
content = cmd("0002", migration_name_0002, "--empty")
self.assertIn("dependencies=[\n('migrations','0001_%s'),\n]" % migration_name_0001, content)
self.assertIn("operations=[\n]", content)
def test_makemigrations_with_invalid_custom_name(self):
msg = 'The migration name must be a valid Python identifier.'
with self.assertRaisesMessage(CommandError, msg):
call_command('makemigrations', 'migrations', '--name', 'invalid name', '--empty')
def test_makemigrations_check(self):
"""
makemigrations --check should exit with a non-zero status when
there are changes to an app requiring migrations.
"""
with self.temporary_migration_module():
with self.assertRaises(SystemExit):
call_command("makemigrations", "--check", "migrations", verbosity=0)
with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
call_command("makemigrations", "--check", "migrations", verbosity=0)
def test_makemigrations_migration_path_output(self):
"""
makemigrations should print the relative paths to the migrations unless
they are outside of the current tree, in which case the absolute path
should be shown.
"""
out = io.StringIO()
apps.register_model('migrations', UnicodeModel)
with self.temporary_migration_module() as migration_dir:
call_command("makemigrations", "migrations", stdout=out)
self.assertIn(os.path.join(migration_dir, '0001_initial.py'), out.getvalue())
def test_makemigrations_migration_path_output_valueerror(self):
"""
makemigrations prints the absolute path if os.path.relpath() raises a
ValueError when it's impossible to obtain a relative path, e.g. on
Windows if Django is installed on a different drive than where the
migration files are created.
"""
out = io.StringIO()
with self.temporary_migration_module() as migration_dir:
with mock.patch('os.path.relpath', side_effect=ValueError):
call_command('makemigrations', 'migrations', stdout=out)
self.assertIn(os.path.join(migration_dir, '0001_initial.py'), out.getvalue())
def test_makemigrations_inconsistent_history(self):
"""
makemigrations should raise InconsistentMigrationHistory exception if
there are some migrations applied before their dependencies.
"""
recorder = MigrationRecorder(connection)
recorder.record_applied('migrations', '0002_second')
msg = "Migration migrations.0002_second is applied before its dependency migrations.0001_initial"
with self.temporary_migration_module(module="migrations.test_migrations"):
with self.assertRaisesMessage(InconsistentMigrationHistory, msg):
call_command("makemigrations")
@mock.patch('builtins.input', return_value='1')
@mock.patch('django.db.migrations.questioner.sys.stdin', mock.MagicMock(encoding=sys.getdefaultencoding()))
def test_makemigrations_auto_now_add_interactive(self, *args):
"""
makemigrations prompts the user when adding auto_now_add to an existing
model.
"""
class Entry(models.Model):
title = models.CharField(max_length=255)
creation_date = models.DateTimeField(auto_now_add=True)
class Meta:
app_label = 'migrations'
# Monkeypatch interactive questioner to auto accept
with mock.patch('django.db.migrations.questioner.sys.stdout', new_callable=io.StringIO) as prompt_stdout:
out = io.StringIO()
with self.temporary_migration_module(module='migrations.test_auto_now_add'):
call_command('makemigrations', 'migrations', interactive=True, stdout=out)
output = out.getvalue()
prompt_output = prompt_stdout.getvalue()
self.assertIn("You can accept the default 'timezone.now' by pressing 'Enter'", prompt_output)
self.assertIn("Add field creation_date to entry", output)
class SquashMigrationsTests(MigrationTestBase):
"""
Tests running the squashmigrations command.
"""
def test_squashmigrations_squashes(self):
"""
squashmigrations squashes migrations.
"""
with self.temporary_migration_module(module="migrations.test_migrations") as migration_dir:
call_command("squashmigrations", "migrations", "0002", interactive=False, verbosity=0)
squashed_migration_file = os.path.join(migration_dir, "0001_squashed_0002_second.py")
self.assertTrue(os.path.exists(squashed_migration_file))
def test_squashmigrations_initial_attribute(self):
with self.temporary_migration_module(module="migrations.test_migrations") as migration_dir:
call_command("squashmigrations", "migrations", "0002", interactive=False, verbosity=0)
squashed_migration_file = os.path.join(migration_dir, "0001_squashed_0002_second.py")
with open(squashed_migration_file, encoding='utf-8') as fp:
content = fp.read()
self.assertIn("initial = True", content)
def test_squashmigrations_optimizes(self):
"""
squashmigrations optimizes operations.
"""
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations"):
call_command("squashmigrations", "migrations", "0002", interactive=False, verbosity=1, stdout=out)
self.assertIn("Optimized from 8 operations to 2 operations.", out.getvalue())
def test_ticket_23799_squashmigrations_no_optimize(self):
"""
squashmigrations --no-optimize doesn't optimize operations.
"""
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations"):
call_command("squashmigrations", "migrations", "0002",
interactive=False, verbosity=1, no_optimize=True, stdout=out)
self.assertIn("Skipping optimization", out.getvalue())
def test_squashmigrations_valid_start(self):
"""
squashmigrations accepts a starting migration.
"""
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_no_changes") as migration_dir:
call_command("squashmigrations", "migrations", "0002", "0003",
interactive=False, verbosity=1, stdout=out)
squashed_migration_file = os.path.join(migration_dir, "0002_second_squashed_0003_third.py")
with open(squashed_migration_file, encoding='utf-8') as fp:
content = fp.read()
self.assertIn(" ('migrations', '0001_initial')", content)
self.assertNotIn("initial = True", content)
out = out.getvalue()
self.assertNotIn(" - 0001_initial", out)
self.assertIn(" - 0002_second", out)
self.assertIn(" - 0003_third", out)
def test_squashmigrations_invalid_start(self):
"""
squashmigrations doesn't accept a starting migration after the ending migration.
"""
with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
msg = (
"The migration 'migrations.0003_third' cannot be found. Maybe "
"it comes after the migration 'migrations.0002_second'"
)
with self.assertRaisesMessage(CommandError, msg):
call_command("squashmigrations", "migrations", "0003", "0002", interactive=False, verbosity=0)
def test_squashed_name_with_start_migration_name(self):
"""--squashed-name specifies the new migration's name."""
squashed_name = 'squashed_name'
with self.temporary_migration_module(module='migrations.test_migrations') as migration_dir:
call_command(
'squashmigrations', 'migrations', '0001', '0002',
squashed_name=squashed_name, interactive=False, verbosity=0,
)
squashed_migration_file = os.path.join(migration_dir, '0001_%s.py' % squashed_name)
self.assertTrue(os.path.exists(squashed_migration_file))
def test_squashed_name_without_start_migration_name(self):
"""--squashed-name also works if a start migration is omitted."""
squashed_name = 'squashed_name'
with self.temporary_migration_module(module="migrations.test_migrations") as migration_dir:
call_command(
'squashmigrations', 'migrations', '0001',
squashed_name=squashed_name, interactive=False, verbosity=0,
)
squashed_migration_file = os.path.join(migration_dir, '0001_%s.py' % squashed_name)
self.assertTrue(os.path.exists(squashed_migration_file))
class AppLabelErrorTests(TestCase):
"""
This class inherits TestCase because MigrationTestBase uses
`available_apps = ['migrations']` which means that it's the only installed
app. 'django.contrib.auth' must be in INSTALLED_APPS for some of these
tests.
"""
nonexistent_app_error = "No installed app with label 'nonexistent_app'."
did_you_mean_auth_error = (
"No installed app with label 'django.contrib.auth'. Did you mean "
"'auth'?"
)
def test_makemigrations_nonexistent_app_label(self):
err = io.StringIO()
with self.assertRaises(SystemExit):
call_command('makemigrations', 'nonexistent_app', stderr=err)
self.assertIn(self.nonexistent_app_error, err.getvalue())
def test_makemigrations_app_name_specified_as_label(self):
err = io.StringIO()
with self.assertRaises(SystemExit):
call_command('makemigrations', 'django.contrib.auth', stderr=err)
self.assertIn(self.did_you_mean_auth_error, err.getvalue())
def test_migrate_nonexistent_app_label(self):
with self.assertRaisesMessage(CommandError, self.nonexistent_app_error):
call_command('migrate', 'nonexistent_app')
def test_migrate_app_name_specified_as_label(self):
with self.assertRaisesMessage(CommandError, self.did_you_mean_auth_error):
call_command('migrate', 'django.contrib.auth')
def test_showmigrations_nonexistent_app_label(self):
err = io.StringIO()
with self.assertRaises(SystemExit):
call_command('showmigrations', 'nonexistent_app', stderr=err)
self.assertIn(self.nonexistent_app_error, err.getvalue())
def test_showmigrations_app_name_specified_as_label(self):
err = io.StringIO()
with self.assertRaises(SystemExit):
call_command('showmigrations', 'django.contrib.auth', stderr=err)
self.assertIn(self.did_you_mean_auth_error, err.getvalue())
def test_sqlmigrate_nonexistent_app_label(self):
with self.assertRaisesMessage(CommandError, self.nonexistent_app_error):
call_command('sqlmigrate', 'nonexistent_app', '0002')
def test_sqlmigrate_app_name_specified_as_label(self):
with self.assertRaisesMessage(CommandError, self.did_you_mean_auth_error):
call_command('sqlmigrate', 'django.contrib.auth', '0002')
def test_squashmigrations_nonexistent_app_label(self):
with self.assertRaisesMessage(CommandError, self.nonexistent_app_error):
call_command('squashmigrations', 'nonexistent_app', '0002')
def test_squashmigrations_app_name_specified_as_label(self):
with self.assertRaisesMessage(CommandError, self.did_you_mean_auth_error):
call_command('squashmigrations', 'django.contrib.auth', '0002')
| 47.024698 | 118 | 0.647612 | import datetime
import importlib
import io
import os
import sys
from unittest import mock
from django.apps import apps
from django.core.management import CommandError, call_command
from django.db import (
ConnectionHandler, DatabaseError, connection, connections, models,
)
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.backends.utils import truncate_name
from django.db.migrations.exceptions import InconsistentMigrationHistory
from django.db.migrations.recorder import MigrationRecorder
from django.test import TestCase, override_settings, skipUnlessDBFeature
from .models import UnicodeModel, UnserializableModel
from .routers import TestRouter
from .test_base import MigrationTestBase
class MigrateTests(MigrationTestBase):
databases = {'default', 'other'}
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
def test_migrate(self):
self.assertTableNotExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
self.assertTableNotExists("migrations_book")
stdout = io.StringIO()
call_command('migrate', 'migrations', '0001', verbosity=1, stdout=stdout, no_color=True)
stdout = stdout.getvalue()
self.assertIn('Target specific migration: 0001_initial, from migrations', stdout)
self.assertIn('Applying migrations.0001_initial... OK', stdout)
self.assertTableExists("migrations_author")
self.assertTableExists("migrations_tribble")
self.assertTableNotExists("migrations_book")
call_command("migrate", verbosity=0)
self.assertTableExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
self.assertTableExists("migrations_book")
stdout = io.StringIO()
call_command('migrate', 'migrations', 'zero', verbosity=1, stdout=stdout, no_color=True)
stdout = stdout.getvalue()
self.assertIn('Unapply all migrations: migrations', stdout)
self.assertIn('Unapplying migrations.0002_second... OK', stdout)
self.assertTableNotExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
self.assertTableNotExists("migrations_book")
@override_settings(INSTALLED_APPS=[
'django.contrib.auth',
'django.contrib.contenttypes',
'migrations.migrations_test_apps.migrated_app',
])
def test_migrate_with_system_checks(self):
out = io.StringIO()
call_command('migrate', skip_checks=False, no_color=True, stdout=out)
self.assertIn('Apply all migrations: migrated_app', out.getvalue())
@override_settings(INSTALLED_APPS=['migrations', 'migrations.migrations_test_apps.unmigrated_app_syncdb'])
def test_app_without_migrations(self):
msg = "App 'unmigrated_app_syncdb' does not have migrations."
with self.assertRaisesMessage(CommandError, msg):
call_command('migrate', app_label='unmigrated_app_syncdb')
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_clashing_prefix'})
def test_ambiguous_prefix(self):
msg = (
"More than one migration matches 'a' in app 'migrations'. Please "
"be more specific."
)
with self.assertRaisesMessage(CommandError, msg):
call_command('migrate', app_label='migrations', migration_name='a')
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations'})
def test_unknown_prefix(self):
msg = "Cannot find a migration matching 'nonexistent' from app 'migrations'."
with self.assertRaisesMessage(CommandError, msg):
call_command('migrate', app_label='migrations', migration_name='nonexistent')
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_initial_false"})
def test_migrate_initial_false(self):
self.assertTableNotExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
call_command("migrate", "migrations", "0001", verbosity=0)
call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
with self.assertRaises(DatabaseError):
call_command("migrate", "migrations", "0001", fake_initial=True, verbosity=0)
call_command("migrate", "migrations", "0001", fake=True, verbosity=0)
call_command("migrate", "migrations", "zero", verbosity=0)
self.assertTableNotExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
self.assertTableNotExists("migrations_book")
@override_settings(
MIGRATION_MODULES={"migrations": "migrations.test_migrations"},
DATABASE_ROUTERS=['migrations.routers.TestRouter'],
)
def test_migrate_fake_initial(self):
# Make sure no tables are created
for db in self.databases:
self.assertTableNotExists("migrations_author", using=db)
self.assertTableNotExists("migrations_tribble", using=db)
# Run the migrations to 0001 only
call_command("migrate", "migrations", "0001", verbosity=0)
call_command("migrate", "migrations", "0001", verbosity=0, database="other")
# Make sure the right tables exist
self.assertTableExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
# Also check the "other" database
self.assertTableNotExists("migrations_author", using="other")
self.assertTableExists("migrations_tribble", using="other")
# Fake a roll-back
call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
call_command("migrate", "migrations", "zero", fake=True, verbosity=0, database="other")
# Make sure the tables still exist
self.assertTableExists("migrations_author")
self.assertTableExists("migrations_tribble", using="other")
# Try to run initial migration
with self.assertRaises(DatabaseError):
call_command("migrate", "migrations", "0001", verbosity=0)
# Run initial migration with an explicit --fake-initial
out = io.StringIO()
with mock.patch('django.core.management.color.supports_color', lambda *args: False):
call_command("migrate", "migrations", "0001", fake_initial=True, stdout=out, verbosity=1)
call_command("migrate", "migrations", "0001", fake_initial=True, verbosity=0, database="other")
self.assertIn(
"migrations.0001_initial... faked",
out.getvalue().lower()
)
# Run migrations all the way
call_command("migrate", verbosity=0)
call_command("migrate", verbosity=0, database="other")
# Make sure the right tables exist
self.assertTableExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
self.assertTableExists("migrations_book")
self.assertTableNotExists("migrations_author", using="other")
self.assertTableNotExists("migrations_tribble", using="other")
self.assertTableNotExists("migrations_book", using="other")
# Fake a roll-back
call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
call_command("migrate", "migrations", "zero", fake=True, verbosity=0, database="other")
# Make sure the tables still exist
self.assertTableExists("migrations_author")
self.assertTableNotExists("migrations_tribble")
self.assertTableExists("migrations_book")
# Try to run initial migration
with self.assertRaises(DatabaseError):
call_command("migrate", "migrations", verbosity=0)
# Run initial migration with an explicit --fake-initial
with self.assertRaises(DatabaseError):
# Fails because "migrations_tribble" does not exist but needs to in
# order to make --fake-initial work.
call_command("migrate", "migrations", fake_initial=True, verbosity=0)
# Fake an apply
call_command("migrate", "migrations", fake=True, verbosity=0)
call_command("migrate", "migrations", fake=True, verbosity=0, database="other")
# Unmigrate everything
call_command("migrate", "migrations", "zero", verbosity=0)
call_command("migrate", "migrations", "zero", verbosity=0, database="other")
# Make sure it's all gone
for db in self.databases:
self.assertTableNotExists("migrations_author", using=db)
self.assertTableNotExists("migrations_tribble", using=db)
self.assertTableNotExists("migrations_book", using=db)
@skipUnlessDBFeature('ignores_table_name_case')
def test_migrate_fake_initial_case_insensitive(self):
with override_settings(MIGRATION_MODULES={
'migrations': 'migrations.test_fake_initial_case_insensitive.initial',
}):
call_command('migrate', 'migrations', '0001', verbosity=0)
call_command('migrate', 'migrations', 'zero', fake=True, verbosity=0)
with override_settings(MIGRATION_MODULES={
'migrations': 'migrations.test_fake_initial_case_insensitive.fake_initial',
}):
out = io.StringIO()
call_command(
'migrate',
'migrations',
'0001',
fake_initial=True,
stdout=out,
verbosity=1,
no_color=True,
)
self.assertIn(
'migrations.0001_initial... faked',
out.getvalue().lower(),
)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_fake_split_initial"})
def test_migrate_fake_split_initial(self):
call_command("migrate", "migrations", "0002", verbosity=0)
call_command("migrate", "migrations", "zero", fake=True, verbosity=0)
out = io.StringIO()
with mock.patch('django.core.management.color.supports_color', lambda *args: False):
call_command("migrate", "migrations", "0002", fake_initial=True, stdout=out, verbosity=1)
value = out.getvalue().lower()
self.assertIn("migrations.0001_initial... faked", value)
self.assertIn("migrations.0002_second... faked", value)
call_command("migrate", "migrations", fake=True, verbosity=0)
call_command("migrate", "migrations", "zero", verbosity=0)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_conflict"})
def test_migrate_conflict_exit(self):
with self.assertRaisesMessage(CommandError, "Conflicting migrations detected"):
call_command("migrate", "migrations")
@override_settings(MIGRATION_MODULES={
'migrations': 'migrations.test_migrations',
})
def test_migrate_check(self):
with self.assertRaises(SystemExit):
call_command('migrate', 'migrations', '0001', check_unapplied=True, verbosity=0)
self.assertTableNotExists('migrations_author')
self.assertTableNotExists('migrations_tribble')
self.assertTableNotExists('migrations_book')
@override_settings(MIGRATION_MODULES={
'migrations': 'migrations.test_migrations_plan',
})
def test_migrate_check_plan(self):
out = io.StringIO()
with self.assertRaises(SystemExit):
call_command(
'migrate',
'migrations',
'0001',
check_unapplied=True,
plan=True,
stdout=out,
no_color=True,
)
self.assertEqual(
'Planned operations:\n'
'migrations.0001_initial\n'
' Create model Salamander\n'
' Raw Python operation -> Grow salamander tail.\n',
out.getvalue(),
)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
def test_showmigrations_list(self):
out = io.StringIO()
with mock.patch('django.core.management.color.supports_color', lambda *args: True):
call_command("showmigrations", format='list', stdout=out, verbosity=0, no_color=False)
self.assertEqual(
'\x1b[1mmigrations\n\x1b[0m'
' [ ] 0001_initial\n'
' [ ] 0002_second\n',
out.getvalue().lower()
)
call_command("migrate", "migrations", "0001", verbosity=0)
out = io.StringIO()
call_command("showmigrations", "migrations", format='list', stdout=out, verbosity=0, no_color=True)
self.assertEqual(
'migrations\n'
' [x] 0001_initial\n'
' [ ] 0002_second\n',
out.getvalue().lower()
)
out = io.StringIO()
call_command('showmigrations', 'migrations', stdout=out, verbosity=2, no_color=True)
migration1 = MigrationRecorder(connection).migration_qs.get(app='migrations', name='0001_initial')
self.assertEqual(
'migrations\n'
' [x] 0001_initial (applied at %s)\n'
' [ ] 0002_second\n' % migration1.applied.strftime('%Y-%m-%d %H:%M:%S'),
out.getvalue().lower()
)
call_command("migrate", "migrations", "zero", verbosity=0)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_run_before"})
def test_showmigrations_plan(self):
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out)
self.assertEqual(
"[ ] migrations.0001_initial\n"
"[ ] migrations.0003_third\n"
"[ ] migrations.0002_second\n",
out.getvalue().lower()
)
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out, verbosity=2)
self.assertEqual(
"[ ] migrations.0001_initial\n"
"[ ] migrations.0003_third ... (migrations.0001_initial)\n"
"[ ] migrations.0002_second ... (migrations.0001_initial, migrations.0003_third)\n",
out.getvalue().lower()
)
call_command("migrate", "migrations", "0003", verbosity=0)
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out)
self.assertEqual(
"[x] migrations.0001_initial\n"
"[x] migrations.0003_third\n"
"[ ] migrations.0002_second\n",
out.getvalue().lower()
)
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out, verbosity=2)
self.assertEqual(
"[x] migrations.0001_initial\n"
"[x] migrations.0003_third ... (migrations.0001_initial)\n"
"[ ] migrations.0002_second ... (migrations.0001_initial, migrations.0003_third)\n",
out.getvalue().lower()
)
call_command("migrate", "migrations", "zero", verbosity=0)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_plan'})
def test_migrate_plan(self):
out = io.StringIO()
call_command('migrate', 'migrations', '0003', plan=True, stdout=out, no_color=True)
self.assertEqual(
'Planned operations:\n'
'migrations.0001_initial\n'
' Create model Salamander\n'
' Raw Python operation -> Grow salamander tail.\n'
'migrations.0002_second\n'
' Create model Book\n'
" Raw SQL operation -> ['SELECT * FROM migrations_book']\n"
'migrations.0003_third\n'
' Create model Author\n'
" Raw SQL operation -> ['SELECT * FROM migrations_author']\n",
out.getvalue()
)
try:
call_command('migrate', 'migrations', '0003', verbosity=0)
out = io.StringIO()
call_command('migrate', 'migrations', '0003', plan=True, stdout=out, no_color=True)
self.assertEqual(
'Planned operations:\n'
' No planned migration operations.\n',
out.getvalue()
)
out = io.StringIO()
call_command('migrate', 'migrations', '0001', plan=True, stdout=out, no_color=True)
self.assertEqual(
'Planned operations:\n'
'migrations.0003_third\n'
' Undo Create model Author\n'
" Raw SQL operation -> ['SELECT * FROM migrations_book']\n"
'migrations.0002_second\n'
' Undo Create model Book\n'
" Raw SQL operation -> ['SELECT * FROM migrations_salamand…\n",
out.getvalue()
)
out = io.StringIO()
# Show the migration plan to fourth, with truncated details.
call_command('migrate', 'migrations', '0004', plan=True, stdout=out, no_color=True)
self.assertEqual(
'Planned operations:\n'
'migrations.0004_fourth\n'
' Raw SQL operation -> SELECT * FROM migrations_author WHE…\n',
out.getvalue()
)
# Show the plan when an operation is irreversible.
# Migrate to the fourth migration.
call_command('migrate', 'migrations', '0004', verbosity=0)
out = io.StringIO()
call_command('migrate', 'migrations', '0003', plan=True, stdout=out, no_color=True)
self.assertEqual(
'Planned operations:\n'
'migrations.0004_fourth\n'
' Raw SQL operation -> IRREVERSIBLE\n',
out.getvalue()
)
out = io.StringIO()
call_command('migrate', 'migrations', '0005', plan=True, stdout=out, no_color=True)
# Operation is marked as irreversible only in the revert plan.
self.assertEqual(
'Planned operations:\n'
'migrations.0005_fifth\n'
' Raw Python operation\n'
' Raw Python operation\n'
' Raw Python operation -> Feed salamander.\n',
out.getvalue()
)
call_command('migrate', 'migrations', '0005', verbosity=0)
out = io.StringIO()
call_command('migrate', 'migrations', '0004', plan=True, stdout=out, no_color=True)
self.assertEqual(
'Planned operations:\n'
'migrations.0005_fifth\n'
' Raw Python operation -> IRREVERSIBLE\n'
' Raw Python operation -> IRREVERSIBLE\n'
' Raw Python operation\n',
out.getvalue()
)
finally:
# Cleanup by unmigrating everything: fake the irreversible, then
# migrate all to zero.
call_command('migrate', 'migrations', '0003', fake=True, verbosity=0)
call_command('migrate', 'migrations', 'zero', verbosity=0)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_empty'})
def test_showmigrations_no_migrations(self):
out = io.StringIO()
call_command('showmigrations', stdout=out, no_color=True)
self.assertEqual('migrations\n (no migrations)\n', out.getvalue().lower())
@override_settings(INSTALLED_APPS=['migrations.migrations_test_apps.unmigrated_app'])
def test_showmigrations_unmigrated_app(self):
out = io.StringIO()
call_command('showmigrations', 'unmigrated_app', stdout=out, no_color=True)
self.assertEqual('unmigrated_app\n (no migrations)\n', out.getvalue().lower())
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_empty"})
def test_showmigrations_plan_no_migrations(self):
out = io.StringIO()
call_command('showmigrations', format='plan', stdout=out, no_color=True)
self.assertEqual('(no migrations)\n', out.getvalue().lower())
out = io.StringIO()
call_command('showmigrations', format='plan', stdout=out, verbosity=2, no_color=True)
self.assertEqual('(no migrations)\n', out.getvalue().lower())
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed_complex"})
def test_showmigrations_plan_squashed(self):
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out)
self.assertEqual(
"[ ] migrations.1_auto\n"
"[ ] migrations.2_auto\n"
"[ ] migrations.3_squashed_5\n"
"[ ] migrations.6_auto\n"
"[ ] migrations.7_auto\n",
out.getvalue().lower()
)
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out, verbosity=2)
self.assertEqual(
"[ ] migrations.1_auto\n"
"[ ] migrations.2_auto ... (migrations.1_auto)\n"
"[ ] migrations.3_squashed_5 ... (migrations.2_auto)\n"
"[ ] migrations.6_auto ... (migrations.3_squashed_5)\n"
"[ ] migrations.7_auto ... (migrations.6_auto)\n",
out.getvalue().lower()
)
call_command("migrate", "migrations", "3_squashed_5", verbosity=0)
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out)
self.assertEqual(
"[x] migrations.1_auto\n"
"[x] migrations.2_auto\n"
"[x] migrations.3_squashed_5\n"
"[ ] migrations.6_auto\n"
"[ ] migrations.7_auto\n",
out.getvalue().lower()
)
out = io.StringIO()
call_command("showmigrations", format='plan', stdout=out, verbosity=2)
self.assertEqual(
"[x] migrations.1_auto\n"
"[x] migrations.2_auto ... (migrations.1_auto)\n"
"[x] migrations.3_squashed_5 ... (migrations.2_auto)\n"
"[ ] migrations.6_auto ... (migrations.3_squashed_5)\n"
"[ ] migrations.7_auto ... (migrations.6_auto)\n",
out.getvalue().lower()
)
@override_settings(INSTALLED_APPS=[
'migrations.migrations_test_apps.mutate_state_b',
'migrations.migrations_test_apps.alter_fk.author_app',
'migrations.migrations_test_apps.alter_fk.book_app',
])
def test_showmigrations_plan_single_app_label(self):
# Single app with no dependencies on other apps.
out = io.StringIO()
call_command('showmigrations', 'mutate_state_b', format='plan', stdout=out)
self.assertEqual(
'[ ] mutate_state_b.0001_initial\n'
'[ ] mutate_state_b.0002_add_field\n',
out.getvalue()
)
# Single app with dependencies.
out = io.StringIO()
call_command('showmigrations', 'author_app', format='plan', stdout=out)
self.assertEqual(
'[ ] author_app.0001_initial\n'
'[ ] book_app.0001_initial\n'
'[ ] author_app.0002_alter_id\n',
out.getvalue()
)
# Some migrations already applied.
call_command('migrate', 'author_app', '0001', verbosity=0)
out = io.StringIO()
call_command('showmigrations', 'author_app', format='plan', stdout=out)
self.assertEqual(
'[X] author_app.0001_initial\n'
'[ ] book_app.0001_initial\n'
'[ ] author_app.0002_alter_id\n',
out.getvalue()
)
# Cleanup by unmigrating author_app.
call_command('migrate', 'author_app', 'zero', verbosity=0)
@override_settings(INSTALLED_APPS=[
'migrations.migrations_test_apps.mutate_state_b',
'migrations.migrations_test_apps.alter_fk.author_app',
'migrations.migrations_test_apps.alter_fk.book_app',
])
def test_showmigrations_plan_multiple_app_labels(self):
# Multiple apps: author_app depends on book_app; mutate_state_b doesn't
out = io.StringIO()
call_command('showmigrations', 'mutate_state_b', 'author_app', format='plan', stdout=out)
self.assertEqual(
'[ ] author_app.0001_initial\n'
'[ ] book_app.0001_initial\n'
'[ ] author_app.0002_alter_id\n'
'[ ] mutate_state_b.0001_initial\n'
'[ ] mutate_state_b.0002_add_field\n',
out.getvalue()
)
# expected as above).
out = io.StringIO()
call_command('showmigrations', 'author_app', 'mutate_state_b', format='plan', stdout=out)
self.assertEqual(
'[ ] author_app.0001_initial\n'
'[ ] book_app.0001_initial\n'
'[ ] author_app.0002_alter_id\n'
'[ ] mutate_state_b.0001_initial\n'
'[ ] mutate_state_b.0002_add_field\n',
out.getvalue()
)
@override_settings(INSTALLED_APPS=['migrations.migrations_test_apps.unmigrated_app'])
def test_showmigrations_plan_app_label_no_migrations(self):
out = io.StringIO()
call_command('showmigrations', 'unmigrated_app', format='plan', stdout=out, no_color=True)
self.assertEqual('(no migrations)\n', out.getvalue())
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
def test_sqlmigrate_forwards(self):
out = io.StringIO()
call_command("sqlmigrate", "migrations", "0001", stdout=out)
output = out.getvalue().lower()
index_tx_start = output.find(connection.ops.start_transaction_sql().lower())
index_op_desc_author = output.find('-- create model author')
index_create_table = output.find('create table')
index_op_desc_tribble = output.find('-- create model tribble')
index_op_desc_unique_together = output.find('-- alter unique_together')
index_tx_end = output.find(connection.ops.end_transaction_sql().lower())
if connection.features.can_rollback_ddl:
self.assertGreater(index_tx_start, -1, "Transaction start not found")
self.assertGreater(
index_tx_end, index_op_desc_unique_together,
"Transaction end not found or found before operation description (unique_together)"
)
self.assertGreater(
index_op_desc_author, index_tx_start,
"Operation description (author) not found or found before transaction start"
)
self.assertGreater(
index_create_table, index_op_desc_author,
"CREATE TABLE not found or found before operation description (author)"
)
self.assertGreater(
index_op_desc_tribble, index_create_table,
"Operation description (tribble) not found or found before CREATE TABLE (author)"
)
self.assertGreater(
index_op_desc_unique_together, index_op_desc_tribble,
"Operation description (unique_together) not found or found before operation description (tribble)"
)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
def test_sqlmigrate_backwards(self):
# Cannot generate the reverse SQL unless we've applied the migration.
call_command("migrate", "migrations", verbosity=0)
out = io.StringIO()
call_command("sqlmigrate", "migrations", "0001", stdout=out, backwards=True)
output = out.getvalue().lower()
index_tx_start = output.find(connection.ops.start_transaction_sql().lower())
index_op_desc_unique_together = output.find('-- alter unique_together')
index_op_desc_tribble = output.find('-- create model tribble')
index_op_desc_author = output.find('-- create model author')
index_drop_table = output.rfind('drop table')
index_tx_end = output.find(connection.ops.end_transaction_sql().lower())
if connection.features.can_rollback_ddl:
self.assertGreater(index_tx_start, -1, "Transaction start not found")
self.assertGreater(
index_tx_end, index_op_desc_unique_together,
"Transaction end not found or found before DROP TABLE"
)
self.assertGreater(
index_op_desc_unique_together, index_tx_start,
"Operation description (unique_together) not found or found before transaction start"
)
self.assertGreater(
index_op_desc_tribble, index_op_desc_unique_together,
"Operation description (tribble) not found or found before operation description (unique_together)"
)
self.assertGreater(
index_op_desc_author, index_op_desc_tribble,
"Operation description (author) not found or found before operation description (tribble)"
)
self.assertGreater(
index_drop_table, index_op_desc_author,
"DROP TABLE not found or found before operation description (author)"
)
call_command("migrate", "migrations", "zero", verbosity=0)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_non_atomic"})
def test_sqlmigrate_for_non_atomic_migration(self):
out = io.StringIO()
call_command("sqlmigrate", "migrations", "0001", stdout=out)
output = out.getvalue().lower()
queries = [q.strip() for q in output.splitlines()]
if connection.ops.start_transaction_sql():
self.assertNotIn(connection.ops.start_transaction_sql().lower(), queries)
self.assertNotIn(connection.ops.end_transaction_sql().lower(), queries)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations'})
def test_sqlmigrate_for_non_transactional_databases(self):
out = io.StringIO()
with mock.patch.object(connection.features, 'can_rollback_ddl', False):
call_command('sqlmigrate', 'migrations', '0001', stdout=out)
output = out.getvalue().lower()
queries = [q.strip() for q in output.splitlines()]
start_transaction_sql = connection.ops.start_transaction_sql()
if start_transaction_sql:
self.assertNotIn(start_transaction_sql.lower(), queries)
self.assertNotIn(connection.ops.end_transaction_sql().lower(), queries)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_squashed'})
def test_sqlmigrate_ambiguous_prefix_squashed_migrations(self):
msg = (
"More than one migration matches '0001' in app 'migrations'. "
"Please be more specific."
)
with self.assertRaisesMessage(CommandError, msg):
call_command('sqlmigrate', 'migrations', '0001')
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_squashed'})
def test_sqlmigrate_squashed_migration(self):
out = io.StringIO()
call_command('sqlmigrate', 'migrations', '0001_squashed_0002', stdout=out)
output = out.getvalue().lower()
self.assertIn('-- create model author', output)
self.assertIn('-- create model book', output)
self.assertNotIn('-- create model tribble', output)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_squashed'})
def test_sqlmigrate_replaced_migration(self):
out = io.StringIO()
call_command('sqlmigrate', 'migrations', '0001_initial', stdout=out)
output = out.getvalue().lower()
self.assertIn('-- create model author', output)
self.assertIn('-- create model tribble', output)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations_no_operations'})
def test_migrations_no_operations(self):
err = io.StringIO()
call_command('sqlmigrate', 'migrations', '0001_initial', stderr=err)
self.assertEqual(err.getvalue(), 'No operations found.\n')
@override_settings(
INSTALLED_APPS=[
"migrations.migrations_test_apps.migrated_app",
"migrations.migrations_test_apps.migrated_unapplied_app",
"migrations.migrations_test_apps.unmigrated_app",
],
)
def test_regression_22823_unmigrated_fk_to_migrated_model(self):
call_command("migrate", "migrated_unapplied_app", stdout=io.StringIO())
del apps._pending_operations[('migrations', 'tribble')]
@override_settings(INSTALLED_APPS=['migrations.migrations_test_apps.unmigrated_app_syncdb'])
def test_migrate_syncdb_deferred_sql_executed_with_schemaeditor(self):
stdout = io.StringIO()
with mock.patch.object(BaseDatabaseSchemaEditor, 'execute') as execute:
call_command('migrate', run_syncdb=True, verbosity=1, stdout=stdout, no_color=True)
create_table_count = len([call for call in execute.mock_calls if 'CREATE TABLE' in str(call)])
self.assertEqual(create_table_count, 2)
# index.
self.assertGreater(len(execute.mock_calls), 2)
stdout = stdout.getvalue()
self.assertIn('Synchronize unmigrated apps: unmigrated_app_syncdb', stdout)
self.assertIn('Creating tables...', stdout)
table_name = truncate_name('unmigrated_app_syncdb_classroom', connection.ops.max_name_length())
self.assertIn('Creating table %s' % table_name, stdout)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations'})
def test_migrate_syncdb_app_with_migrations(self):
msg = "Can't use run_syncdb with app 'migrations' as it has migrations."
with self.assertRaisesMessage(CommandError, msg):
call_command('migrate', 'migrations', run_syncdb=True, verbosity=0)
@override_settings(INSTALLED_APPS=[
'migrations.migrations_test_apps.unmigrated_app_syncdb',
'migrations.migrations_test_apps.unmigrated_app_simple',
])
def test_migrate_syncdb_app_label(self):
stdout = io.StringIO()
with mock.patch.object(BaseDatabaseSchemaEditor, 'execute') as execute:
call_command('migrate', 'unmigrated_app_syncdb', run_syncdb=True, stdout=stdout)
create_table_count = len([call for call in execute.mock_calls if 'CREATE TABLE' in str(call)])
self.assertEqual(create_table_count, 2)
self.assertGreater(len(execute.mock_calls), 2)
self.assertIn('Synchronize unmigrated app: unmigrated_app_syncdb', stdout.getvalue())
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"})
def test_migrate_record_replaced(self):
recorder = MigrationRecorder(connection)
out = io.StringIO()
call_command("migrate", "migrations", verbosity=0)
call_command("showmigrations", "migrations", stdout=out, no_color=True)
self.assertEqual(
'migrations\n'
' [x] 0001_squashed_0002 (2 squashed migrations)\n',
out.getvalue().lower()
)
applied_migrations = recorder.applied_migrations()
self.assertIn(("migrations", "0001_initial"), applied_migrations)
self.assertIn(("migrations", "0002_second"), applied_migrations)
self.assertIn(("migrations", "0001_squashed_0002"), applied_migrations)
call_command("migrate", "migrations", "zero", verbosity=0)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"})
def test_migrate_record_squashed(self):
recorder = MigrationRecorder(connection)
recorder.record_applied("migrations", "0001_initial")
recorder.record_applied("migrations", "0002_second")
out = io.StringIO()
call_command("migrate", "migrations", verbosity=0)
call_command("showmigrations", "migrations", stdout=out, no_color=True)
self.assertEqual(
'migrations\n'
' [x] 0001_squashed_0002 (2 squashed migrations)\n',
out.getvalue().lower()
)
self.assertIn(
("migrations", "0001_squashed_0002"),
recorder.applied_migrations()
)
@override_settings(MIGRATION_MODULES={'migrations': 'migrations.test_migrations'})
def test_migrate_inconsistent_history(self):
recorder = MigrationRecorder(connection)
recorder.record_applied("migrations", "0002_second")
msg = "Migration migrations.0002_second is applied before its dependency migrations.0001_initial"
with self.assertRaisesMessage(InconsistentMigrationHistory, msg):
call_command("migrate")
applied_migrations = recorder.applied_migrations()
self.assertNotIn(("migrations", "0001_initial"), applied_migrations)
class MakeMigrationsTests(MigrationTestBase):
def setUp(self):
super().setUp()
self._old_models = apps.app_configs['migrations'].models.copy()
def tearDown(self):
apps.app_configs['migrations'].models = self._old_models
apps.all_models['migrations'] = self._old_models
apps.clear_cache()
super().tearDown()
def test_files_content(self):
self.assertTableNotExists("migrations_unicodemodel")
apps.register_model('migrations', UnicodeModel)
with self.temporary_migration_module() as migration_dir:
call_command("makemigrations", "migrations", verbosity=0)
init_file = os.path.join(migration_dir, "__init__.py")
self.assertTrue(os.path.exists(init_file))
with open(init_file) as fp:
content = fp.read()
self.assertEqual(content, '')
initial_file = os.path.join(migration_dir, "0001_initial.py")
self.assertTrue(os.path.exists(initial_file))
with open(initial_file, encoding='utf-8') as fp:
content = fp.read()
self.assertIn('migrations.CreateModel', content)
self.assertIn('initial = True', content)
self.assertIn('úñí©óðé µóðéø', content)
self.assertIn('úñí©óðé µóðéøß', content)
self.assertIn('ÚÑÍ¢ÓÐÉ', content)
self.assertIn('“Ðjáñgó”', content)
def test_makemigrations_order(self):
module = 'migrations.test_migrations_order'
with self.temporary_migration_module(module=module) as migration_dir:
if hasattr(importlib, 'invalidate_caches'):
importlib.invalidate_caches()
call_command('makemigrations', 'migrations', '--empty', '-n', 'a', '-v', '0')
self.assertTrue(os.path.exists(os.path.join(migration_dir, '0002_a.py')))
def test_makemigrations_empty_connections(self):
empty_connections = ConnectionHandler({'default': {}})
with mock.patch('django.core.management.commands.makemigrations.connections', new=empty_connections):
out = io.StringIO()
call_command('makemigrations', stdout=out)
self.assertIn('No changes detected', out.getvalue())
with self.temporary_migration_module() as migration_dir:
call_command('makemigrations', 'migrations', verbosity=0)
init_file = os.path.join(migration_dir, '__init__.py')
self.assertTrue(os.path.exists(init_file))
@override_settings(INSTALLED_APPS=['migrations', 'migrations2'])
def test_makemigrations_consistency_checks_respect_routers(self):
def patched_has_table(migration_recorder):
if migration_recorder.connection is connections['other']:
raise Exception('Other connection')
else:
return mock.DEFAULT
self.assertTableNotExists('migrations_unicodemodel')
apps.register_model('migrations', UnicodeModel)
with mock.patch.object(
MigrationRecorder, 'has_table',
autospec=True, side_effect=patched_has_table) as has_table:
with self.temporary_migration_module() as migration_dir:
call_command("makemigrations", "migrations", verbosity=0)
initial_file = os.path.join(migration_dir, "0001_initial.py")
self.assertTrue(os.path.exists(initial_file))
self.assertEqual(has_table.call_count, 1)
# be checked.
with self.settings(DATABASE_ROUTERS=['migrations.routers.TestRouter']):
call_command('makemigrations', 'migrations', verbosity=0)
self.assertEqual(has_table.call_count, 2) # 'default' again
# With a router that doesn't prohibit migrating 'other',
with self.settings(DATABASE_ROUTERS=['migrations.routers.DefaultOtherRouter']):
with self.assertRaisesMessage(Exception, 'Other connection'):
call_command('makemigrations', 'migrations', verbosity=0)
self.assertEqual(has_table.call_count, 4)
# no consistency checks are made.
with self.settings(DATABASE_ROUTERS=['migrations.routers.TestRouter']):
with mock.patch.object(TestRouter, 'allow_migrate', return_value=False) as allow_migrate:
call_command('makemigrations', 'migrations', verbosity=0)
allow_migrate.assert_any_call('other', 'migrations', model_name='UnicodeModel')
# allow_migrate() is called with the correct arguments.
self.assertGreater(len(allow_migrate.mock_calls), 0)
called_aliases = set()
for mock_call in allow_migrate.mock_calls:
_, call_args, call_kwargs = mock_call
connection_alias, app_name = call_args
called_aliases.add(connection_alias)
# Raises an error if invalid app_name/model_name occurs.
apps.get_app_config(app_name).get_model(call_kwargs['model_name'])
self.assertEqual(called_aliases, set(connections))
self.assertEqual(has_table.call_count, 4)
def test_failing_migration(self):
# If a migration fails to serialize, it shouldn't generate an empty file.
apps.register_model('migrations', UnserializableModel)
with self.temporary_migration_module() as migration_dir:
with self.assertRaisesMessage(ValueError, 'Cannot serialize'):
call_command("makemigrations", "migrations", verbosity=0)
initial_file = os.path.join(migration_dir, "0001_initial.py")
self.assertFalse(os.path.exists(initial_file))
def test_makemigrations_conflict_exit(self):
with self.temporary_migration_module(module="migrations.test_migrations_conflict"):
with self.assertRaises(CommandError) as context:
call_command("makemigrations")
exception_message = str(context.exception)
self.assertIn(
'Conflicting migrations detected; multiple leaf nodes '
'in the migration graph:',
exception_message
)
self.assertIn('0002_second', exception_message)
self.assertIn('0002_conflicting_second', exception_message)
self.assertIn('in migrations', exception_message)
self.assertIn("To fix them run 'python manage.py makemigrations --merge'", exception_message)
def test_makemigrations_merge_no_conflict(self):
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations"):
call_command("makemigrations", merge=True, stdout=out)
self.assertIn("No conflicts detected to merge.", out.getvalue())
def test_makemigrations_empty_no_app_specified(self):
msg = 'You must supply at least one app label when using --empty.'
with self.assertRaisesMessage(CommandError, msg):
call_command("makemigrations", empty=True)
def test_makemigrations_empty_migration(self):
with self.temporary_migration_module() as migration_dir:
call_command("makemigrations", "migrations", empty=True, verbosity=0)
initial_file = os.path.join(migration_dir, "0001_initial.py")
self.assertTrue(os.path.exists(initial_file))
with open(initial_file, encoding='utf-8') as fp:
content = fp.read()
content = content.replace(' ', '')
self.assertIn('dependencies=[\n]', content)
self.assertIn('operations=[\n]', content)
@override_settings(MIGRATION_MODULES={"migrations": None})
def test_makemigrations_disabled_migrations_for_app(self):
msg = (
"Django can't create migrations for app 'migrations' because migrations "
"have been disabled via the MIGRATION_MODULES setting."
)
with self.assertRaisesMessage(ValueError, msg):
call_command("makemigrations", "migrations", empty=True, verbosity=0)
def test_makemigrations_no_changes_no_apps(self):
out = io.StringIO()
call_command("makemigrations", stdout=out)
self.assertIn("No changes detected", out.getvalue())
def test_makemigrations_no_changes(self):
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
call_command("makemigrations", "migrations", stdout=out)
self.assertIn("No changes detected in app 'migrations'", out.getvalue())
def test_makemigrations_no_apps_initial(self):
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_empty"):
call_command("makemigrations", stdout=out)
self.assertIn("0001_initial.py", out.getvalue())
def test_makemigrations_no_init(self):
out = io.StringIO()
with self.temporary_migration_module(module='migrations.test_migrations_no_init'):
call_command('makemigrations', stdout=out)
self.assertIn('0001_initial.py', out.getvalue())
def test_makemigrations_migrations_announce(self):
out = io.StringIO()
with self.temporary_migration_module():
call_command("makemigrations", "migrations", stdout=out)
self.assertIn("Migrations for 'migrations'", out.getvalue())
def test_makemigrations_no_common_ancestor(self):
with self.assertRaises(ValueError) as context:
with self.temporary_migration_module(module="migrations.test_migrations_no_ancestor"):
call_command("makemigrations", "migrations", merge=True)
exception_message = str(context.exception)
self.assertIn("Could not find common ancestor of", exception_message)
self.assertIn("0002_second", exception_message)
self.assertIn("0002_conflicting_second", exception_message)
def test_makemigrations_interactive_reject(self):
# Monkeypatch interactive questioner to auto reject
with mock.patch('builtins.input', mock.Mock(return_value='N')):
with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
call_command("makemigrations", "migrations", name="merge", merge=True, interactive=True, verbosity=0)
merge_file = os.path.join(migration_dir, '0003_merge.py')
self.assertFalse(os.path.exists(merge_file))
def test_makemigrations_interactive_accept(self):
# Monkeypatch interactive questioner to auto accept
with mock.patch('builtins.input', mock.Mock(return_value='y')):
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
call_command("makemigrations", "migrations", name="merge", merge=True, interactive=True, stdout=out)
merge_file = os.path.join(migration_dir, '0003_merge.py')
self.assertTrue(os.path.exists(merge_file))
self.assertIn("Created new merge migration", out.getvalue())
@mock.patch('django.db.migrations.utils.datetime')
def test_makemigrations_default_merge_name(self, mock_datetime):
mock_datetime.datetime.now.return_value = datetime.datetime(2016, 1, 2, 3, 4)
with mock.patch('builtins.input', mock.Mock(return_value='y')):
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
call_command("makemigrations", "migrations", merge=True, interactive=True, stdout=out)
merge_file = os.path.join(migration_dir, '0003_merge_20160102_0304.py')
self.assertTrue(os.path.exists(merge_file))
self.assertIn("Created new merge migration", out.getvalue())
def test_makemigrations_non_interactive_not_null_addition(self):
class SillyModel(models.Model):
silly_field = models.BooleanField(default=False)
silly_int = models.IntegerField()
class Meta:
app_label = "migrations"
out = io.StringIO()
with self.assertRaises(SystemExit):
with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
call_command("makemigrations", "migrations", interactive=False, stdout=out)
def test_makemigrations_non_interactive_not_null_alteration(self):
class Author(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField()
age = models.IntegerField(default=0)
class Meta:
app_label = "migrations"
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations"):
call_command("makemigrations", "migrations", interactive=False, stdout=out)
self.assertIn("Alter field slug on author", out.getvalue())
def test_makemigrations_non_interactive_no_model_rename(self):
class RenamedModel(models.Model):
silly_field = models.BooleanField(default=False)
class Meta:
app_label = "migrations"
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
call_command("makemigrations", "migrations", interactive=False, stdout=out)
self.assertIn("Delete model SillyModel", out.getvalue())
self.assertIn("Create model RenamedModel", out.getvalue())
def test_makemigrations_non_interactive_no_field_rename(self):
class SillyModel(models.Model):
silly_rename = models.BooleanField(default=False)
class Meta:
app_label = "migrations"
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
call_command("makemigrations", "migrations", interactive=False, stdout=out)
self.assertIn("Remove field silly_field from sillymodel", out.getvalue())
self.assertIn("Add field silly_rename to sillymodel", out.getvalue())
def test_makemigrations_handle_merge(self):
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
call_command("makemigrations", "migrations", name="merge", merge=True, interactive=False, stdout=out)
merge_file = os.path.join(migration_dir, '0003_merge.py')
self.assertTrue(os.path.exists(merge_file))
output = out.getvalue()
self.assertIn("Merging migrations", output)
self.assertIn("Branch 0002_second", output)
self.assertIn("Branch 0002_conflicting_second", output)
self.assertIn("Created new merge migration", output)
def test_makemigration_merge_dry_run(self):
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
call_command(
"makemigrations", "migrations", name="merge", dry_run=True,
merge=True, interactive=False, stdout=out,
)
merge_file = os.path.join(migration_dir, '0003_merge.py')
self.assertFalse(os.path.exists(merge_file))
output = out.getvalue()
self.assertIn("Merging migrations", output)
self.assertIn("Branch 0002_second", output)
self.assertIn("Branch 0002_conflicting_second", output)
self.assertNotIn("Created new merge migration", output)
def test_makemigration_merge_dry_run_verbosity_3(self):
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
call_command(
"makemigrations", "migrations", name="merge", dry_run=True,
merge=True, interactive=False, stdout=out, verbosity=3,
)
merge_file = os.path.join(migration_dir, '0003_merge.py')
self.assertFalse(os.path.exists(merge_file))
output = out.getvalue()
self.assertIn("Merging migrations", output)
self.assertIn("Branch 0002_second", output)
self.assertIn("Branch 0002_conflicting_second", output)
self.assertNotIn("Created new merge migration", output)
# Additional output caused by verbosity 3
# The complete merge migration file that would be written
self.assertIn("class Migration(migrations.Migration):", output)
self.assertIn("dependencies = [", output)
self.assertIn("('migrations', '0002_second')", output)
self.assertIn("('migrations', '0002_conflicting_second')", output)
self.assertIn("operations = [", output)
self.assertIn("]", output)
def test_makemigrations_dry_run(self):
class SillyModel(models.Model):
silly_field = models.BooleanField(default=False)
silly_date = models.DateField() # Added field without a default
class Meta:
app_label = "migrations"
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
call_command("makemigrations", "migrations", dry_run=True, stdout=out)
# Output the expected changes directly, without asking for defaults
self.assertIn("Add field silly_date to sillymodel", out.getvalue())
def test_makemigrations_dry_run_verbosity_3(self):
class SillyModel(models.Model):
silly_field = models.BooleanField(default=False)
silly_char = models.CharField(default="")
class Meta:
app_label = "migrations"
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_no_default"):
call_command("makemigrations", "migrations", dry_run=True, stdout=out, verbosity=3)
# Normal --dry-run output
self.assertIn("- Add field silly_char to sillymodel", out.getvalue())
# Additional output caused by verbosity 3
# The complete migrations file that would be written
self.assertIn("class Migration(migrations.Migration):", out.getvalue())
self.assertIn("dependencies = [", out.getvalue())
self.assertIn("('migrations', '0001_initial'),", out.getvalue())
self.assertIn("migrations.AddField(", out.getvalue())
self.assertIn("model_name='sillymodel',", out.getvalue())
self.assertIn("name='silly_char',", out.getvalue())
def test_makemigrations_migrations_modules_path_not_exist(self):
class SillyModel(models.Model):
silly_field = models.BooleanField(default=False)
class Meta:
app_label = "migrations"
out = io.StringIO()
migration_module = "migrations.test_migrations_path_doesnt_exist.foo.bar"
with self.temporary_migration_module(module=migration_module) as migration_dir:
call_command("makemigrations", "migrations", stdout=out)
# Migrations file is actually created in the expected path.
initial_file = os.path.join(migration_dir, "0001_initial.py")
self.assertTrue(os.path.exists(initial_file))
# Command output indicates the migration is created.
self.assertIn(" - Create model SillyModel", out.getvalue())
@override_settings(MIGRATION_MODULES={'migrations': 'some.nonexistent.path'})
def test_makemigrations_migrations_modules_nonexistent_toplevel_package(self):
msg = (
'Could not locate an appropriate location to create migrations '
'package some.nonexistent.path. Make sure the toplevel package '
'exists and can be imported.'
)
with self.assertRaisesMessage(ValueError, msg):
call_command('makemigrations', 'migrations', empty=True, verbosity=0)
def test_makemigrations_interactive_by_default(self):
# Monkeypatch interactive questioner to auto reject
out = io.StringIO()
with mock.patch('builtins.input', mock.Mock(return_value='N')):
with self.temporary_migration_module(module="migrations.test_migrations_conflict") as migration_dir:
call_command("makemigrations", "migrations", name="merge", merge=True, stdout=out)
merge_file = os.path.join(migration_dir, '0003_merge.py')
# This will fail if interactive is False by default
self.assertFalse(os.path.exists(merge_file))
self.assertNotIn("Created new merge migration", out.getvalue())
@override_settings(
INSTALLED_APPS=[
"migrations",
"migrations.migrations_test_apps.unspecified_app_with_conflict"])
def test_makemigrations_unspecified_app_with_conflict_no_merge(self):
with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
call_command("makemigrations", "migrations", merge=False, verbosity=0)
@override_settings(
INSTALLED_APPS=[
"migrations.migrations_test_apps.migrated_app",
"migrations.migrations_test_apps.unspecified_app_with_conflict"])
def test_makemigrations_unspecified_app_with_conflict_merge(self):
# Monkeypatch interactive questioner to auto accept
with mock.patch('builtins.input', mock.Mock(return_value='y')):
out = io.StringIO()
with self.temporary_migration_module(app_label="migrated_app") as migration_dir:
call_command("makemigrations", "migrated_app", name="merge", merge=True, interactive=True, stdout=out)
merge_file = os.path.join(migration_dir, '0003_merge.py')
self.assertFalse(os.path.exists(merge_file))
self.assertIn("No conflicts detected to merge.", out.getvalue())
@override_settings(
INSTALLED_APPS=[
"migrations.migrations_test_apps.migrated_app",
"migrations.migrations_test_apps.conflicting_app_with_dependencies"])
def test_makemigrations_merge_dont_output_dependency_operations(self):
# Monkeypatch interactive questioner to auto accept
with mock.patch('builtins.input', mock.Mock(return_value='N')):
out = io.StringIO()
with mock.patch('django.core.management.color.supports_color', lambda *args: False):
call_command(
"makemigrations", "conflicting_app_with_dependencies",
merge=True, interactive=True, stdout=out
)
val = out.getvalue().lower()
self.assertIn('merging conflicting_app_with_dependencies\n', val)
self.assertIn(
' branch 0002_conflicting_second\n'
' - create model something\n',
val
)
self.assertIn(
' branch 0002_second\n'
' - delete model tribble\n'
' - remove field silly_field from author\n'
' - add field rating to author\n'
' - create model book\n',
val
)
def test_makemigrations_with_custom_name(self):
with self.temporary_migration_module() as migration_dir:
def cmd(migration_count, migration_name, *args):
call_command("makemigrations", "migrations", "--verbosity", "0", "--name", migration_name, *args)
migration_file = os.path.join(migration_dir, "%s_%s.py" % (migration_count, migration_name))
# Check for existing migration file in migration folder
self.assertTrue(os.path.exists(migration_file))
with open(migration_file, encoding='utf-8') as fp:
content = fp.read()
content = content.replace(" ", "")
return content
# generate an initial migration
migration_name_0001 = "my_initial_migration"
content = cmd("0001", migration_name_0001)
self.assertIn("dependencies=[\n]", content)
# importlib caches os.listdir() on some platforms like macOS
# (#23850).
if hasattr(importlib, 'invalidate_caches'):
importlib.invalidate_caches()
# generate an empty migration
migration_name_0002 = "my_custom_migration"
content = cmd("0002", migration_name_0002, "--empty")
self.assertIn("dependencies=[\n('migrations','0001_%s'),\n]" % migration_name_0001, content)
self.assertIn("operations=[\n]", content)
def test_makemigrations_with_invalid_custom_name(self):
msg = 'The migration name must be a valid Python identifier.'
with self.assertRaisesMessage(CommandError, msg):
call_command('makemigrations', 'migrations', '--name', 'invalid name', '--empty')
def test_makemigrations_check(self):
with self.temporary_migration_module():
with self.assertRaises(SystemExit):
call_command("makemigrations", "--check", "migrations", verbosity=0)
with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
call_command("makemigrations", "--check", "migrations", verbosity=0)
def test_makemigrations_migration_path_output(self):
out = io.StringIO()
apps.register_model('migrations', UnicodeModel)
with self.temporary_migration_module() as migration_dir:
call_command("makemigrations", "migrations", stdout=out)
self.assertIn(os.path.join(migration_dir, '0001_initial.py'), out.getvalue())
def test_makemigrations_migration_path_output_valueerror(self):
out = io.StringIO()
with self.temporary_migration_module() as migration_dir:
with mock.patch('os.path.relpath', side_effect=ValueError):
call_command('makemigrations', 'migrations', stdout=out)
self.assertIn(os.path.join(migration_dir, '0001_initial.py'), out.getvalue())
def test_makemigrations_inconsistent_history(self):
recorder = MigrationRecorder(connection)
recorder.record_applied('migrations', '0002_second')
msg = "Migration migrations.0002_second is applied before its dependency migrations.0001_initial"
with self.temporary_migration_module(module="migrations.test_migrations"):
with self.assertRaisesMessage(InconsistentMigrationHistory, msg):
call_command("makemigrations")
@mock.patch('builtins.input', return_value='1')
@mock.patch('django.db.migrations.questioner.sys.stdin', mock.MagicMock(encoding=sys.getdefaultencoding()))
def test_makemigrations_auto_now_add_interactive(self, *args):
class Entry(models.Model):
title = models.CharField(max_length=255)
creation_date = models.DateTimeField(auto_now_add=True)
class Meta:
app_label = 'migrations'
# Monkeypatch interactive questioner to auto accept
with mock.patch('django.db.migrations.questioner.sys.stdout', new_callable=io.StringIO) as prompt_stdout:
out = io.StringIO()
with self.temporary_migration_module(module='migrations.test_auto_now_add'):
call_command('makemigrations', 'migrations', interactive=True, stdout=out)
output = out.getvalue()
prompt_output = prompt_stdout.getvalue()
self.assertIn("You can accept the default 'timezone.now' by pressing 'Enter'", prompt_output)
self.assertIn("Add field creation_date to entry", output)
class SquashMigrationsTests(MigrationTestBase):
def test_squashmigrations_squashes(self):
with self.temporary_migration_module(module="migrations.test_migrations") as migration_dir:
call_command("squashmigrations", "migrations", "0002", interactive=False, verbosity=0)
squashed_migration_file = os.path.join(migration_dir, "0001_squashed_0002_second.py")
self.assertTrue(os.path.exists(squashed_migration_file))
def test_squashmigrations_initial_attribute(self):
with self.temporary_migration_module(module="migrations.test_migrations") as migration_dir:
call_command("squashmigrations", "migrations", "0002", interactive=False, verbosity=0)
squashed_migration_file = os.path.join(migration_dir, "0001_squashed_0002_second.py")
with open(squashed_migration_file, encoding='utf-8') as fp:
content = fp.read()
self.assertIn("initial = True", content)
def test_squashmigrations_optimizes(self):
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations"):
call_command("squashmigrations", "migrations", "0002", interactive=False, verbosity=1, stdout=out)
self.assertIn("Optimized from 8 operations to 2 operations.", out.getvalue())
def test_ticket_23799_squashmigrations_no_optimize(self):
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations"):
call_command("squashmigrations", "migrations", "0002",
interactive=False, verbosity=1, no_optimize=True, stdout=out)
self.assertIn("Skipping optimization", out.getvalue())
def test_squashmigrations_valid_start(self):
out = io.StringIO()
with self.temporary_migration_module(module="migrations.test_migrations_no_changes") as migration_dir:
call_command("squashmigrations", "migrations", "0002", "0003",
interactive=False, verbosity=1, stdout=out)
squashed_migration_file = os.path.join(migration_dir, "0002_second_squashed_0003_third.py")
with open(squashed_migration_file, encoding='utf-8') as fp:
content = fp.read()
self.assertIn(" ('migrations', '0001_initial')", content)
self.assertNotIn("initial = True", content)
out = out.getvalue()
self.assertNotIn(" - 0001_initial", out)
self.assertIn(" - 0002_second", out)
self.assertIn(" - 0003_third", out)
def test_squashmigrations_invalid_start(self):
with self.temporary_migration_module(module="migrations.test_migrations_no_changes"):
msg = (
"The migration 'migrations.0003_third' cannot be found. Maybe "
"it comes after the migration 'migrations.0002_second'"
)
with self.assertRaisesMessage(CommandError, msg):
call_command("squashmigrations", "migrations", "0003", "0002", interactive=False, verbosity=0)
def test_squashed_name_with_start_migration_name(self):
squashed_name = 'squashed_name'
with self.temporary_migration_module(module='migrations.test_migrations') as migration_dir:
call_command(
'squashmigrations', 'migrations', '0001', '0002',
squashed_name=squashed_name, interactive=False, verbosity=0,
)
squashed_migration_file = os.path.join(migration_dir, '0001_%s.py' % squashed_name)
self.assertTrue(os.path.exists(squashed_migration_file))
def test_squashed_name_without_start_migration_name(self):
squashed_name = 'squashed_name'
with self.temporary_migration_module(module="migrations.test_migrations") as migration_dir:
call_command(
'squashmigrations', 'migrations', '0001',
squashed_name=squashed_name, interactive=False, verbosity=0,
)
squashed_migration_file = os.path.join(migration_dir, '0001_%s.py' % squashed_name)
self.assertTrue(os.path.exists(squashed_migration_file))
class AppLabelErrorTests(TestCase):
nonexistent_app_error = "No installed app with label 'nonexistent_app'."
did_you_mean_auth_error = (
"No installed app with label 'django.contrib.auth'. Did you mean "
"'auth'?"
)
def test_makemigrations_nonexistent_app_label(self):
err = io.StringIO()
with self.assertRaises(SystemExit):
call_command('makemigrations', 'nonexistent_app', stderr=err)
self.assertIn(self.nonexistent_app_error, err.getvalue())
def test_makemigrations_app_name_specified_as_label(self):
err = io.StringIO()
with self.assertRaises(SystemExit):
call_command('makemigrations', 'django.contrib.auth', stderr=err)
self.assertIn(self.did_you_mean_auth_error, err.getvalue())
def test_migrate_nonexistent_app_label(self):
with self.assertRaisesMessage(CommandError, self.nonexistent_app_error):
call_command('migrate', 'nonexistent_app')
def test_migrate_app_name_specified_as_label(self):
with self.assertRaisesMessage(CommandError, self.did_you_mean_auth_error):
call_command('migrate', 'django.contrib.auth')
def test_showmigrations_nonexistent_app_label(self):
err = io.StringIO()
with self.assertRaises(SystemExit):
call_command('showmigrations', 'nonexistent_app', stderr=err)
self.assertIn(self.nonexistent_app_error, err.getvalue())
def test_showmigrations_app_name_specified_as_label(self):
err = io.StringIO()
with self.assertRaises(SystemExit):
call_command('showmigrations', 'django.contrib.auth', stderr=err)
self.assertIn(self.did_you_mean_auth_error, err.getvalue())
def test_sqlmigrate_nonexistent_app_label(self):
with self.assertRaisesMessage(CommandError, self.nonexistent_app_error):
call_command('sqlmigrate', 'nonexistent_app', '0002')
def test_sqlmigrate_app_name_specified_as_label(self):
with self.assertRaisesMessage(CommandError, self.did_you_mean_auth_error):
call_command('sqlmigrate', 'django.contrib.auth', '0002')
def test_squashmigrations_nonexistent_app_label(self):
with self.assertRaisesMessage(CommandError, self.nonexistent_app_error):
call_command('squashmigrations', 'nonexistent_app', '0002')
def test_squashmigrations_app_name_specified_as_label(self):
with self.assertRaisesMessage(CommandError, self.did_you_mean_auth_error):
call_command('squashmigrations', 'django.contrib.auth', '0002')
| true | true |
f7f8a6eb63db0c10f63cbe777b8b0a03762a708c | 14,704 | py | Python | step1_UNET_train.py | nchlis/rsom_vasculature | 320b6f0ff0a9968f18c6500aaa93d4c1d86ad25f | [
"MIT"
] | null | null | null | step1_UNET_train.py | nchlis/rsom_vasculature | 320b6f0ff0a9968f18c6500aaa93d4c1d86ad25f | [
"MIT"
] | null | null | null | step1_UNET_train.py | nchlis/rsom_vasculature | 320b6f0ff0a9968f18c6500aaa93d4c1d86ad25f | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 6 16:04:13 2018
@author: N.Chlis
"""
#if used on a non-GUI server ######
#import matplotlib
#matplotlib.use('Agg')
###################################
import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
try:
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
except RuntimeError as e:
print(e)
import numpy as np
#import pandas as pd
import matplotlib.pyplot as plt
#import h5py
import pandas as pd
from keras.models import Model
from keras.layers import Input
from keras.layers import Activation
from keras.layers import BatchNormalization
from keras.layers import Dense
#from keras.layers import Flatten
from keras.layers import AveragePooling2D
from keras.layers.convolutional import Conv2D, MaxPooling2D, UpSampling2D, AveragePooling2D, Conv2DTranspose
from keras.layers.merge import concatenate #Concatenate (capital C) not working
#from keras.utils.vis_utils import plot_model
from keras.layers import Dropout
from keras.callbacks import EarlyStopping
from keras.callbacks import ModelCheckpoint
from keras.callbacks import CSVLogger
import time
import skimage.transform
from sklearn.model_selection import train_test_split
from keras import backend as K
import gc
import os
def rotateT(X,angle):
#rotate image tensor, TF order, single channel
X_rot = np.zeros_like(X)
#repeat for every channel
for ch in np.arange(X.shape[-1]):
#print('channel',ch)
#repeat for every image
for i in np.arange(X.shape[0]):
#print('image',i)
X_rot[i,:,:,ch] = skimage.transform.rotate(X[i,:,:,ch],angle=angle,resize=False,preserve_range=True,mode='edge')
return(X_rot)
def shiftT(X,dx,dy):
#shift image tensor, TF order, single channel
X_shift = np.zeros_like(X)
#repeat for every image
tform = skimage.transform.SimilarityTransform(translation=(dx, dy))
for i in np.arange(X.shape[0]):
#print('image',i)
X_shift[i,:,:,:] = skimage.transform.warp(X[i,:,:,:],tform,mode='edge')
return(X_shift)
#%% define the generator for training
# randomly flip, rotate and translate each input image
def aug_generator(X_raw=None,Y_raw=None,
batch_size=4,
flip_axes=['x','y'],
rotation_angles=[5,15],
translate_axes=['x','y'],
translate_percentages=[0,0.1]):
batch_size=batch_size#recommended batch size
Ndatapoints = len(X_raw)
#Naugmentations=4 #original + flip, rotation, noise_gaussian, noise_snp
while(True):
#print('start!')
ix_randomized = np.random.choice(Ndatapoints,size=Ndatapoints,replace=False)
ix_batches = np.array_split(ix_randomized,int(Ndatapoints/batch_size))
for b in range(len(ix_batches)):
#print('step',b,'of',len(ix_batches))
ix_batch = ix_batches[b]
current_batch_size=len(ix_batch)
#print('size of current batch',current_batch_size)
#print(ix_batch)
X_batch = X_raw[ix_batch,:,:,:].copy()#.copy() to leave original unchanged
Y_batch = Y_raw[ix_batch,:,:,:].copy()#.copy() to leave original unchanged
#now do augmentation on images and masks
#iterate over each image in the batch
for img in range(current_batch_size):
#print('current_image',img,': ',ix_batch[img])
do_aug=np.random.choice([True, False],size=1)[0]#50-50 chance
if do_aug == True:
#print('flipping',img)
flip_axis_selected = np.random.choice(flip_axes,1,replace=False)[0]
if flip_axis_selected == 'x':
flip_axis_selected = 1
else: # 'y'
flip_axis_selected = 0
#flip an axis
X_batch[img,:,:,:] = np.flip(X_batch[img,:,:,:],axis=flip_axis_selected)
Y_batch[img,:,:,:] = np.flip(Y_batch[img,:,:,:],axis=flip_axis_selected)
#print('Flip on axis',flip_axis_selected)
do_aug=np.random.choice([True, False],size=1)[0]#50-50 chance
if do_aug == True:
#print('rotating',img)
rotation_angle_selected = np.random.uniform(low=rotation_angles[0],high=rotation_angles[1],size=1)[0]
#rotate the image
X_batch[img,:,:,:] = rotateT(np.expand_dims(X_batch[img,:,:,:],axis=0),angle=rotation_angle_selected)
Y_batch[img,:,:,:] = rotateT(np.expand_dims(Y_batch[img,:,:,:],axis=0),angle=rotation_angle_selected)
#print('Rotate angle',rotation_angle_selected)
do_aug=np.random.choice([True, False],size=1)[0]#50-50 chance
if do_aug == True:
#print('shifting',img)
#print(X_batch.shape)
dx=0
if 'x' in translate_axes:
dx=np.random.uniform(low=translate_percentages[0],high=translate_percentages[1],size=1)[0]
dx=dx*X_batch.shape[1]
dy=0
if 'y' in translate_axes:
dy=np.random.uniform(low=translate_percentages[0],high=translate_percentages[1],size=1)[0]
dy=dy*X_batch.shape[2]
#translate the image
#print('dx',dx)
#print('dy',dy)
X_batch[img,:,:,:] = shiftT(np.expand_dims(X_batch[img,:,:,:],axis=0),dx=dx,dy=dy)
Y_batch[img,:,:,:] = shiftT(np.expand_dims(Y_batch[img,:,:,:],axis=0),dx=dx,dy=dy)
Y_batch_skin=(Y_batch==1).astype('float')
Y_batch_vasc=(Y_batch==2).astype('float')
yield(X_batch,[Y_batch_skin,Y_batch_vasc])
#print('step end after',b,'of',len(ix_batches))
#%%
#load the data
IMHEIGHT = 768
IMWIDTH = 256
savepath = './data_'+str(IMHEIGHT)+'_'+str(IMWIDTH)+'_annotated/'
#df=pd.read_csv(savepath+'/metadata_qc.csv')
df=pd.read_csv(savepath+'/metadata_qc_extra.csv')
X=np.load(savepath+'X.npy')#data
Y=np.load(savepath+'Y.npy')#masks
X=X[:,:,:,0:2]#drop the last black channel
df=pd.read_csv(savepath+'/metadata_qc_extra.csv')
study=df['case'].values
#do quality control, only keep 115 out of 122 unique studies
#the 115 unique studies correspond to unique 205 scans (multiple scans for some patients)
qc_pass = df.quality_control.values=='pass'
study=study[qc_pass]
X=X[qc_pass,:,:,:]
Y=Y[qc_pass,:,:,:]
study_unique=np.unique(study)
#%% do leave one patient out validation
start=0
#resume=True
resume=False
if resume==True:
#there are 2 files per saved model in the trained_models folder
start=int(len(os.listdir('./trained_models/'))/2)
for i in np.arange(start=start,stop=len(study_unique)):#Leave one study out
print('*** Study',i+1,'of',len(study_unique),'***')
s = study_unique[i]
print('Study number',s)
train_ix = study!=s
test_ix = study==s
X_tr=X[train_ix,:]
Y_tr=Y[train_ix,:]
#X_ts=X[test_ix,:]
#Y_ts=Y[test_ix,:]
X_tr, X_val, Y_tr, Y_val = train_test_split(X_tr, Y_tr, test_size=0.1, random_state=1)
Y_tr_skin=(Y_tr==1).astype('float')
Y_tr_vasc=(Y_tr==2).astype('float')
Y_val_skin=(Y_val==1).astype('float')
Y_val_vasc=(Y_val==2).astype('float')
#%% set-up the UNET model
#model parameters
bnorm_axis = -1
#filter sizes of the original model
nfilters = np.array([64, 128, 256, 512, 1024])
drop_rate=0.5
drop_train=False
#downsize the UNET for this example.
#the smaller network is faster to train
#and produces excellent results on the dataset at hand
div=8
nfilters = (nfilters/div).astype('int')
#aug=True
aug=False
#input
input_tensor = Input(shape=X_tr.shape[1:], name='input_tensor')
####################################
# encoder (contracting path)
####################################
#encoder block 0
e0 = Conv2D(filters=nfilters[0], kernel_size=(3,3), padding='same')(input_tensor)
e0 = BatchNormalization(axis=bnorm_axis)(e0)
e0 = Activation('relu')(e0)
e0 = Conv2D(filters=nfilters[0], kernel_size=(3,3), padding='same')(e0)
e0 = BatchNormalization(axis=bnorm_axis)(e0)
e0 = Activation('relu')(e0)
#encoder block 1
e1 = MaxPooling2D((2, 2))(e0)
e1 = Conv2D(filters=nfilters[1], kernel_size=(3,3), padding='same')(e1)
e1 = BatchNormalization(axis=bnorm_axis)(e1)
e1 = Activation('relu')(e1)
e1 = Conv2D(filters=nfilters[1], kernel_size=(3,3), padding='same')(e1)
e1 = BatchNormalization(axis=bnorm_axis)(e1)
e1 = Activation('relu')(e1)
#encoder block 2
e2 = Dropout(drop_rate)(e1, training = drop_train)
e2 = MaxPooling2D((2, 2))(e2)
e2 = Conv2D(filters=nfilters[2], kernel_size=(3,3), padding='same')(e2)
e2 = BatchNormalization(axis=bnorm_axis)(e2)
e2 = Activation('relu')(e2)
e2 = Conv2D(filters=nfilters[2], kernel_size=(3,3), padding='same')(e2)
e2 = BatchNormalization(axis=bnorm_axis)(e2)
e2 = Activation('relu')(e2)
#encoder block 3
e3 = Dropout(drop_rate)(e2, training = drop_train)
e3 = MaxPooling2D((2, 2))(e3)
e3 = Conv2D(filters=nfilters[3], kernel_size=(3,3), padding='same')(e3)
e3 = BatchNormalization(axis=bnorm_axis)(e3)
e3 = Activation('relu')(e3)
e3 = Conv2D(filters=nfilters[3], kernel_size=(3,3), padding='same')(e3)
e3 = BatchNormalization(axis=bnorm_axis)(e3)
e3 = Activation('relu')(e3)
#encoder block 4
e4 = Dropout(drop_rate)(e3, training = drop_train)
e4 = MaxPooling2D((2, 2))(e4)
e4 = Conv2D(filters=nfilters[4], kernel_size=(3,3), padding='same')(e4)
e4 = BatchNormalization(axis=bnorm_axis)(e4)
e4 = Activation('relu')(e4)
e4 = Conv2D(filters=nfilters[4], kernel_size=(3,3), padding='same')(e4)
e4 = BatchNormalization(axis=bnorm_axis)(e4)
e4 = Activation('relu')(e4)
#e4 = MaxPooling2D((2, 2))(e4)
####################################
# decoder (expansive path)
####################################
#decoder block 3
d3 = Dropout(drop_rate)(e4, training = drop_train)
d3=UpSampling2D((2, 2),)(d3)
d3=concatenate([e3,d3], axis=-1)#skip connection
d3=Conv2DTranspose(nfilters[3], (3, 3), padding='same')(d3)
d3=BatchNormalization(axis=bnorm_axis)(d3)
d3=Activation('relu')(d3)
d3=Conv2DTranspose(nfilters[3], (3, 3), padding='same')(d3)
d3=BatchNormalization(axis=bnorm_axis)(d3)
d3=Activation('relu')(d3)
#decoder block 2
d2 = Dropout(drop_rate)(d3, training = drop_train)
d2=UpSampling2D((2, 2),)(d2)
d2=concatenate([e2,d2], axis=-1)#skip connection
d2=Conv2DTranspose(nfilters[2], (3, 3), padding='same')(d2)
d2=BatchNormalization(axis=bnorm_axis)(d2)
d2=Activation('relu')(d2)
d2=Conv2DTranspose(nfilters[2], (3, 3), padding='same')(d2)
d2=BatchNormalization(axis=bnorm_axis)(d2)
d2=Activation('relu')(d2)
#decoder block 1
d1=UpSampling2D((2, 2),)(d2)
d1=concatenate([e1,d1], axis=-1)#skip connection
d1=Conv2DTranspose(nfilters[1], (3, 3), padding='same')(d1)
d1=BatchNormalization(axis=bnorm_axis)(d1)
d1=Activation('relu')(d1)
d1=Conv2DTranspose(nfilters[1], (3, 3), padding='same')(d1)
d1=BatchNormalization(axis=bnorm_axis)(d1)
d1=Activation('relu')(d1)
#decoder block 0
d0=UpSampling2D((2, 2),)(d1)
d0=concatenate([e0,d0], axis=-1)#skip connection
d0=Conv2DTranspose(nfilters[0], (3, 3), padding='same')(d0)
d0=BatchNormalization(axis=bnorm_axis)(d0)
d0=Activation('relu')(d0)
d0=Conv2DTranspose(nfilters[0], (3, 3), padding='same')(d0)
d0=BatchNormalization(axis=bnorm_axis)(d0)
d0=Activation('relu')(d0)
#output
#out_class = Dense(1)(d0)
out_class_skin = Conv2D(1, (1, 1), padding='same')(d0)
out_class_skin = Activation('sigmoid',name='output_skin')(out_class_skin)
out_class_vasc = Conv2D(1, (1, 1), padding='same')(d0)
out_class_vasc = Activation('sigmoid',name='output_vasc')(out_class_vasc)
#create and compile the model
model=Model(inputs=input_tensor,outputs=[out_class_skin,out_class_vasc])
model.compile(loss={'output_skin':'binary_crossentropy',#epidermis region
'output_vasc':'binary_crossentropy'},#dermis region
optimizer='adam')
#%%
print(model.summary())
#%% train the model
filepath = 'mcd_unet_testStudy'+str(s)+'_MSOT_div'+str(div)+'_drop_rate'+str(drop_rate)+'_aug'+str(aug)
#save the model when val_loss improves during training
checkpoint = ModelCheckpoint('./trained_models/'+filepath+'.hdf5', monitor='val_loss', verbose=1, save_best_only=True, mode='auto')
#save training progress in a .csv
csvlog = CSVLogger('./trained_models/'+filepath+'_train_log.csv',append=True)
#stop training if no improvement has been seen on val_loss for a while
early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=40)
batch_size=16
#initialize the generator
gen_train = aug_generator(X_tr,Y_tr,batch_size=batch_size,flip_axes=['x'])
#split the array and see how many splits there are to determine #steps
steps_per_epoch_tr = len(np.array_split(np.zeros(len(X_tr)),int(len(X_tr)/batch_size)))
if aug==True:
#actually do the training
model.fit_generator(generator=gen_train,
steps_per_epoch=steps_per_epoch_tr,#the generator internally goes over the entire dataset in one iteration
validation_data=(X_val,[Y_val_skin,Y_val_vasc]),
epochs=200,
verbose=2,
initial_epoch=0,
callbacks=[checkpoint, csvlog, early_stopping])
else:#no data augmentation
model.fit(x=X_tr,y=[Y_tr_skin,Y_tr_vasc],
batch_size=batch_size,
validation_data=(X_val,[Y_val_skin,Y_val_vasc]),
epochs=200,
verbose=2,
initial_epoch=0,
callbacks=[checkpoint, csvlog, early_stopping])
print('clearing Keras session...')
del model
K.clear_session()
gc.collect()
| 39.002653 | 135 | 0.614867 |
Pooling2D, Conv2DTranspose
from keras.layers.merge import concatenate
from keras.layers import Dropout
from keras.callbacks import EarlyStopping
from keras.callbacks import ModelCheckpoint
from keras.callbacks import CSVLogger
import time
import skimage.transform
from sklearn.model_selection import train_test_split
from keras import backend as K
import gc
import os
def rotateT(X,angle):
X_rot = np.zeros_like(X)
for ch in np.arange(X.shape[-1]):
for i in np.arange(X.shape[0]):
X_rot[i,:,:,ch] = skimage.transform.rotate(X[i,:,:,ch],angle=angle,resize=False,preserve_range=True,mode='edge')
return(X_rot)
def shiftT(X,dx,dy):
X_shift = np.zeros_like(X)
tform = skimage.transform.SimilarityTransform(translation=(dx, dy))
for i in np.arange(X.shape[0]):
X_shift[i,:,:,:] = skimage.transform.warp(X[i,:,:,:],tform,mode='edge')
return(X_shift)
def aug_generator(X_raw=None,Y_raw=None,
batch_size=4,
flip_axes=['x','y'],
rotation_angles=[5,15],
translate_axes=['x','y'],
translate_percentages=[0,0.1]):
batch_size=batch_size
Ndatapoints = len(X_raw)
= np.random.choice(Ndatapoints,size=Ndatapoints,replace=False)
ix_batches = np.array_split(ix_randomized,int(Ndatapoints/batch_size))
for b in range(len(ix_batches)):
ix_batch = ix_batches[b]
current_batch_size=len(ix_batch)
X_batch = X_raw[ix_batch,:,:,:].copy()
Y_batch = Y_raw[ix_batch,:,:,:].copy()
for img in range(current_batch_size):
do_aug=np.random.choice([True, False],size=1)[0]
if do_aug == True:
flip_axis_selected = np.random.choice(flip_axes,1,replace=False)[0]
if flip_axis_selected == 'x':
flip_axis_selected = 1
else:
flip_axis_selected = 0
X_batch[img,:,:,:] = np.flip(X_batch[img,:,:,:],axis=flip_axis_selected)
Y_batch[img,:,:,:] = np.flip(Y_batch[img,:,:,:],axis=flip_axis_selected)
do_aug=np.random.choice([True, False],size=1)[0]
if do_aug == True:
rotation_angle_selected = np.random.uniform(low=rotation_angles[0],high=rotation_angles[1],size=1)[0]
X_batch[img,:,:,:] = rotateT(np.expand_dims(X_batch[img,:,:,:],axis=0),angle=rotation_angle_selected)
Y_batch[img,:,:,:] = rotateT(np.expand_dims(Y_batch[img,:,:,:],axis=0),angle=rotation_angle_selected)
do_aug=np.random.choice([True, False],size=1)[0]
if do_aug == True:
dx=0
if 'x' in translate_axes:
dx=np.random.uniform(low=translate_percentages[0],high=translate_percentages[1],size=1)[0]
dx=dx*X_batch.shape[1]
dy=0
if 'y' in translate_axes:
dy=np.random.uniform(low=translate_percentages[0],high=translate_percentages[1],size=1)[0]
dy=dy*X_batch.shape[2]
X_batch[img,:,:,:] = shiftT(np.expand_dims(X_batch[img,:,:,:],axis=0),dx=dx,dy=dy)
Y_batch[img,:,:,:] = shiftT(np.expand_dims(Y_batch[img,:,:,:],axis=0),dx=dx,dy=dy)
Y_batch_skin=(Y_batch==1).astype('float')
Y_batch_vasc=(Y_batch==2).astype('float')
yield(X_batch,[Y_batch_skin,Y_batch_vasc])
IMHEIGHT = 768
IMWIDTH = 256
savepath = './data_'+str(IMHEIGHT)+'_'+str(IMWIDTH)+'_annotated/'
df=pd.read_csv(savepath+'/metadata_qc_extra.csv')
X=np.load(savepath+'X.npy')
Y=np.load(savepath+'Y.npy')
X=X[:,:,:,0:2]
df=pd.read_csv(savepath+'/metadata_qc_extra.csv')
study=df['case'].values
qc_pass = df.quality_control.values=='pass'
study=study[qc_pass]
X=X[qc_pass,:,:,:]
Y=Y[qc_pass,:,:,:]
study_unique=np.unique(study)
start=0
resume=False
if resume==True:
start=int(len(os.listdir('./trained_models/'))/2)
for i in np.arange(start=start,stop=len(study_unique)):
print('*** Study',i+1,'of',len(study_unique),'***')
s = study_unique[i]
print('Study number',s)
train_ix = study!=s
test_ix = study==s
X_tr=X[train_ix,:]
Y_tr=Y[train_ix,:]
X_tr, X_val, Y_tr, Y_val = train_test_split(X_tr, Y_tr, test_size=0.1, random_state=1)
Y_tr_skin=(Y_tr==1).astype('float')
Y_tr_vasc=(Y_tr==2).astype('float')
Y_val_skin=(Y_val==1).astype('float')
Y_val_vasc=(Y_val==2).astype('float')
bnorm_axis = -1
nfilters = np.array([64, 128, 256, 512, 1024])
drop_rate=0.5
drop_train=False
div=8
nfilters = (nfilters/div).astype('int')
aug=False
input_tensor = Input(shape=X_tr.shape[1:], name='input_tensor')
3,3), padding='same')(e3)
e3 = BatchNormalization(axis=bnorm_axis)(e3)
e3 = Activation('relu')(e3)
e3 = Conv2D(filters=nfilters[3], kernel_size=(3,3), padding='same')(e3)
e3 = BatchNormalization(axis=bnorm_axis)(e3)
e3 = Activation('relu')(e3)
e4 = Dropout(drop_rate)(e3, training = drop_train)
e4 = MaxPooling2D((2, 2))(e4)
e4 = Conv2D(filters=nfilters[4], kernel_size=(3,3), padding='same')(e4)
e4 = BatchNormalization(axis=bnorm_axis)(e4)
e4 = Activation('relu')(e4)
e4 = Conv2D(filters=nfilters[4], kernel_size=(3,3), padding='same')(e4)
e4 = BatchNormalization(axis=bnorm_axis)(e4)
e4 = Activation('relu')(e4)
catenate([e0,d0], axis=-1)
d0=Conv2DTranspose(nfilters[0], (3, 3), padding='same')(d0)
d0=BatchNormalization(axis=bnorm_axis)(d0)
d0=Activation('relu')(d0)
d0=Conv2DTranspose(nfilters[0], (3, 3), padding='same')(d0)
d0=BatchNormalization(axis=bnorm_axis)(d0)
d0=Activation('relu')(d0)
out_class_skin = Conv2D(1, (1, 1), padding='same')(d0)
out_class_skin = Activation('sigmoid',name='output_skin')(out_class_skin)
out_class_vasc = Conv2D(1, (1, 1), padding='same')(d0)
out_class_vasc = Activation('sigmoid',name='output_vasc')(out_class_vasc)
model=Model(inputs=input_tensor,outputs=[out_class_skin,out_class_vasc])
model.compile(loss={'output_skin':'binary_crossentropy',
'output_vasc':'binary_crossentropy'},
optimizer='adam')
print(model.summary())
filepath = 'mcd_unet_testStudy'+str(s)+'_MSOT_div'+str(div)+'_drop_rate'+str(drop_rate)+'_aug'+str(aug)
checkpoint = ModelCheckpoint('./trained_models/'+filepath+'.hdf5', monitor='val_loss', verbose=1, save_best_only=True, mode='auto')
csvlog = CSVLogger('./trained_models/'+filepath+'_train_log.csv',append=True)
early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=40)
batch_size=16
gen_train = aug_generator(X_tr,Y_tr,batch_size=batch_size,flip_axes=['x'])
teps_per_epoch_tr = len(np.array_split(np.zeros(len(X_tr)),int(len(X_tr)/batch_size)))
if aug==True:
model.fit_generator(generator=gen_train,
steps_per_epoch=steps_per_epoch_tr,
validation_data=(X_val,[Y_val_skin,Y_val_vasc]),
epochs=200,
verbose=2,
initial_epoch=0,
callbacks=[checkpoint, csvlog, early_stopping])
else:
model.fit(x=X_tr,y=[Y_tr_skin,Y_tr_vasc],
batch_size=batch_size,
validation_data=(X_val,[Y_val_skin,Y_val_vasc]),
epochs=200,
verbose=2,
initial_epoch=0,
callbacks=[checkpoint, csvlog, early_stopping])
print('clearing Keras session...')
del model
K.clear_session()
gc.collect()
| true | true |
f7f8a6fdab32dc1c54645d1c1932231b6fbb75d8 | 449 | py | Python | example/search_para.py | natethinks/cherry | a482621a3e397f6667f21e16d5ec0eb12c7fc4fb | [
"MIT"
] | 1 | 2020-03-07T16:59:09.000Z | 2020-03-07T16:59:09.000Z | example/search_para.py | natethinks/cherry | a482621a3e397f6667f21e16d5ec0eb12c7fc4fb | [
"MIT"
] | null | null | null | example/search_para.py | natethinks/cherry | a482621a3e397f6667f21e16d5ec0eb12c7fc4fb | [
"MIT"
] | null | null | null | from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.linear_model import SGDClassifier
from sklearn.svm import SVC
import cherry
import numpy as np
parameters = {
'clf__alpha': [0.1, 0.5, 1],
'clf__fit_prior': [True, False]
}
cherry.search('harmful', parameters, cv=10, n_jobs=-1)
| 24.944444 | 76 | 0.790646 | from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.linear_model import SGDClassifier
from sklearn.svm import SVC
import cherry
import numpy as np
parameters = {
'clf__alpha': [0.1, 0.5, 1],
'clf__fit_prior': [True, False]
}
cherry.search('harmful', parameters, cv=10, n_jobs=-1)
| true | true |
f7f8a7e539915aea4ea6f9e0d76500b25eda3ad9 | 147 | py | Python | 17/02/4.py | pylangstudy/201706 | f1cc6af6b18e5bd393cda27f5166067c4645d4d3 | [
"CC0-1.0"
] | null | null | null | 17/02/4.py | pylangstudy/201706 | f1cc6af6b18e5bd393cda27f5166067c4645d4d3 | [
"CC0-1.0"
] | 70 | 2017-06-01T11:02:51.000Z | 2017-06-30T00:35:32.000Z | 17/02/4.py | pylangstudy/201706 | f1cc6af6b18e5bd393cda27f5166067c4645d4d3 | [
"CC0-1.0"
] | null | null | null | class Human:
def __init__(self, name, age=10):
self.name = name
self.age = age
c = Human('Yamada')
print(c.name)
print(c.age)
| 16.333333 | 37 | 0.591837 | class Human:
def __init__(self, name, age=10):
self.name = name
self.age = age
c = Human('Yamada')
print(c.name)
print(c.age)
| true | true |
f7f8a8d270acb0b807f8aa99470fa8628463a10a | 751 | py | Python | V2RaycSpider1225/src/services/utils/armor/anti_email/exceptions.py | winkxx/V2RayCloudSpider | de1c87a0d823ba4c9a905c5ff4fdf70911b05332 | [
"MIT"
] | 1 | 2021-12-10T14:27:44.000Z | 2021-12-10T14:27:44.000Z | V2RaycSpider1225/src/services/utils/armor/anti_email/exceptions.py | kaimrdzt/V2RayCloudSpider | de1c87a0d823ba4c9a905c5ff4fdf70911b05332 | [
"MIT"
] | null | null | null | V2RaycSpider1225/src/services/utils/armor/anti_email/exceptions.py | kaimrdzt/V2RayCloudSpider | de1c87a0d823ba4c9a905c5ff4fdf70911b05332 | [
"MIT"
] | 1 | 2021-12-10T14:27:48.000Z | 2021-12-10T14:27:48.000Z | # -*- coding: utf-8 -*-
# Time : 2021/12/22 9:04
# Author : QIN2DIM
# Github : https://github.com/QIN2DIM
# Description:
from typing import Optional, Sequence
class AntiEmailException(Exception):
def __init__(self, msg: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None) -> None:
self.msg = msg
self.stacktrace = stacktrace
def __str__(self) -> str:
exception_msg = "Message: {}\n".format(self.msg)
if self.stacktrace:
stacktrace = "\n".join(self.stacktrace)
exception_msg += "Stacktrace:\n{}".format(stacktrace)
return exception_msg
class GetEmailTimeout(AntiEmailException):
pass
class GetEmailCodeTimeout(AntiEmailException):
pass
| 25.896552 | 102 | 0.648469 |
from typing import Optional, Sequence
class AntiEmailException(Exception):
def __init__(self, msg: Optional[str] = None, stacktrace: Optional[Sequence[str]] = None) -> None:
self.msg = msg
self.stacktrace = stacktrace
def __str__(self) -> str:
exception_msg = "Message: {}\n".format(self.msg)
if self.stacktrace:
stacktrace = "\n".join(self.stacktrace)
exception_msg += "Stacktrace:\n{}".format(stacktrace)
return exception_msg
class GetEmailTimeout(AntiEmailException):
pass
class GetEmailCodeTimeout(AntiEmailException):
pass
| true | true |
f7f8a9043512f8d9ef83fe92d6463ce10aaf227a | 675 | py | Python | RESTBasic/migrations/versions/4be2799e102a_initial_database.py | vgeorgo/courses-python-udemy-create-websites-using-flask | 34f0a789402f4dabfdbf87272fc823979b3af313 | [
"MIT"
] | 1 | 2021-01-05T19:26:07.000Z | 2021-01-05T19:26:07.000Z | RESTBasic/migrations/versions/4be2799e102a_initial_database.py | vgeorgo/courses-python-udemy-create-websites-using-flask | 34f0a789402f4dabfdbf87272fc823979b3af313 | [
"MIT"
] | null | null | null | RESTBasic/migrations/versions/4be2799e102a_initial_database.py | vgeorgo/courses-python-udemy-create-websites-using-flask | 34f0a789402f4dabfdbf87272fc823979b3af313 | [
"MIT"
] | null | null | null | """initial database
Revision ID: 4be2799e102a
Revises:
Create Date: 2018-11-28 20:39:45.470767
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '4be2799e102a'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('puppy',
sa.Column('name', sa.String(length=80), nullable=False),
sa.PrimaryKeyConstraint('name')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('puppy')
# ### end Alembic commands ###
| 21.09375 | 65 | 0.678519 | from alembic import op
import sqlalchemy as sa
revision = '4be2799e102a'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
| true | true |
f7f8a9c041be576fde6e55df4c464185a1401561 | 1,868 | py | Python | src/api/dataflow/flow/handlers/nodes/base_node/base_source_node.py | Chromico/bk-base | be822d9bbee544a958bed4831348185a75604791 | [
"MIT"
] | 84 | 2021-06-30T06:20:23.000Z | 2022-03-22T03:05:49.000Z | src/api/dataflow/flow/handlers/nodes/base_node/base_source_node.py | Chromico/bk-base | be822d9bbee544a958bed4831348185a75604791 | [
"MIT"
] | 7 | 2021-06-30T06:21:16.000Z | 2022-03-29T07:36:13.000Z | src/api/dataflow/flow/handlers/nodes/base_node/base_source_node.py | Chromico/bk-base | be822d9bbee544a958bed4831348185a75604791 | [
"MIT"
] | 40 | 2021-06-30T06:21:26.000Z | 2022-03-29T12:42:26.000Z | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
--------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from dataflow.flow.handlers.nodes.base_node.node_handler import NodeHandler
class SourceNode(NodeHandler):
"""
数据源节点的父类
"""
def update_node_metadata_relation(self, bk_biz_id, result_table_ids, heads=None, tails=None):
"""
更新节点与rt、processing等实体的关联关系
@param bk_biz_id:
@param result_table_ids:
@param heads: 只有计算节点有 heads,tails 参数
@param tails:
"""
self.node_info.update_as_source(bk_biz_id, result_table_ids[0])
| 44.47619 | 111 | 0.731799 |
from dataflow.flow.handlers.nodes.base_node.node_handler import NodeHandler
class SourceNode(NodeHandler):
def update_node_metadata_relation(self, bk_biz_id, result_table_ids, heads=None, tails=None):
self.node_info.update_as_source(bk_biz_id, result_table_ids[0])
| true | true |
f7f8aa0690977174d486c205bf4183d5ca541045 | 723 | py | Python | bnn_mcmc_examples/examples/mlp/noisy_xor/setting1/mcmc/hmc/benchmark_run.py | papamarkou/bnn_mcmc_examples | 7bb4ecfb33db4c30a8e61e31f528bda0efb24e3d | [
"MIT"
] | 1 | 2021-09-09T15:55:37.000Z | 2021-09-09T15:55:37.000Z | bnn_mcmc_examples/examples/mlp/noisy_xor/setting1/mcmc/hmc/benchmark_run.py | kushagragpt99/bnn_mcmc_examples | 297cdb1e74335860989bebdb4ff6f6322b6adc06 | [
"MIT"
] | null | null | null | bnn_mcmc_examples/examples/mlp/noisy_xor/setting1/mcmc/hmc/benchmark_run.py | kushagragpt99/bnn_mcmc_examples | 297cdb1e74335860989bebdb4ff6f6322b6adc06 | [
"MIT"
] | 1 | 2021-10-05T06:38:57.000Z | 2021-10-05T06:38:57.000Z | # %% Import packages
from bnn_mcmc_examples.examples.mlp.noisy_xor.setting1.mcmc.constants import (
num_chains, num_epochs, num_burnin_epochs, verbose, verbose_step
)
from bnn_mcmc_examples.examples.mlp.noisy_xor.setting1.mcmc.hmc.constants import sampler_output_path
from bnn_mcmc_examples.examples.mlp.noisy_xor.setting1.mcmc.hmc.sampler import sampler
# %% Benchmark HMC sampler
sampler.benchmark(
num_chains=num_chains,
num_epochs=num_epochs,
num_burnin_epochs=num_burnin_epochs,
path=sampler_output_path,
check_conditions=lambda chain, runtime : 0.35 <= chain.acceptance_rate() <= 0.95,
verbose=verbose,
verbose_step=verbose_step,
print_acceptance=True,
print_runtime=True
)
| 32.863636 | 100 | 0.789765 |
from bnn_mcmc_examples.examples.mlp.noisy_xor.setting1.mcmc.constants import (
num_chains, num_epochs, num_burnin_epochs, verbose, verbose_step
)
from bnn_mcmc_examples.examples.mlp.noisy_xor.setting1.mcmc.hmc.constants import sampler_output_path
from bnn_mcmc_examples.examples.mlp.noisy_xor.setting1.mcmc.hmc.sampler import sampler
sampler.benchmark(
num_chains=num_chains,
num_epochs=num_epochs,
num_burnin_epochs=num_burnin_epochs,
path=sampler_output_path,
check_conditions=lambda chain, runtime : 0.35 <= chain.acceptance_rate() <= 0.95,
verbose=verbose,
verbose_step=verbose_step,
print_acceptance=True,
print_runtime=True
)
| true | true |
f7f8aad8153f32829043537366778aa134928729 | 2,658 | py | Python | .leetcode/110.balanced-binary-tree.py | KuiyuanFu/PythonLeetCode | 8962df2fa838eb7ae48fa59de272ba55a89756d8 | [
"MIT"
] | null | null | null | .leetcode/110.balanced-binary-tree.py | KuiyuanFu/PythonLeetCode | 8962df2fa838eb7ae48fa59de272ba55a89756d8 | [
"MIT"
] | null | null | null | .leetcode/110.balanced-binary-tree.py | KuiyuanFu/PythonLeetCode | 8962df2fa838eb7ae48fa59de272ba55a89756d8 | [
"MIT"
] | null | null | null | # @lc app=leetcode id=110 lang=python3
#
# [110] Balanced Binary Tree
#
# https://leetcode.com/problems/balanced-binary-tree/description/
#
# algorithms
# Easy (44.89%)
# Likes: 3539
# Dislikes: 232
# Total Accepted: 571.5K
# Total Submissions: 1.3M
# Testcase Example: '[3,9,20,null,null,15,7]'
#
# Given a binary tree, determine if it is height-balanced.
#
# For this problem, a height-balanced binary tree is defined as:
#
#
# a binary tree in which the left and right subtrees of every node differ in
# height by no more than 1.
#
#
#
# Example 1:
#
#
# Input: root = [3,9,20,null,null,15,7]
# Output: true
#
#
# Example 2:
#
#
# Input: root = [1,2,2,3,3,null,null,4,4]
# Output: false
#
#
# Example 3:
#
#
# Input: root = []
# Output: true
#
#
#
# Constraints:
#
#
# The number of nodes in the tree is in the range [0, 5000].
# -10^4 <= Node.val <= 10^4
#
#
#
# @lc tags=tree;depth-first-search
# @lc imports=start
from imports import *
# @lc imports=end
# @lc idea=start
#
# 给定一棵二叉树,判断是否是高度平衡的。
# 后序遍历,判断深度。
#
# @lc idea=end
# @lc group=
# @lc rank=
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
# return isBalance and height
def recur(node: TreeNode) -> Tuple[bool, int]:
if not node:
return True, 0
fl, heightL = recur(node.left)
fr, heightR = recur(node.right)
if not (fl and fr) or abs(heightR - heightL) > 1:
return False, 0
return (True, max(heightR, heightL) + 1)
return recur(root)[0]
pass
# @lc code=end
# @lc main=start
if __name__ == '__main__':
print('Example 1:')
print('Input : ')
print('root = [3,9,20,null,null,15,7]')
print('Output :')
print(
str(Solution().isBalanced(listToTreeNode([3, 9, 20, None, None, 15,
7]))))
print('Exception :')
print('true')
print()
print('Example 2:')
print('Input : ')
print('root = [1,2,2,3,3,null,null,4,4]')
print('Output :')
print(
str(Solution().isBalanced(
listToTreeNode([1, 2, 2, 3, 3, None, None, 4, 4]))))
print('Exception :')
print('false')
print()
print('Example 3:')
print('Input : ')
print('root = []')
print('Output :')
print(str(Solution().isBalanced(listToTreeNode([]))))
print('Exception :')
print('true')
print()
pass
# @lc main=end | 19.688889 | 76 | 0.569977 |
from imports import *
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def recur(node: TreeNode) -> Tuple[bool, int]:
if not node:
return True, 0
fl, heightL = recur(node.left)
fr, heightR = recur(node.right)
if not (fl and fr) or abs(heightR - heightL) > 1:
return False, 0
return (True, max(heightR, heightL) + 1)
return recur(root)[0]
pass
if __name__ == '__main__':
print('Example 1:')
print('Input : ')
print('root = [3,9,20,null,null,15,7]')
print('Output :')
print(
str(Solution().isBalanced(listToTreeNode([3, 9, 20, None, None, 15,
7]))))
print('Exception :')
print('true')
print()
print('Example 2:')
print('Input : ')
print('root = [1,2,2,3,3,null,null,4,4]')
print('Output :')
print(
str(Solution().isBalanced(
listToTreeNode([1, 2, 2, 3, 3, None, None, 4, 4]))))
print('Exception :')
print('false')
print()
print('Example 3:')
print('Input : ')
print('root = []')
print('Output :')
print(str(Solution().isBalanced(listToTreeNode([]))))
print('Exception :')
print('true')
print()
pass
| true | true |
f7f8ac6ae10da5f1a2dfc69c0e6914a217010b74 | 9,344 | py | Python | gui.py | huxinkan517/video-subtitle-extractor | 3fcd9d3e1f5198a0343be24f25101cd3db65ccff | [
"Apache-2.0"
] | 1 | 2021-12-15T08:14:49.000Z | 2021-12-15T08:14:49.000Z | gui.py | huxinkan517/video-subtitle-extractor | 3fcd9d3e1f5198a0343be24f25101cd3db65ccff | [
"Apache-2.0"
] | null | null | null | gui.py | huxinkan517/video-subtitle-extractor | 3fcd9d3e1f5198a0343be24f25101cd3db65ccff | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
"""
@Author : Fang Yao
@Time : 2021/4/1 6:07 下午
@FileName: gui.py
@desc:
"""
import sys
import PySimpleGUI as sg
import cv2
import os
from threading import Thread
from backend.tools.settings import set_language_mode
from main import SubtitleExtractor
class SubtitleExtractorGUI:
def __init__(self):
# 获取窗口分辨率
self.screen_width, self.screen_height = sg.Window.get_screen_size()
# 设置视频预览区域大小
self.video_preview_height = self.screen_height // 2
self.video_preview_width = self.screen_width // 2
# 字幕提取器布局
self.layout = None
# 字幕提取其窗口
self.window = None
# 视频路径
self.video_path = None
# 视频cap
self.video_cap = None
# 视频的帧率
self.fps = None
# 视频的帧数
self.frame_count = None
# 视频的宽
self.frame_width = None
# 视频的高
self.frame_height = None
# 设置字幕区域高宽
self.xmin = None
self.xmax = None
self.ymin = None
self.ymax = None
def run(self):
# 创建布局
self._create_layout()
# 创建窗口
self.window = sg.Window(title='硬字幕提取器', layout=self.layout)
while True:
# 循环读取事件
event, values = self.window.read(timeout=10)
# 处理【打开】事件
self._file_event_handler(event, values)
# 处理【滑动】事件
self._slide_event_handler(event, values)
# 处理【识别语言】事件
self._language_mode_event_handler(event, values)
# 处理【运行】事件
self._run_event_handler(event, values)
# 如果关闭软件,退出
if event == sg.WIN_CLOSED:
break
def _create_layout(self):
"""
创建字幕提取器布局
"""
sg.theme('LightBrown12')
self.layout = [
# 显示视频预览
[sg.Image(size=(self.video_preview_width, self.video_preview_height), background_color='black',
key='-DISPLAY-')],
# 打开按钮 + 快进快退条
[sg.Input(key='-FILE-', visible=False, enable_events=True),
sg.FileBrowse('打开', file_types=(('所有文件', '*.*'), ('mp4文件', '*.mp4'),
('flv文件', '*.flv'), ('wmv文件', '*.wmv'), ('avi文件', '*.avi')),
key='-FILE_BTN-'),
sg.Slider(size=(80, 20), range=(1, 1), key='-SLIDER-', orientation='h',
enable_events=True,
disable_number_display=True),
],
# 输出区域
[sg.Output(size=(70, 10), font='Courier 10'),
sg.Frame(title='垂直方向', layout=[[
sg.Slider(range=(0, 0), orientation='v', size=(10, 20),
# disable_number_display=True,
enable_events=True,
default_value=0, key='-Y-SLIDER-'),
sg.Slider(range=(0, 0), orientation='v', size=(10, 20),
# disable_number_display=True,
enable_events=True,
default_value=0, key='-Y-SLIDER-H-'),
]], pad=((15, 5), (0, 0))),
sg.Frame(title='水平方向', layout=[[
sg.Slider(range=(0, 0), orientation='v', size=(10, 20),
# disable_number_display=True,
enable_events=True,
default_value=0, key='-X-SLIDER-'),
sg.Slider(range=(0, 0), orientation='v', size=(10, 20),
# disable_number_display=True,
enable_events=True,
default_value=0, key='-X-SLIDER-W-'),
]], pad=((15, 5), (0, 0)))
],
# 运行按钮 + 进度条
[sg.Button(button_text='运行', key='-RUN-', size=(20, 1)),
sg.Button(button_text='识别语言', key='-LANGUAGE-MODE-', size=(20, 1))
],
]
def _file_event_handler(self, event, values):
"""
当点击打开按钮时:
1)打开视频文件,将画布显示视频帧
2)获取视频信息,初始化进度条滑块范围
"""
if event == '-FILE-':
self.video_path = values['-FILE-']
if self.video_path != '':
self.video_cap = cv2.VideoCapture(self.video_path)
if self.video_cap is None:
return
if self.video_cap.isOpened():
ret, frame = self.video_cap.read()
if ret:
print(f'成功打开视频:{self.video_path}')
# 获取视频的帧数
self.frame_count = self.video_cap.get(cv2.CAP_PROP_FRAME_COUNT)
# 获取视频的高度
self.frame_height = self.video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
# 获取视频的宽度
self.frame_width = self.video_cap.get(cv2.CAP_PROP_FRAME_WIDTH)
# 获取视频的帧率
self.fps = self.video_cap.get(cv2.CAP_PROP_FPS)
# 调整视频帧大小,是播放器能够显示
resized_frame = cv2.resize(src=frame, dsize=(self.video_preview_width, self.video_preview_height))
# 显示视频帧
self.window['-DISPLAY-'].update(data=cv2.imencode('.png', resized_frame)[1].tobytes())
# 更新视频进度条滑块range
self.window['-SLIDER-'].update(range=(1, self.frame_count))
self.window['-SLIDER-'].update(1)
# 更新视频字幕位置滑块range
self.window['-Y-SLIDER-'].update(range=(0, self.frame_height), disabled=False)
self.window['-Y-SLIDER-H-'].update(range=(0, self.frame_height // 2), disabled=False)
self.window['-Y-SLIDER-'].update(self.frame_height * .85)
self.window['-Y-SLIDER-H-'].update(self.frame_height * .146)
self.window['-X-SLIDER-'].update(range=(0, self.frame_width), disabled=False)
self.window['-X-SLIDER-W-'].update(range=(0, self.frame_width), disabled=False)
self.window['-X-SLIDER-'].update(self.frame_width * .15)
self.window['-X-SLIDER-W-'].update(self.frame_width * .7)
def _language_mode_event_handler(self, event, values):
if event != '-LANGUAGE-MODE-':
return
if 'OK' == set_language_mode(os.path.join(os.path.dirname(__file__), 'settings.ini')):
# 如果是源码运行,则用python解释器 重启
python = sys.executable
os.execl(python, python, *sys.argv)
def _run_event_handler(self, event, values):
"""
当点击运行按钮时:
1) 禁止修改字幕滑块区域
2) 禁止再次点击【运行】和【打开】按钮
3) 设定字幕区域位置
"""
if event == '-RUN-':
if self.video_cap is None:
print('请先打开视频')
else:
# 1) 禁止修改字幕滑块区域
self.window['-Y-SLIDER-'].update(disabled=True)
self.window['-X-SLIDER-'].update(disabled=True)
self.window['-Y-SLIDER-H-'].update(disabled=True)
self.window['-X-SLIDER-W-'].update(disabled=True)
# 2) 禁止再次点击【运行】、【打开】和【识别语言】按钮
self.window['-RUN-'].update(disabled=True)
self.window['-FILE-'].update(disabled=True)
self.window['-FILE_BTN-'].update(disabled=True)
self.window['-LANGUAGE-MODE-'].update(disabled=True)
# 3) 设定字幕区域位置
self.xmin = int(values['-X-SLIDER-'])
self.xmax = int(values['-X-SLIDER-'] + values['-X-SLIDER-W-'])
self.ymin = int(values['-Y-SLIDER-'])
self.ymax = int(values['-Y-SLIDER-'] + values['-Y-SLIDER-H-'])
print(f'字幕区域:({self.ymin},{self.ymax},{self.xmin},{self.xmax})')
subtitle_area = (self.ymin, self.ymax, self.xmin, self.xmax)
se = SubtitleExtractor(self.video_path, subtitle_area)
Thread(target=se.run, daemon=True).start()
def _slide_event_handler(self, event, values):
"""
当滑动视频进度条/滑动字幕选择区域滑块时:
1) 判断视频是否存在,如果存在则显示对应的视频帧
2) 绘制rectangle
"""
if event == '-SLIDER-' or event == '-Y-SLIDER-' or event == '-Y-SLIDER-H-' or event == '-X-SLIDER-' or event == '-X-SLIDER-W-':
if self.video_cap is not None and self.video_cap.isOpened():
frame_no = int(values['-SLIDER-'])
self.video_cap.set(cv2.CAP_PROP_POS_FRAMES, frame_no)
ret, frame = self.video_cap.read()
if ret:
# 画字幕框
y = int(values['-Y-SLIDER-'])
h = int(values['-Y-SLIDER-H-'])
x = int(values['-X-SLIDER-'])
w = int(values['-X-SLIDER-W-'])
draw = cv2.rectangle(img=frame, pt1=(x, y), pt2=(x + w, y + h),
color=(0, 255, 0), thickness=3)
# 调整视频帧大小,使播放器能够显示
resized_frame = cv2.resize(src=draw, dsize=(self.video_preview_width, self.video_preview_height))
# 显示视频帧
self.window['-DISPLAY-'].update(data=cv2.imencode('.png', resized_frame)[1].tobytes())
if __name__ == '__main__':
# 运行图形化界面
subtitleExtractorGUI = SubtitleExtractorGUI()
subtitleExtractorGUI.run()
| 41.714286 | 135 | 0.502783 |
import sys
import PySimpleGUI as sg
import cv2
import os
from threading import Thread
from backend.tools.settings import set_language_mode
from main import SubtitleExtractor
class SubtitleExtractorGUI:
def __init__(self):
self.screen_width, self.screen_height = sg.Window.get_screen_size()
self.video_preview_height = self.screen_height // 2
self.video_preview_width = self.screen_width // 2
self.layout = None
self.window = None
self.video_path = None
self.video_cap = None
self.fps = None
self.frame_count = None
self.frame_width = None
self.frame_height = None
self.xmin = None
self.xmax = None
self.ymin = None
self.ymax = None
def run(self):
self._create_layout()
self.window = sg.Window(title='硬字幕提取器', layout=self.layout)
while True:
event, values = self.window.read(timeout=10)
self._file_event_handler(event, values)
self._slide_event_handler(event, values)
self._language_mode_event_handler(event, values)
self._run_event_handler(event, values)
if event == sg.WIN_CLOSED:
break
def _create_layout(self):
sg.theme('LightBrown12')
self.layout = [
[sg.Image(size=(self.video_preview_width, self.video_preview_height), background_color='black',
key='-DISPLAY-')],
[sg.Input(key='-FILE-', visible=False, enable_events=True),
sg.FileBrowse('打开', file_types=(('所有文件', '*.*'), ('mp4文件', '*.mp4'),
('flv文件', '*.flv'), ('wmv文件', '*.wmv'), ('avi文件', '*.avi')),
key='-FILE_BTN-'),
sg.Slider(size=(80, 20), range=(1, 1), key='-SLIDER-', orientation='h',
enable_events=True,
disable_number_display=True),
],
[sg.Output(size=(70, 10), font='Courier 10'),
sg.Frame(title='垂直方向', layout=[[
sg.Slider(range=(0, 0), orientation='v', size=(10, 20),
enable_events=True,
default_value=0, key='-Y-SLIDER-'),
sg.Slider(range=(0, 0), orientation='v', size=(10, 20),
enable_events=True,
default_value=0, key='-Y-SLIDER-H-'),
]], pad=((15, 5), (0, 0))),
sg.Frame(title='水平方向', layout=[[
sg.Slider(range=(0, 0), orientation='v', size=(10, 20),
enable_events=True,
default_value=0, key='-X-SLIDER-'),
sg.Slider(range=(0, 0), orientation='v', size=(10, 20),
enable_events=True,
default_value=0, key='-X-SLIDER-W-'),
]], pad=((15, 5), (0, 0)))
],
[sg.Button(button_text='运行', key='-RUN-', size=(20, 1)),
sg.Button(button_text='识别语言', key='-LANGUAGE-MODE-', size=(20, 1))
],
]
def _file_event_handler(self, event, values):
if event == '-FILE-':
self.video_path = values['-FILE-']
if self.video_path != '':
self.video_cap = cv2.VideoCapture(self.video_path)
if self.video_cap is None:
return
if self.video_cap.isOpened():
ret, frame = self.video_cap.read()
if ret:
print(f'成功打开视频:{self.video_path}')
self.frame_count = self.video_cap.get(cv2.CAP_PROP_FRAME_COUNT)
self.frame_height = self.video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
self.frame_width = self.video_cap.get(cv2.CAP_PROP_FRAME_WIDTH)
self.fps = self.video_cap.get(cv2.CAP_PROP_FPS)
resized_frame = cv2.resize(src=frame, dsize=(self.video_preview_width, self.video_preview_height))
self.window['-DISPLAY-'].update(data=cv2.imencode('.png', resized_frame)[1].tobytes())
self.window['-SLIDER-'].update(range=(1, self.frame_count))
self.window['-SLIDER-'].update(1)
self.window['-Y-SLIDER-'].update(range=(0, self.frame_height), disabled=False)
self.window['-Y-SLIDER-H-'].update(range=(0, self.frame_height // 2), disabled=False)
self.window['-Y-SLIDER-'].update(self.frame_height * .85)
self.window['-Y-SLIDER-H-'].update(self.frame_height * .146)
self.window['-X-SLIDER-'].update(range=(0, self.frame_width), disabled=False)
self.window['-X-SLIDER-W-'].update(range=(0, self.frame_width), disabled=False)
self.window['-X-SLIDER-'].update(self.frame_width * .15)
self.window['-X-SLIDER-W-'].update(self.frame_width * .7)
def _language_mode_event_handler(self, event, values):
if event != '-LANGUAGE-MODE-':
return
if 'OK' == set_language_mode(os.path.join(os.path.dirname(__file__), 'settings.ini')):
python = sys.executable
os.execl(python, python, *sys.argv)
def _run_event_handler(self, event, values):
if event == '-RUN-':
if self.video_cap is None:
print('请先打开视频')
else:
self.window['-Y-SLIDER-'].update(disabled=True)
self.window['-X-SLIDER-'].update(disabled=True)
self.window['-Y-SLIDER-H-'].update(disabled=True)
self.window['-X-SLIDER-W-'].update(disabled=True)
self.window['-RUN-'].update(disabled=True)
self.window['-FILE-'].update(disabled=True)
self.window['-FILE_BTN-'].update(disabled=True)
self.window['-LANGUAGE-MODE-'].update(disabled=True)
self.xmin = int(values['-X-SLIDER-'])
self.xmax = int(values['-X-SLIDER-'] + values['-X-SLIDER-W-'])
self.ymin = int(values['-Y-SLIDER-'])
self.ymax = int(values['-Y-SLIDER-'] + values['-Y-SLIDER-H-'])
print(f'字幕区域:({self.ymin},{self.ymax},{self.xmin},{self.xmax})')
subtitle_area = (self.ymin, self.ymax, self.xmin, self.xmax)
se = SubtitleExtractor(self.video_path, subtitle_area)
Thread(target=se.run, daemon=True).start()
def _slide_event_handler(self, event, values):
if event == '-SLIDER-' or event == '-Y-SLIDER-' or event == '-Y-SLIDER-H-' or event == '-X-SLIDER-' or event == '-X-SLIDER-W-':
if self.video_cap is not None and self.video_cap.isOpened():
frame_no = int(values['-SLIDER-'])
self.video_cap.set(cv2.CAP_PROP_POS_FRAMES, frame_no)
ret, frame = self.video_cap.read()
if ret:
y = int(values['-Y-SLIDER-'])
h = int(values['-Y-SLIDER-H-'])
x = int(values['-X-SLIDER-'])
w = int(values['-X-SLIDER-W-'])
draw = cv2.rectangle(img=frame, pt1=(x, y), pt2=(x + w, y + h),
color=(0, 255, 0), thickness=3)
resized_frame = cv2.resize(src=draw, dsize=(self.video_preview_width, self.video_preview_height))
self.window['-DISPLAY-'].update(data=cv2.imencode('.png', resized_frame)[1].tobytes())
if __name__ == '__main__':
subtitleExtractorGUI = SubtitleExtractorGUI()
subtitleExtractorGUI.run()
| true | true |
f7f8ad698b4c8adfaeb8585e6f4f2379b2e28fce | 1,363 | py | Python | tests/benchmarks/constructs/RichComparisonStrings.py | RESP3CT88/Nuitka | 0fcc25d9f00c4fc78c79a863c4b7987f573962e1 | [
"Apache-2.0"
] | 5,421 | 2018-09-24T08:04:06.000Z | 2022-03-31T20:02:37.000Z | tests/benchmarks/constructs/RichComparisonStrings.py | ztessler/Nuitka | 04c9a5471b702a0e5f28398f2661c93b83ab0d1a | [
"Apache-2.0"
] | 1,348 | 2018-09-22T13:41:00.000Z | 2022-03-31T22:33:40.000Z | tests/benchmarks/constructs/RichComparisonStrings.py | ztessler/Nuitka | 04c9a5471b702a0e5f28398f2661c93b83ab0d1a | [
"Apache-2.0"
] | 396 | 2018-09-28T15:37:03.000Z | 2022-03-29T10:52:09.000Z | # Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Python test originally created or extracted from other peoples work. The
# parts from me are licensed as below. It is at least Free Software where
# it's copied from other people. In these cases, that will normally be
# indicated.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module_value1 = "1000"
module_value2 = "2000"
import sys
loop_count = 50000 if len(sys.argv) < 2 else int(sys.argv[1])
def calledRepeatedly(value1, value2):
# Force frame and eliminate forward propagation (currently).
module_value1
# construct_begin
if value1 == value2:
return
# construct_end
return value1, value2
import itertools
for x in itertools.repeat(None, 50000):
calledRepeatedly(module_value1, module_value2)
print("OK.")
| 31.697674 | 78 | 0.718269 |
# indicated.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module_value1 = "1000"
module_value2 = "2000"
import sys
loop_count = 50000 if len(sys.argv) < 2 else int(sys.argv[1])
def calledRepeatedly(value1, value2):
# Force frame and eliminate forward propagation (currently).
module_value1
# construct_begin
if value1 == value2:
return
# construct_end
return value1, value2
import itertools
for x in itertools.repeat(None, 50000):
calledRepeatedly(module_value1, module_value2)
print("OK.")
| true | true |
f7f8ae2a57aa94fc1312d1681af759d69cfd2fd7 | 968 | py | Python | isi_sdk_8_0_1/test/test_network_groupnet_extended.py | mohitjain97/isilon_sdk_python | a371f438f542568edb8cda35e929e6b300b1177c | [
"Unlicense"
] | 24 | 2018-06-22T14:13:23.000Z | 2022-03-23T01:21:26.000Z | isi_sdk_8_0_1/test/test_network_groupnet_extended.py | mohitjain97/isilon_sdk_python | a371f438f542568edb8cda35e929e6b300b1177c | [
"Unlicense"
] | 46 | 2018-04-30T13:28:22.000Z | 2022-03-21T21:11:07.000Z | isi_sdk_8_0_1/test/test_network_groupnet_extended.py | mohitjain97/isilon_sdk_python | a371f438f542568edb8cda35e929e6b300b1177c | [
"Unlicense"
] | 29 | 2018-06-19T00:14:04.000Z | 2022-02-08T17:51:19.000Z | # coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 4
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import isi_sdk_8_0_1
from isi_sdk_8_0_1.models.network_groupnet_extended import NetworkGroupnetExtended # noqa: E501
from isi_sdk_8_0_1.rest import ApiException
class TestNetworkGroupnetExtended(unittest.TestCase):
"""NetworkGroupnetExtended unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testNetworkGroupnetExtended(self):
"""Test NetworkGroupnetExtended"""
# FIXME: construct object with mandatory attributes with example values
# model = isi_sdk_8_0_1.models.network_groupnet_extended.NetworkGroupnetExtended() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
| 23.609756 | 104 | 0.725207 |
from __future__ import absolute_import
import unittest
import isi_sdk_8_0_1
from isi_sdk_8_0_1.models.network_groupnet_extended import NetworkGroupnetExtended
from isi_sdk_8_0_1.rest import ApiException
class TestNetworkGroupnetExtended(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testNetworkGroupnetExtended(self):
s
if __name__ == '__main__':
unittest.main()
| true | true |
f7f8aea11007006a9ce355c1421574e7faad75a0 | 15,035 | py | Python | sdk/python/pulumi_azure_native/network/v20171101/network_watcher.py | sebtelko/pulumi-azure-native | 711ec021b5c73da05611c56c8a35adb0ce3244e4 | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_native/network/v20171101/network_watcher.py | sebtelko/pulumi-azure-native | 711ec021b5c73da05611c56c8a35adb0ce3244e4 | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_native/network/v20171101/network_watcher.py | sebtelko/pulumi-azure-native | 711ec021b5c73da05611c56c8a35adb0ce3244e4 | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
__all__ = ['NetworkWatcherArgs', 'NetworkWatcher']
@pulumi.input_type
class NetworkWatcherArgs:
def __init__(__self__, *,
resource_group_name: pulumi.Input[str],
etag: Optional[pulumi.Input[str]] = None,
id: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
network_watcher_name: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None):
"""
The set of arguments for constructing a NetworkWatcher resource.
:param pulumi.Input[str] resource_group_name: The name of the resource group.
:param pulumi.Input[str] etag: A unique read-only string that changes whenever the resource is updated.
:param pulumi.Input[str] id: Resource ID.
:param pulumi.Input[str] location: Resource location.
:param pulumi.Input[str] network_watcher_name: The name of the network watcher.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags.
"""
pulumi.set(__self__, "resource_group_name", resource_group_name)
if etag is not None:
pulumi.set(__self__, "etag", etag)
if id is not None:
pulumi.set(__self__, "id", id)
if location is not None:
pulumi.set(__self__, "location", location)
if network_watcher_name is not None:
pulumi.set(__self__, "network_watcher_name", network_watcher_name)
if tags is not None:
pulumi.set(__self__, "tags", tags)
@property
@pulumi.getter(name="resourceGroupName")
def resource_group_name(self) -> pulumi.Input[str]:
"""
The name of the resource group.
"""
return pulumi.get(self, "resource_group_name")
@resource_group_name.setter
def resource_group_name(self, value: pulumi.Input[str]):
pulumi.set(self, "resource_group_name", value)
@property
@pulumi.getter
def etag(self) -> Optional[pulumi.Input[str]]:
"""
A unique read-only string that changes whenever the resource is updated.
"""
return pulumi.get(self, "etag")
@etag.setter
def etag(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "etag", value)
@property
@pulumi.getter
def id(self) -> Optional[pulumi.Input[str]]:
"""
Resource ID.
"""
return pulumi.get(self, "id")
@id.setter
def id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "id", value)
@property
@pulumi.getter
def location(self) -> Optional[pulumi.Input[str]]:
"""
Resource location.
"""
return pulumi.get(self, "location")
@location.setter
def location(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "location", value)
@property
@pulumi.getter(name="networkWatcherName")
def network_watcher_name(self) -> Optional[pulumi.Input[str]]:
"""
The name of the network watcher.
"""
return pulumi.get(self, "network_watcher_name")
@network_watcher_name.setter
def network_watcher_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "network_watcher_name", value)
@property
@pulumi.getter
def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
"""
Resource tags.
"""
return pulumi.get(self, "tags")
@tags.setter
def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "tags", value)
class NetworkWatcher(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
etag: Optional[pulumi.Input[str]] = None,
id: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
network_watcher_name: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
__props__=None):
"""
Network watcher in a resource group.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] etag: A unique read-only string that changes whenever the resource is updated.
:param pulumi.Input[str] id: Resource ID.
:param pulumi.Input[str] location: Resource location.
:param pulumi.Input[str] network_watcher_name: The name of the network watcher.
:param pulumi.Input[str] resource_group_name: The name of the resource group.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: NetworkWatcherArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
Network watcher in a resource group.
:param str resource_name: The name of the resource.
:param NetworkWatcherArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(NetworkWatcherArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
etag: Optional[pulumi.Input[str]] = None,
id: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
network_watcher_name: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = NetworkWatcherArgs.__new__(NetworkWatcherArgs)
__props__.__dict__["etag"] = etag
__props__.__dict__["id"] = id
__props__.__dict__["location"] = location
__props__.__dict__["network_watcher_name"] = network_watcher_name
if resource_group_name is None and not opts.urn:
raise TypeError("Missing required property 'resource_group_name'")
__props__.__dict__["resource_group_name"] = resource_group_name
__props__.__dict__["tags"] = tags
__props__.__dict__["name"] = None
__props__.__dict__["provisioning_state"] = None
__props__.__dict__["type"] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:network/v20171101:NetworkWatcher"), pulumi.Alias(type_="azure-native:network:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20160901:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20160901:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20161201:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20161201:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20170301:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20170301:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20170601:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20170601:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20170801:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20170801:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20170901:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20170901:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20171001:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20171001:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20180101:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20180101:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20180201:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20180201:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20180401:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20180401:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20180601:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20180601:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20180701:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20180701:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20180801:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20180801:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20181001:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20181001:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20181101:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20181101:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20181201:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20181201:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20190201:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20190201:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20190401:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20190401:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20190601:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20190601:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20190701:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20190701:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20190801:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20190801:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20190901:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20190901:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20191101:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20191101:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20191201:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20191201:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20200301:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20200301:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20200401:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20200401:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20200501:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20200501:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20200601:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20200601:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20200701:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20200701:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20200801:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20200801:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20201101:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20201101:NetworkWatcher")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(NetworkWatcher, __self__).__init__(
'azure-native:network/v20171101:NetworkWatcher',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'NetworkWatcher':
"""
Get an existing NetworkWatcher resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = NetworkWatcherArgs.__new__(NetworkWatcherArgs)
__props__.__dict__["etag"] = None
__props__.__dict__["location"] = None
__props__.__dict__["name"] = None
__props__.__dict__["provisioning_state"] = None
__props__.__dict__["tags"] = None
__props__.__dict__["type"] = None
return NetworkWatcher(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def etag(self) -> pulumi.Output[Optional[str]]:
"""
A unique read-only string that changes whenever the resource is updated.
"""
return pulumi.get(self, "etag")
@property
@pulumi.getter
def location(self) -> pulumi.Output[str]:
"""
Resource location.
"""
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
Resource name.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> pulumi.Output[str]:
"""
The provisioning state of the resource.
"""
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter
def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]:
"""
Resource tags.
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
"""
Resource type.
"""
return pulumi.get(self, "type")
| 55.07326 | 4,551 | 0.684071 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
__all__ = ['NetworkWatcherArgs', 'NetworkWatcher']
@pulumi.input_type
class NetworkWatcherArgs:
def __init__(__self__, *,
resource_group_name: pulumi.Input[str],
etag: Optional[pulumi.Input[str]] = None,
id: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
network_watcher_name: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None):
pulumi.set(__self__, "resource_group_name", resource_group_name)
if etag is not None:
pulumi.set(__self__, "etag", etag)
if id is not None:
pulumi.set(__self__, "id", id)
if location is not None:
pulumi.set(__self__, "location", location)
if network_watcher_name is not None:
pulumi.set(__self__, "network_watcher_name", network_watcher_name)
if tags is not None:
pulumi.set(__self__, "tags", tags)
@property
@pulumi.getter(name="resourceGroupName")
def resource_group_name(self) -> pulumi.Input[str]:
return pulumi.get(self, "resource_group_name")
@resource_group_name.setter
def resource_group_name(self, value: pulumi.Input[str]):
pulumi.set(self, "resource_group_name", value)
@property
@pulumi.getter
def etag(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "etag")
@etag.setter
def etag(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "etag", value)
@property
@pulumi.getter
def id(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "id")
@id.setter
def id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "id", value)
@property
@pulumi.getter
def location(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "location")
@location.setter
def location(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "location", value)
@property
@pulumi.getter(name="networkWatcherName")
def network_watcher_name(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "network_watcher_name")
@network_watcher_name.setter
def network_watcher_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "network_watcher_name", value)
@property
@pulumi.getter
def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
return pulumi.get(self, "tags")
@tags.setter
def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "tags", value)
class NetworkWatcher(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
etag: Optional[pulumi.Input[str]] = None,
id: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
network_watcher_name: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
__props__=None):
...
@overload
def __init__(__self__,
resource_name: str,
args: NetworkWatcherArgs,
opts: Optional[pulumi.ResourceOptions] = None):
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(NetworkWatcherArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
etag: Optional[pulumi.Input[str]] = None,
id: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
network_watcher_name: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = NetworkWatcherArgs.__new__(NetworkWatcherArgs)
__props__.__dict__["etag"] = etag
__props__.__dict__["id"] = id
__props__.__dict__["location"] = location
__props__.__dict__["network_watcher_name"] = network_watcher_name
if resource_group_name is None and not opts.urn:
raise TypeError("Missing required property 'resource_group_name'")
__props__.__dict__["resource_group_name"] = resource_group_name
__props__.__dict__["tags"] = tags
__props__.__dict__["name"] = None
__props__.__dict__["provisioning_state"] = None
__props__.__dict__["type"] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:network/v20171101:NetworkWatcher"), pulumi.Alias(type_="azure-native:network:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20160901:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20160901:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20161201:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20161201:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20170301:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20170301:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20170601:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20170601:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20170801:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20170801:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20170901:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20170901:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20171001:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20171001:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20180101:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20180101:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20180201:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20180201:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20180401:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20180401:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20180601:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20180601:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20180701:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20180701:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20180801:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20180801:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20181001:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20181001:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20181101:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20181101:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20181201:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20181201:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20190201:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20190201:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20190401:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20190401:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20190601:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20190601:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20190701:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20190701:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20190801:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20190801:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20190901:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20190901:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20191101:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20191101:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20191201:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20191201:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20200301:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20200301:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20200401:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20200401:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20200501:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20200501:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20200601:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20200601:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20200701:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20200701:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20200801:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20200801:NetworkWatcher"), pulumi.Alias(type_="azure-native:network/v20201101:NetworkWatcher"), pulumi.Alias(type_="azure-nextgen:network/v20201101:NetworkWatcher")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(NetworkWatcher, __self__).__init__(
'azure-native:network/v20171101:NetworkWatcher',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'NetworkWatcher':
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = NetworkWatcherArgs.__new__(NetworkWatcherArgs)
__props__.__dict__["etag"] = None
__props__.__dict__["location"] = None
__props__.__dict__["name"] = None
__props__.__dict__["provisioning_state"] = None
__props__.__dict__["tags"] = None
__props__.__dict__["type"] = None
return NetworkWatcher(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def etag(self) -> pulumi.Output[Optional[str]]:
return pulumi.get(self, "etag")
@property
@pulumi.getter
def location(self) -> pulumi.Output[str]:
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
return pulumi.get(self, "name")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> pulumi.Output[str]:
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter
def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]:
return pulumi.get(self, "tags")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
return pulumi.get(self, "type")
| true | true |
f7f8b138f669f1edbe1b56d33d66b4880b7b7e35 | 16,783 | py | Python | python/iceberg/api/types/type_util.py | moulimukherjee/incubator-iceberg | bf7edc4b325df6dd80d86fea0149d2be0ad09468 | [
"Apache-2.0"
] | 58 | 2019-09-10T20:51:26.000Z | 2022-03-22T11:06:09.000Z | python/iceberg/api/types/type_util.py | moulimukherjee/incubator-iceberg | bf7edc4b325df6dd80d86fea0149d2be0ad09468 | [
"Apache-2.0"
] | 292 | 2019-07-23T04:33:18.000Z | 2021-07-26T04:28:22.000Z | python/iceberg/api/types/type_util.py | moulimukherjee/incubator-iceberg | bf7edc4b325df6dd80d86fea0149d2be0ad09468 | [
"Apache-2.0"
] | 26 | 2019-08-28T23:59:03.000Z | 2022-03-04T08:54:08.000Z | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import math
from typing import List
from .type import (Type,
TypeID)
from .types import (ListType,
MapType,
NestedField,
StructType)
MAX_PRECISION = list()
REQUIRED_LENGTH = [-1 for item in range(40)]
MAX_PRECISION.append(0)
for i in range(1, 24):
MAX_PRECISION.append(int(math.floor(math.log10(math.pow(2, 8 * i - 1) - 1))))
for i in range(len(REQUIRED_LENGTH)):
for j in range(len(MAX_PRECISION)):
if i <= MAX_PRECISION[j]:
REQUIRED_LENGTH[i] = j
break
if REQUIRED_LENGTH[i] < 0:
raise RuntimeError("Could not find required length for precision %s" % i)
def select(schema, field_ids):
import iceberg.api.schema
if schema is None:
raise RuntimeError("Schema cannot be None")
if field_ids is None:
raise RuntimeError("Field ids cannot be None")
result = visit(schema, PruneColumns(field_ids))
if schema.as_struct() == result:
return schema
elif result is not None:
if schema.get_aliases() is not None:
return iceberg.api.schema.Schema(result.as_nested_type().fields, schema.get_aliases())
else:
return iceberg.api.schema.Schema(result.as_nested_type().fields)
return iceberg.api.schema.Schema(list(), schema.get_aliases())
def get_projected_ids(schema):
import iceberg.api.schema
if isinstance(schema, iceberg.api.schema.Schema):
return visit(schema, GetProjectedIds())
elif isinstance(schema, Type):
if schema.is_primitive_type():
return set()
return set(visit(schema, GetProjectedIds))
else:
raise RuntimeError("Argument %s must be Schema or a Type" % schema)
def select_not(schema, field_ids):
projected_ids = get_projected_ids(schema)
projected_ids.difference(field_ids)
return select(schema, projected_ids)
def join(left, right):
import iceberg.api.schema
return iceberg.api.schema.Schema(left + right)
def index_by_name(struct):
return visit(struct, IndexByName())
def index_by_id(struct):
return visit(struct, IndexById())
def assign_fresh_ids(type_var, next_id):
from ..schema import Schema
if isinstance(type_var, Type):
return visit(type_var, AssignFreshIds(next_id))
elif isinstance(type_var, Schema):
schema = type_var
return Schema(list(visit(schema.as_struct(), AssignFreshIds(next_id))
.as_nested_type().fields))
def visit(arg, visitor): # noqa: ignore=C901
from ..schema import Schema
if isinstance(visitor, CustomOrderSchemaVisitor):
return visit_custom_order(arg, visitor)
elif isinstance(arg, Schema):
return visitor.schema(arg, visit(arg.as_struct(), visitor))
elif isinstance(arg, Type):
type_var = arg
if type_var.type_id == TypeID.STRUCT:
struct = type_var.as_nested_type().as_struct_type()
results = list()
for field in struct.fields:
visitor.field_ids.append(field.field_id)
visitor.field_names.append(field.name)
result = None
try:
result = visit(field.type, visitor)
except RuntimeError:
pass
finally:
visitor.field_ids.pop()
visitor.field_names.pop()
results.append(visitor.field(field, result))
return visitor.struct(struct, results)
elif type_var.type_id == TypeID.LIST:
list_var = type_var.as_nested_type().as_list_type()
visitor.field_ids.append(list_var.element_id)
try:
element_result = visit(list_var.element_type, visitor)
except RuntimeError:
pass
finally:
visitor.field_ids.pop()
return visitor.list(list_var, element_result)
elif type_var.type_id == TypeID.MAP:
raise NotImplementedError()
else:
return visitor.primitive(arg.as_primitive_type())
else:
raise RuntimeError("Invalid type for arg: %s" % arg)
def visit_custom_order(arg, visitor):
from ..schema import Schema
if isinstance(arg, Schema):
schema = arg
return visitor.schema(arg, VisitFuture(schema.as_struct(), visitor))
elif isinstance(arg, Type):
type_var = arg
if type_var.type_id == TypeID.STRUCT:
struct = type_var.as_nested_type().as_struct_type()
results = list()
fields = struct.fields
for field in fields:
results.append(VisitFieldFuture(field, visitor))
struct = visitor.struct(struct, [x.get() for x in results])
return struct
elif type_var.type_id == TypeID.LIST:
list_var = type_var.as_nested_type().as_list_type()
return visitor.list(list_var, VisitFuture(list_var.element_type, visitor))
elif type_var.type_id == TypeID.MAP:
raise NotImplementedError()
return visitor.primitive(type_var.as_primitive_type())
class SchemaVisitor(object):
def __init__(self):
self.field_names = list()
self.field_ids = list()
def schema(self, schema, struct_result):
return None
def struct(self, struct, field_results):
return None
def field(self, field, field_result):
return None
def list(self, list_var, element_result):
return None
def map(self, map_var, key_result, value_result):
return None
def primitive(self, primitive_var):
return None
class CustomOrderSchemaVisitor(object):
def __init__(self):
super(CustomOrderSchemaVisitor, self).__init__()
def schema(self, schema, struct_result):
return None
def struct(self, struct, field_results):
return None
def field(self, field, field_result):
return None
def list(self, list_var, element_result):
return None
def map(self, map_var, key_result, value_result):
return None
def primitive(self, primitive_var):
return None
class VisitFuture(object):
def __init__(self, type, visitor):
self.type = type
self.visitor = visitor
def get(self):
return visit(self.type, self.visitor)
class VisitFieldFuture(object):
def __init__(self, field, visitor):
self.field = field
self.visitor = visitor
def get(self):
return self.visitor.field(self.field, VisitFuture(self.field.type, self.visitor).get)
def decimal_required_bytes(precision):
if precision < 0 or precision > 40:
raise RuntimeError("Unsupported decimal precision: %s" % precision)
return REQUIRED_LENGTH[precision]
class GetProjectedIds(SchemaVisitor):
def __init__(self):
super(GetProjectedIds, self).__init__()
self.field_ids = list()
def schema(self, schema, struct_result):
return self.field_ids
def struct(self, struct, field_results):
return self.field_ids
def field(self, field, field_result):
if field_result is None:
self.field_ids.append(field.field_id)
return self.field_ids
def list(self, list_var, element_result):
if element_result is None:
for field in list_var.fields():
self.field_ids.append(field.field_id)
return self.field_ids
def map(self, map_var, key_result, value_result):
if value_result is None:
for field in map_var.fields():
self.field_ids.append(field.field_id)
return self.field_ids
class PruneColumns(SchemaVisitor):
def __init__(self, selected):
super(PruneColumns, self).__init__()
self.selected = list(selected)
def schema(self, schema, struct_result):
return struct_result
def struct(self, struct, field_results):
fields = struct.fields
selected_fields = list()
same_types = True
for i, projected_type in enumerate(field_results):
field = fields[i]
if projected_type is not None:
if field.type == projected_type:
selected_fields.append(field)
elif projected_type is not None:
same_types = False
if field.is_optional:
selected_fields.append(NestedField.optional(field.field_id,
field.name,
projected_type))
else:
selected_fields.append(NestedField.required(field.field_id,
field.name,
projected_type))
if len(selected_fields) != 0:
if len(selected_fields) == len(fields) and same_types:
return struct
else:
return StructType.of(selected_fields)
def field(self, field, field_result):
if field.field_id in self.selected:
return field.type
elif field_result is not None:
return field_result
def primitive(self, primitive_var):
return None
class IndexByName(SchemaVisitor):
DOT = "."
def __init__(self):
super(IndexByName, self).__init__()
self.name_to_id = dict()
def schema(self, schema, struct_result):
return self.name_to_id
def struct(self, struct, field_results):
return self.name_to_id
def field(self, field, field_result):
self.add_field(field.name, field.field_id)
def list(self, list_var, element_result):
for field in list_var.fields():
self.add_field(field.name, field.field_id)
def map(self, map_var, key_result, value_result):
for field in map_var.fields():
self.add_field(field.name, field.field_id)
def add_field(self, name, field_id):
full_name = name
if not self.field_names and len(self.field_names) > 0:
full_name = IndexByName.DOT.join([IndexByName.DOT.join(reversed(self.field_names)), name])
self.name_to_id[full_name] = field_id
class IndexById(SchemaVisitor):
def __init__(self):
super(IndexById, self).__init__()
self.index = dict()
def schema(self, schema, struct_result):
return self.index
def struct(self, struct, field_results):
return self.index
def field(self, field, field_result):
self.index[field.field_id] = field
def list(self, list_var, element_result):
for field in list_var.fields():
self.index[field.field_id] = field
def map(self, map_var, key_result, value_result):
for field in map_var.fields:
self.index[field.field_id] = field
class NextID(object):
def __init__(self):
raise NotImplementedError()
def get(self):
raise NotImplementedError()
class AssignFreshIds(CustomOrderSchemaVisitor):
def __init__(self, next_id):
super(AssignFreshIds, self).__init__()
self.next_id = next_id
def schema(self, schema, struct_result):
return self.next_id()
def struct(self, struct, field_results):
fields = struct.fields
length = len(struct.fields)
new_ids = list()
for _ in range(length):
new_ids.append(self.next_id())
new_fields = list()
types = iter(field_results)
for i in range(length):
field = fields[i]
type = next(types)
if field.is_optional:
new_fields.append(NestedField.optional(new_ids[i], field.name, type))
else:
new_fields.append(NestedField.required(new_ids[i], field.name, type))
return StructType.of(new_fields)
def field(self, field, field_result):
return field_result()
def list(self, list_var, element_result):
new_id = self.next_id()
if list_var.is_element_optional():
return ListType.of_optional(new_id, element_result.get())
else:
return ListType.of_required(new_id, element_result.get())
def map(self, map_var, key_result, value_result):
new_key_id = self.next_id()
new_value_id = self.next_id()
if map_var.is_value_optional():
return MapType.of_optional(new_key_id, new_value_id, key_result(), value_result())
else:
return MapType.of_required(new_key_id, new_value_id, key_result(), value_result())
def primitive(self, primitive_var):
return primitive_var
class CheckCompatibility(CustomOrderSchemaVisitor):
@staticmethod
def write_compatibility_errors(read_schema, write_schema):
visit(read_schema, CheckCompatibility(write_schema, True))
@staticmethod
def read_compatibility_errors(read_schema, write_schema):
visit(write_schema, CheckCompatibility(read_schema, False))
NO_ERRORS: List[str] = []
def __init__(self, schema, check_ordering):
self.schema = schema
self.check_ordering = check_ordering
self.current_type = None
def schema(self, schema, struct_result):
self.current_type = self.schema.as_struct()
try:
struct_result.get()
finally:
self.current_type = None
def struct(self, struct, field_results):
if struct is None:
raise RuntimeError("Evaluation must start with a schema.")
if not self.current_type.is_struct_type():
return [": %s cannot be read as a struct" % self.current_type]
errors = []
for field_errors in field_results:
errors = errors + field_errors
if self.check_ordering:
new_struct = self.current_type.as_struct_type()
id_to_ord = {}
for i, val in enumerate(new_struct.fields):
id_to_ord[val.field_id] = i
last_ordinal = -1
for read_field in self.struct.fields:
id_var = read_field.field_id
field = struct.field(id=id_var)
if field is not None:
ordinal = id_to_ord[id]
if last_ordinal >= ordinal:
errors.append("%s is out of order before %s" % (read_field.name,
new_struct.fields[last_ordinal].name))
last_ordinal = ordinal
return errors
def field(self, field, field_result) -> List[str]:
struct = self.current_type.as_struct_type()
curr_field = struct.field(field.field_id)
errors = []
if curr_field is None:
if not field.is_optional:
errors.append("{} is required, but is missing".format(field.name))
return self.NO_ERRORS
self.current_type = curr_field.type
try:
if not field.is_optional and curr_field.is_optional:
errors.append(field.name + " should be required, but is optional")
for error in field_result:
if error.startswith(":"):
errors.append("{}{}".format(field.field_name, error))
else:
errors.append("{}.{}".format(field.field_name, error))
return errors
except RuntimeError:
pass
finally:
self.current_type = struct
return errors
def list(self, list_var, element_result):
raise NotImplementedError()
def map(self, map_var, key_result, value_result):
raise NotImplementedError()
def primitive(self, primitive_var):
raise NotImplementedError()
| 31.195167 | 110 | 0.618423 |
import math
from typing import List
from .type import (Type,
TypeID)
from .types import (ListType,
MapType,
NestedField,
StructType)
MAX_PRECISION = list()
REQUIRED_LENGTH = [-1 for item in range(40)]
MAX_PRECISION.append(0)
for i in range(1, 24):
MAX_PRECISION.append(int(math.floor(math.log10(math.pow(2, 8 * i - 1) - 1))))
for i in range(len(REQUIRED_LENGTH)):
for j in range(len(MAX_PRECISION)):
if i <= MAX_PRECISION[j]:
REQUIRED_LENGTH[i] = j
break
if REQUIRED_LENGTH[i] < 0:
raise RuntimeError("Could not find required length for precision %s" % i)
def select(schema, field_ids):
import iceberg.api.schema
if schema is None:
raise RuntimeError("Schema cannot be None")
if field_ids is None:
raise RuntimeError("Field ids cannot be None")
result = visit(schema, PruneColumns(field_ids))
if schema.as_struct() == result:
return schema
elif result is not None:
if schema.get_aliases() is not None:
return iceberg.api.schema.Schema(result.as_nested_type().fields, schema.get_aliases())
else:
return iceberg.api.schema.Schema(result.as_nested_type().fields)
return iceberg.api.schema.Schema(list(), schema.get_aliases())
def get_projected_ids(schema):
import iceberg.api.schema
if isinstance(schema, iceberg.api.schema.Schema):
return visit(schema, GetProjectedIds())
elif isinstance(schema, Type):
if schema.is_primitive_type():
return set()
return set(visit(schema, GetProjectedIds))
else:
raise RuntimeError("Argument %s must be Schema or a Type" % schema)
def select_not(schema, field_ids):
projected_ids = get_projected_ids(schema)
projected_ids.difference(field_ids)
return select(schema, projected_ids)
def join(left, right):
import iceberg.api.schema
return iceberg.api.schema.Schema(left + right)
def index_by_name(struct):
return visit(struct, IndexByName())
def index_by_id(struct):
return visit(struct, IndexById())
def assign_fresh_ids(type_var, next_id):
from ..schema import Schema
if isinstance(type_var, Type):
return visit(type_var, AssignFreshIds(next_id))
elif isinstance(type_var, Schema):
schema = type_var
return Schema(list(visit(schema.as_struct(), AssignFreshIds(next_id))
.as_nested_type().fields))
def visit(arg, visitor):
from ..schema import Schema
if isinstance(visitor, CustomOrderSchemaVisitor):
return visit_custom_order(arg, visitor)
elif isinstance(arg, Schema):
return visitor.schema(arg, visit(arg.as_struct(), visitor))
elif isinstance(arg, Type):
type_var = arg
if type_var.type_id == TypeID.STRUCT:
struct = type_var.as_nested_type().as_struct_type()
results = list()
for field in struct.fields:
visitor.field_ids.append(field.field_id)
visitor.field_names.append(field.name)
result = None
try:
result = visit(field.type, visitor)
except RuntimeError:
pass
finally:
visitor.field_ids.pop()
visitor.field_names.pop()
results.append(visitor.field(field, result))
return visitor.struct(struct, results)
elif type_var.type_id == TypeID.LIST:
list_var = type_var.as_nested_type().as_list_type()
visitor.field_ids.append(list_var.element_id)
try:
element_result = visit(list_var.element_type, visitor)
except RuntimeError:
pass
finally:
visitor.field_ids.pop()
return visitor.list(list_var, element_result)
elif type_var.type_id == TypeID.MAP:
raise NotImplementedError()
else:
return visitor.primitive(arg.as_primitive_type())
else:
raise RuntimeError("Invalid type for arg: %s" % arg)
def visit_custom_order(arg, visitor):
from ..schema import Schema
if isinstance(arg, Schema):
schema = arg
return visitor.schema(arg, VisitFuture(schema.as_struct(), visitor))
elif isinstance(arg, Type):
type_var = arg
if type_var.type_id == TypeID.STRUCT:
struct = type_var.as_nested_type().as_struct_type()
results = list()
fields = struct.fields
for field in fields:
results.append(VisitFieldFuture(field, visitor))
struct = visitor.struct(struct, [x.get() for x in results])
return struct
elif type_var.type_id == TypeID.LIST:
list_var = type_var.as_nested_type().as_list_type()
return visitor.list(list_var, VisitFuture(list_var.element_type, visitor))
elif type_var.type_id == TypeID.MAP:
raise NotImplementedError()
return visitor.primitive(type_var.as_primitive_type())
class SchemaVisitor(object):
def __init__(self):
self.field_names = list()
self.field_ids = list()
def schema(self, schema, struct_result):
return None
def struct(self, struct, field_results):
return None
def field(self, field, field_result):
return None
def list(self, list_var, element_result):
return None
def map(self, map_var, key_result, value_result):
return None
def primitive(self, primitive_var):
return None
class CustomOrderSchemaVisitor(object):
def __init__(self):
super(CustomOrderSchemaVisitor, self).__init__()
def schema(self, schema, struct_result):
return None
def struct(self, struct, field_results):
return None
def field(self, field, field_result):
return None
def list(self, list_var, element_result):
return None
def map(self, map_var, key_result, value_result):
return None
def primitive(self, primitive_var):
return None
class VisitFuture(object):
def __init__(self, type, visitor):
self.type = type
self.visitor = visitor
def get(self):
return visit(self.type, self.visitor)
class VisitFieldFuture(object):
def __init__(self, field, visitor):
self.field = field
self.visitor = visitor
def get(self):
return self.visitor.field(self.field, VisitFuture(self.field.type, self.visitor).get)
def decimal_required_bytes(precision):
if precision < 0 or precision > 40:
raise RuntimeError("Unsupported decimal precision: %s" % precision)
return REQUIRED_LENGTH[precision]
class GetProjectedIds(SchemaVisitor):
def __init__(self):
super(GetProjectedIds, self).__init__()
self.field_ids = list()
def schema(self, schema, struct_result):
return self.field_ids
def struct(self, struct, field_results):
return self.field_ids
def field(self, field, field_result):
if field_result is None:
self.field_ids.append(field.field_id)
return self.field_ids
def list(self, list_var, element_result):
if element_result is None:
for field in list_var.fields():
self.field_ids.append(field.field_id)
return self.field_ids
def map(self, map_var, key_result, value_result):
if value_result is None:
for field in map_var.fields():
self.field_ids.append(field.field_id)
return self.field_ids
class PruneColumns(SchemaVisitor):
def __init__(self, selected):
super(PruneColumns, self).__init__()
self.selected = list(selected)
def schema(self, schema, struct_result):
return struct_result
def struct(self, struct, field_results):
fields = struct.fields
selected_fields = list()
same_types = True
for i, projected_type in enumerate(field_results):
field = fields[i]
if projected_type is not None:
if field.type == projected_type:
selected_fields.append(field)
elif projected_type is not None:
same_types = False
if field.is_optional:
selected_fields.append(NestedField.optional(field.field_id,
field.name,
projected_type))
else:
selected_fields.append(NestedField.required(field.field_id,
field.name,
projected_type))
if len(selected_fields) != 0:
if len(selected_fields) == len(fields) and same_types:
return struct
else:
return StructType.of(selected_fields)
def field(self, field, field_result):
if field.field_id in self.selected:
return field.type
elif field_result is not None:
return field_result
def primitive(self, primitive_var):
return None
class IndexByName(SchemaVisitor):
DOT = "."
def __init__(self):
super(IndexByName, self).__init__()
self.name_to_id = dict()
def schema(self, schema, struct_result):
return self.name_to_id
def struct(self, struct, field_results):
return self.name_to_id
def field(self, field, field_result):
self.add_field(field.name, field.field_id)
def list(self, list_var, element_result):
for field in list_var.fields():
self.add_field(field.name, field.field_id)
def map(self, map_var, key_result, value_result):
for field in map_var.fields():
self.add_field(field.name, field.field_id)
def add_field(self, name, field_id):
full_name = name
if not self.field_names and len(self.field_names) > 0:
full_name = IndexByName.DOT.join([IndexByName.DOT.join(reversed(self.field_names)), name])
self.name_to_id[full_name] = field_id
class IndexById(SchemaVisitor):
def __init__(self):
super(IndexById, self).__init__()
self.index = dict()
def schema(self, schema, struct_result):
return self.index
def struct(self, struct, field_results):
return self.index
def field(self, field, field_result):
self.index[field.field_id] = field
def list(self, list_var, element_result):
for field in list_var.fields():
self.index[field.field_id] = field
def map(self, map_var, key_result, value_result):
for field in map_var.fields:
self.index[field.field_id] = field
class NextID(object):
def __init__(self):
raise NotImplementedError()
def get(self):
raise NotImplementedError()
class AssignFreshIds(CustomOrderSchemaVisitor):
def __init__(self, next_id):
super(AssignFreshIds, self).__init__()
self.next_id = next_id
def schema(self, schema, struct_result):
return self.next_id()
def struct(self, struct, field_results):
fields = struct.fields
length = len(struct.fields)
new_ids = list()
for _ in range(length):
new_ids.append(self.next_id())
new_fields = list()
types = iter(field_results)
for i in range(length):
field = fields[i]
type = next(types)
if field.is_optional:
new_fields.append(NestedField.optional(new_ids[i], field.name, type))
else:
new_fields.append(NestedField.required(new_ids[i], field.name, type))
return StructType.of(new_fields)
def field(self, field, field_result):
return field_result()
def list(self, list_var, element_result):
new_id = self.next_id()
if list_var.is_element_optional():
return ListType.of_optional(new_id, element_result.get())
else:
return ListType.of_required(new_id, element_result.get())
def map(self, map_var, key_result, value_result):
new_key_id = self.next_id()
new_value_id = self.next_id()
if map_var.is_value_optional():
return MapType.of_optional(new_key_id, new_value_id, key_result(), value_result())
else:
return MapType.of_required(new_key_id, new_value_id, key_result(), value_result())
def primitive(self, primitive_var):
return primitive_var
class CheckCompatibility(CustomOrderSchemaVisitor):
@staticmethod
def write_compatibility_errors(read_schema, write_schema):
visit(read_schema, CheckCompatibility(write_schema, True))
@staticmethod
def read_compatibility_errors(read_schema, write_schema):
visit(write_schema, CheckCompatibility(read_schema, False))
NO_ERRORS: List[str] = []
def __init__(self, schema, check_ordering):
self.schema = schema
self.check_ordering = check_ordering
self.current_type = None
def schema(self, schema, struct_result):
self.current_type = self.schema.as_struct()
try:
struct_result.get()
finally:
self.current_type = None
def struct(self, struct, field_results):
if struct is None:
raise RuntimeError("Evaluation must start with a schema.")
if not self.current_type.is_struct_type():
return [": %s cannot be read as a struct" % self.current_type]
errors = []
for field_errors in field_results:
errors = errors + field_errors
if self.check_ordering:
new_struct = self.current_type.as_struct_type()
id_to_ord = {}
for i, val in enumerate(new_struct.fields):
id_to_ord[val.field_id] = i
last_ordinal = -1
for read_field in self.struct.fields:
id_var = read_field.field_id
field = struct.field(id=id_var)
if field is not None:
ordinal = id_to_ord[id]
if last_ordinal >= ordinal:
errors.append("%s is out of order before %s" % (read_field.name,
new_struct.fields[last_ordinal].name))
last_ordinal = ordinal
return errors
def field(self, field, field_result) -> List[str]:
struct = self.current_type.as_struct_type()
curr_field = struct.field(field.field_id)
errors = []
if curr_field is None:
if not field.is_optional:
errors.append("{} is required, but is missing".format(field.name))
return self.NO_ERRORS
self.current_type = curr_field.type
try:
if not field.is_optional and curr_field.is_optional:
errors.append(field.name + " should be required, but is optional")
for error in field_result:
if error.startswith(":"):
errors.append("{}{}".format(field.field_name, error))
else:
errors.append("{}.{}".format(field.field_name, error))
return errors
except RuntimeError:
pass
finally:
self.current_type = struct
return errors
def list(self, list_var, element_result):
raise NotImplementedError()
def map(self, map_var, key_result, value_result):
raise NotImplementedError()
def primitive(self, primitive_var):
raise NotImplementedError()
| true | true |
f7f8b42e34379c5fbcaadc191c0b8029b3990e77 | 4,977 | py | Python | seq2seq_chatbot/preprocessing/cornell.py | rohitjack/J.A.R.V.I.C. | 7d2bff9a3b1d9c1bb73a8db751db9657698d66b7 | [
"MIT"
] | 1 | 2019-11-25T23:36:30.000Z | 2019-11-25T23:36:30.000Z | seq2seq_chatbot/preprocessing/cornell.py | rohitjack/J.A.R.V.I.C. | 7d2bff9a3b1d9c1bb73a8db751db9657698d66b7 | [
"MIT"
] | null | null | null | seq2seq_chatbot/preprocessing/cornell.py | rohitjack/J.A.R.V.I.C. | 7d2bff9a3b1d9c1bb73a8db751db9657698d66b7 | [
"MIT"
] | 5 | 2019-04-06T23:10:09.000Z | 2019-12-19T19:03:43.000Z | import torch
from torch.jit import script, trace
import torch.nn as nn
from torch import optim
import torch.nn.functional as F
import csv
import random
import re
import os
import unicodedata
import codecs
from io import open
import itertools
import math
import pickle
from utils import *
corpus_name = "cornell"
corpus = os.path.join("data", corpus_name)
def printLines(file, n=10):
with open(file, 'rb') as datafile:
lines = datafile.readlines()
for line in lines[:n]:
print(line)
printLines(os.path.join(corpus, "movie_lines.txt"))
def loadLines(fileName, fields):
lines = {}
with open(fileName, 'r', encoding='iso-8859-1') as f:
for line in f:
values = line.split(" +++$+++ ")
# Extract fields
lineObj = {}
for i, field in enumerate(fields):
lineObj[field] = values[i]
lines[lineObj['lineID']] = lineObj
return lines
# Groups fields of lines from `loadLines` into conversations based on *movie_conversations.txt*
def loadConversations(fileName, lines, fields):
conversations = []
with open(fileName, 'r', encoding='iso-8859-1') as f:
for line in f:
values = line.split(" +++$+++ ")
# Extract fields
convObj = {}
for i, field in enumerate(fields):
convObj[field] = values[i]
# Convert string to list (convObj["utteranceIDs"] == "['L598485', 'L598486', ...]")
lineIds = eval(convObj["utteranceIDs"])
# Reassemble lines
convObj["lines"] = []
for lineId in lineIds:
convObj["lines"].append(lines[lineId])
conversations.append(convObj)
return conversations
MIN_COUNT = 3 # Minimum word count threshold for trimming
def trimRareWords(voc, pairs, MIN_COUNT):
# Trim words used under the MIN_COUNT from the voc
voc.trim(MIN_COUNT)
# Filter out pairs with trimmed words
keep_pairs = []
for pair in pairs:
input_sentence = pair[0]
output_sentence = pair[1]
keep_input = True
keep_output = True
# Check input sentence
for word in input_sentence.split(' '):
if word not in voc.word2index:
keep_input = False
break
# Check output sentence
for word in output_sentence.split(' '):
if word not in voc.word2index:
keep_output = False
break
# Only keep pairs that do not contain trimmed word(s) in their input or output sentence
if keep_input and keep_output:
keep_pairs.append(pair)
print("Trimmed from {} pairs to {}, {:.4f} of total".format(len(pairs), len(keep_pairs), len(keep_pairs) / len(pairs)))
return keep_pairs
# Extracts pairs of sentences from conversations
def extractSentencePairs(conversations):
qa_pairs = []
for conversation in conversations:
# Iterate over all the lines of the conversation
for i in range(len(conversation["lines"]) - 1): # We ignore the last line (no answer for it)
inputLine = conversation["lines"][i]["text"].strip()
targetLine = conversation["lines"][i+1]["text"].strip()
# Filter wrong samples (if one of the lists is empty)
if inputLine and targetLine:
qa_pairs.append([inputLine, targetLine])
return qa_pairs
datafile = os.path.join(corpus, "formatted_movie_lines.txt")
delimiter = ' '
# Unescape the delimiter
delimiter = str(codecs.decode(delimiter, "unicode_escape"))
# Initialize lines dict, conversations list, and field ids
lines = {}
conversations = []
MOVIE_LINES_FIELDS = ["lineID", "characterID", "movieID", "character", "text"]
MOVIE_CONVERSATIONS_FIELDS = ["character1ID", "character2ID", "movieID", "utteranceIDs"]
# Load lines and process conversations
print("\nProcessing corpus...")
lines = loadLines(os.path.join(corpus, "movie_lines.txt"), MOVIE_LINES_FIELDS)
print("\nLoading conversations...")
conversations = loadConversations(os.path.join(corpus, "movie_conversations.txt"),
lines, MOVIE_CONVERSATIONS_FIELDS)
# Write new csv file
print("\nWriting newly formatted file...")
with open(datafile, 'w', encoding='utf-8') as outputfile:
pairs = extractSentencePairs(conversations)
pairs = [[normalizeString(s) for s in pair]for pair in pairs]
# print(pairs)
voc, _ = loadPrepareData("cornell", "cornell", "data/cornell/movie_lines.txt", "data/cornell", pairs)
# Trim voc and pairs
pairs = filterPairs(pairs)
pairs = trimRareWords(voc, pairs, MIN_COUNT)
pickle_out_pairs = open(os.path.join(corpus, "cornell_pairs.pickle"), "wb")
pickle.dump(pairs, pickle_out_pairs)
pickle_out_pairs.close()
pickle_out_voc = open(os.path.join(corpus, "cornell_voc.pickle"), "wb")
pickle.dump(voc, pickle_out_voc)
pickle_out_voc.close() | 33.18 | 123 | 0.644364 | import torch
from torch.jit import script, trace
import torch.nn as nn
from torch import optim
import torch.nn.functional as F
import csv
import random
import re
import os
import unicodedata
import codecs
from io import open
import itertools
import math
import pickle
from utils import *
corpus_name = "cornell"
corpus = os.path.join("data", corpus_name)
def printLines(file, n=10):
with open(file, 'rb') as datafile:
lines = datafile.readlines()
for line in lines[:n]:
print(line)
printLines(os.path.join(corpus, "movie_lines.txt"))
def loadLines(fileName, fields):
lines = {}
with open(fileName, 'r', encoding='iso-8859-1') as f:
for line in f:
values = line.split(" +++$+++ ")
lineObj = {}
for i, field in enumerate(fields):
lineObj[field] = values[i]
lines[lineObj['lineID']] = lineObj
return lines
def loadConversations(fileName, lines, fields):
conversations = []
with open(fileName, 'r', encoding='iso-8859-1') as f:
for line in f:
values = line.split(" +++$+++ ")
convObj = {}
for i, field in enumerate(fields):
convObj[field] = values[i]
lineIds = eval(convObj["utteranceIDs"])
convObj["lines"] = []
for lineId in lineIds:
convObj["lines"].append(lines[lineId])
conversations.append(convObj)
return conversations
MIN_COUNT = 3
def trimRareWords(voc, pairs, MIN_COUNT):
voc.trim(MIN_COUNT)
keep_pairs = []
for pair in pairs:
input_sentence = pair[0]
output_sentence = pair[1]
keep_input = True
keep_output = True
for word in input_sentence.split(' '):
if word not in voc.word2index:
keep_input = False
break
for word in output_sentence.split(' '):
if word not in voc.word2index:
keep_output = False
break
if keep_input and keep_output:
keep_pairs.append(pair)
print("Trimmed from {} pairs to {}, {:.4f} of total".format(len(pairs), len(keep_pairs), len(keep_pairs) / len(pairs)))
return keep_pairs
def extractSentencePairs(conversations):
qa_pairs = []
for conversation in conversations:
for i in range(len(conversation["lines"]) - 1):
inputLine = conversation["lines"][i]["text"].strip()
targetLine = conversation["lines"][i+1]["text"].strip()
if inputLine and targetLine:
qa_pairs.append([inputLine, targetLine])
return qa_pairs
datafile = os.path.join(corpus, "formatted_movie_lines.txt")
delimiter = ' '
delimiter = str(codecs.decode(delimiter, "unicode_escape"))
lines = {}
conversations = []
MOVIE_LINES_FIELDS = ["lineID", "characterID", "movieID", "character", "text"]
MOVIE_CONVERSATIONS_FIELDS = ["character1ID", "character2ID", "movieID", "utteranceIDs"]
print("\nProcessing corpus...")
lines = loadLines(os.path.join(corpus, "movie_lines.txt"), MOVIE_LINES_FIELDS)
print("\nLoading conversations...")
conversations = loadConversations(os.path.join(corpus, "movie_conversations.txt"),
lines, MOVIE_CONVERSATIONS_FIELDS)
print("\nWriting newly formatted file...")
with open(datafile, 'w', encoding='utf-8') as outputfile:
pairs = extractSentencePairs(conversations)
pairs = [[normalizeString(s) for s in pair]for pair in pairs]
voc, _ = loadPrepareData("cornell", "cornell", "data/cornell/movie_lines.txt", "data/cornell", pairs)
pairs = filterPairs(pairs)
pairs = trimRareWords(voc, pairs, MIN_COUNT)
pickle_out_pairs = open(os.path.join(corpus, "cornell_pairs.pickle"), "wb")
pickle.dump(pairs, pickle_out_pairs)
pickle_out_pairs.close()
pickle_out_voc = open(os.path.join(corpus, "cornell_voc.pickle"), "wb")
pickle.dump(voc, pickle_out_voc)
pickle_out_voc.close() | true | true |
f7f8b49229fa3c8682dfb682060bc70425813e68 | 10,178 | py | Python | build_scripts/build_utils.py | ashwinprasadme/pytype | fed209c73aacfcab15efc33deef3b4016a67cfe5 | [
"Apache-2.0"
] | null | null | null | build_scripts/build_utils.py | ashwinprasadme/pytype | fed209c73aacfcab15efc33deef3b4016a67cfe5 | [
"Apache-2.0"
] | null | null | null | build_scripts/build_utils.py | ashwinprasadme/pytype | fed209c73aacfcab15efc33deef3b4016a67cfe5 | [
"Apache-2.0"
] | null | null | null | """Module with common utilities used by other build and test scripts."""
from __future__ import print_function
import json
import os
import shutil
import subprocess
import sys
PYTYPE_SRC_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OUT_DIR = os.path.join(PYTYPE_SRC_ROOT, "out")
SRC_PYI_DIR = os.path.join(PYTYPE_SRC_ROOT, "pytype", "pyi")
OUT_PYI_DIR = os.path.join(OUT_DIR, "pytype", "pyi")
CMAKE_LOG = os.path.join(OUT_DIR, "cmake.log")
NINJA_LOG = os.path.join(OUT_DIR, "ninja.log")
GEN_FILE_LIST = [
"lexer.lex.cc",
"location.hh",
"parser.tab.cc",
"parser.tab.hh",
"position.hh",
"stack.hh",
]
NINJA_FAILURE_PREFIX = "FAILED: "
FAILURE_MSG_PREFIX = ">>> FAIL"
PASS_MSG_PREFIX = ">>> PASS"
RESULT_MSG_SEP = " - "
_NOT_A_MSG = 0
_NINJA_FAILURE_MSG = 1
_TEST_MODULE_FAIL_MSG = 2
_TEST_MODULE_PASS_MSG = 3
def current_py_version():
"""Return the Python version under which this script is being run."""
return "%d.%d" % (sys.version_info.major, sys.version_info.minor)
def build_script(base_name):
"""Return the full path to a script in the 'build_scripts' directory."""
return os.path.join(PYTYPE_SRC_ROOT, "build_scripts", base_name)
class BuildConfig(object):
"""Utility class to create and manage the build config cache."""
BUILD_CONFIG_CACHE = os.path.join(OUT_DIR, ".build_config.json")
def __init__(self, **kwargs):
self.py_version = kwargs.get("py_version")
self.build_type = kwargs.get("build_type")
def save_to_cache_file(self):
with open(self.BUILD_CONFIG_CACHE, "w") as f:
json.dump(
{"py_version": self.py_version, "build_type": self.build_type}, f)
def __eq__(self, other):
return all([self.py_version == other.py_version,
self.build_type == other.build_type])
def __ne__(self, other):
return any([self.py_version != other.py_version,
self.build_type != other.build_type])
@classmethod
def current_build_config(cls, debug):
return BuildConfig(**{
"py_version": current_py_version(),
"build_type": "debug" if debug else "None"
})
@classmethod
def read_cached_config(cls):
if os.path.exists(cls.BUILD_CONFIG_CACHE):
with open(cls.BUILD_CONFIG_CACHE, "r") as f:
return BuildConfig(**json.load(f))
else:
# There is no python version cache file during the very first run.
return BuildConfig(**{})
def clean_dir(dir_path, exclude_file_list=None):
exclude_list = exclude_file_list or []
for item in os.listdir(dir_path):
path = os.path.join(dir_path, item)
if os.path.isdir(path):
shutil.rmtree(path)
elif item not in exclude_list:
os.remove(path)
def _clean_out_dir(msg):
print(msg)
clean_dir(OUT_DIR, ["README.md", ".gitignore"])
def parse_ninja_output_line(line):
if line.startswith(NINJA_FAILURE_PREFIX):
return _NINJA_FAILURE_MSG, None, None
elif line.startswith(FAILURE_MSG_PREFIX):
components = line.split(RESULT_MSG_SEP)
log_file = components[2] if len(components) == 3 else None
return _TEST_MODULE_FAIL_MSG, components[1], log_file
elif line.startswith(PASS_MSG_PREFIX):
_, mod_name = line.split(RESULT_MSG_SEP)
return _TEST_MODULE_PASS_MSG, mod_name, None
else:
return _NOT_A_MSG, None, None
def failure_msg(mod_name, log_file):
components = [FAILURE_MSG_PREFIX, mod_name]
if log_file:
components.append(log_file)
return RESULT_MSG_SEP.join(components)
def pass_msg(mod_name):
return RESULT_MSG_SEP.join([PASS_MSG_PREFIX, mod_name])
def run_cmd(cmd, cwd=None, pipe=True):
process_options = {}
if pipe:
process_options = {
"stdout": subprocess.PIPE,
"stderr": subprocess.STDOUT,
}
if cwd:
process_options["cwd"] = cwd
process = subprocess.Popen(cmd, **process_options)
stdout, _ = process.communicate()
if pipe and sys.version_info.major >= 3:
# Popen.communicate returns a bytes object always.
stdout = stdout.decode("utf-8")
return process.returncode, stdout
def run_cmake(force_clean=False, log_output=False, debug_build=False):
"""Run cmake in the 'out' directory."""
current_config = BuildConfig.current_build_config(debug_build)
if force_clean:
_clean_out_dir("Force-cleaning 'out' directory.")
elif BuildConfig.read_cached_config() != current_config:
_clean_out_dir(
"Previous build config was different; cleaning 'out' directory.\n")
else:
print("Running with build config same as cached build config; "
"not cleaning 'out' directory.\n")
if os.path.exists(os.path.join(OUT_DIR, "build.ninja")):
# Run CMake if it was not already run. If CMake was already run, it
# generates a build.ninja file in the "out" directory.
msg = "Running CMake skipped as the build.ninja file is present ...\n"
print(msg)
if log_output:
with open(CMAKE_LOG, "w") as cmake_log:
cmake_log.write(msg)
return True
print("Running CMake ...\n")
cmd = ["cmake", PYTYPE_SRC_ROOT, "-G", "Ninja",
"-DPython_ADDITIONAL_VERSIONS=%s" % current_config.py_version]
if debug_build:
cmd.append("-DCMAKE_BUILD_TYPE=Debug")
returncode, stdout = run_cmd(cmd, cwd=OUT_DIR)
# Print the full CMake output to stdout. It is not a lot that it would
# clutter the output, and also gives information about the Python version
# found etc.
print(stdout)
if log_output:
with open(CMAKE_LOG, "w") as cmake_log:
cmake_log.write(stdout)
if returncode != 0:
print(">>> FAILED: CMake command '%s'" % " ".join(cmd))
if log_output:
print(">>> Full CMake output is available in '%s'." % CMAKE_LOG)
return False
# Cache the config for which the build files have been generated.
current_config.save_to_cache_file()
return True
class FailCollector(object):
"""A class to collect failures."""
def __init__(self):
self._failures = []
def add_failure(self, mod_name, log_file):
self._failures.append((mod_name, log_file))
def print_report(self, verbose):
num_failures = len(self._failures)
if num_failures == 0:
return
print("\n%d test module(s) failed: \n" % num_failures)
for mod_name, log_file in self._failures:
msg = "** %s" % mod_name
if log_file:
msg += " - %s" % log_file
print(msg)
if log_file and verbose:
with open(log_file.strip(), 'r') as f:
print(f.read(), file=sys.stderr)
def run_ninja(targets, fail_collector=None, fail_fast=False, verbose=False):
"""Run ninja over the list of specified targets.
Arguments:
targets: The list of targets to run.
fail_collector: A FailCollector object to collect failures.
fail_fast: If True, abort at the first target failure.
verbose: If True, print verbose output.
Returns:
True if no target fails. False, otherwise.
"""
# The -k option to ninja, set to a very high value, makes it run until it
# detects all failures. So, we set it to a high value unless |fail_fast| is
# True.
cmd = ["ninja", "-k", "1" if fail_fast else "100000"] + targets
process = subprocess.Popen(cmd, cwd=OUT_DIR,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
failed_targets = []
# When verbose output is requested, test failure logs are printed to stderr.
# However, sometimes a test fails without generating a log, in which case we
# need to print the ninja build output to see what happened.
print_if_verbose = False
with open(NINJA_LOG, "w") as ninja_log:
while True:
line = process.stdout.readline()
if not line:
break
if sys.version_info.major >= 3:
# process.stdout.readline() always returns a 'bytes' object.
line = line.decode("utf-8")
ninja_log.write(line)
msg_type, modname, logfile = parse_ninja_output_line(line)
if msg_type == _NINJA_FAILURE_MSG:
# This is a failed ninja target.
failed_targets.append(line[len(NINJA_FAILURE_PREFIX):].strip())
print_if_verbose = True
if msg_type == _TEST_MODULE_PASS_MSG or msg_type == _TEST_MODULE_FAIL_MSG:
print(line)
if msg_type == _TEST_MODULE_FAIL_MSG:
fail_collector.add_failure(modname, logfile)
print_if_verbose = False
if verbose and print_if_verbose:
print(line.rstrip())
if failed_targets:
# For convenience, we will print the list of failed targets.
summary_hdr = ">>> Found Ninja target failures (includes test failures):"
print("\n" + summary_hdr)
ninja_log.write("\n" + summary_hdr + "\n")
for t in failed_targets:
target = " - %s" % t
print(target)
ninja_log.write(target + "\n")
process.wait()
if process.returncode == 0:
return True
else:
# Ninja output can be a lot. Printing it here will clutter the output of
# this script. So, just tell the user how to repro the error.
print(">>> FAILED: Ninja command '%s'." % " ".join(cmd))
print(">>> Run it in the 'out' directory to reproduce.")
print(">>> Full Ninja output is available in '%s'." % NINJA_LOG)
print(">>> Failing test modules (if any) will be reported below.")
return False
def generate_files():
"""Run flex and bison to produce the parser .cc and .h files.
Returns:
None upon success, otherwise an error message.
"""
if not run_cmake(force_clean=True):
return "Running CMake failed!"
ninja_cmd = ["ninja", "pytype.pyi.parser_gen", "pytype.pyi.lexer"]
print("Building flex and bison outputs ...\n")
returncode, stdout = run_cmd(ninja_cmd, cwd=OUT_DIR)
if returncode != 0:
return "Error generating the Flex and Bison outputs:\n%s" % stdout
# Copy the generated files into the source tree.
for gen_file in GEN_FILE_LIST:
print("Copying %s to source tree ...\n" % gen_file)
shutil.copy(os.path.join(OUT_PYI_DIR, gen_file),
os.path.join(SRC_PYI_DIR, gen_file))
return None
def clean_generated_files():
for gen_file in GEN_FILE_LIST:
print("Deleting %s from source tree ...\n" % gen_file)
os.remove(os.path.join(SRC_PYI_DIR, gen_file))
| 33.701987 | 80 | 0.681666 |
from __future__ import print_function
import json
import os
import shutil
import subprocess
import sys
PYTYPE_SRC_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OUT_DIR = os.path.join(PYTYPE_SRC_ROOT, "out")
SRC_PYI_DIR = os.path.join(PYTYPE_SRC_ROOT, "pytype", "pyi")
OUT_PYI_DIR = os.path.join(OUT_DIR, "pytype", "pyi")
CMAKE_LOG = os.path.join(OUT_DIR, "cmake.log")
NINJA_LOG = os.path.join(OUT_DIR, "ninja.log")
GEN_FILE_LIST = [
"lexer.lex.cc",
"location.hh",
"parser.tab.cc",
"parser.tab.hh",
"position.hh",
"stack.hh",
]
NINJA_FAILURE_PREFIX = "FAILED: "
FAILURE_MSG_PREFIX = ">>> FAIL"
PASS_MSG_PREFIX = ">>> PASS"
RESULT_MSG_SEP = " - "
_NOT_A_MSG = 0
_NINJA_FAILURE_MSG = 1
_TEST_MODULE_FAIL_MSG = 2
_TEST_MODULE_PASS_MSG = 3
def current_py_version():
return "%d.%d" % (sys.version_info.major, sys.version_info.minor)
def build_script(base_name):
return os.path.join(PYTYPE_SRC_ROOT, "build_scripts", base_name)
class BuildConfig(object):
BUILD_CONFIG_CACHE = os.path.join(OUT_DIR, ".build_config.json")
def __init__(self, **kwargs):
self.py_version = kwargs.get("py_version")
self.build_type = kwargs.get("build_type")
def save_to_cache_file(self):
with open(self.BUILD_CONFIG_CACHE, "w") as f:
json.dump(
{"py_version": self.py_version, "build_type": self.build_type}, f)
def __eq__(self, other):
return all([self.py_version == other.py_version,
self.build_type == other.build_type])
def __ne__(self, other):
return any([self.py_version != other.py_version,
self.build_type != other.build_type])
@classmethod
def current_build_config(cls, debug):
return BuildConfig(**{
"py_version": current_py_version(),
"build_type": "debug" if debug else "None"
})
@classmethod
def read_cached_config(cls):
if os.path.exists(cls.BUILD_CONFIG_CACHE):
with open(cls.BUILD_CONFIG_CACHE, "r") as f:
return BuildConfig(**json.load(f))
else:
return BuildConfig(**{})
def clean_dir(dir_path, exclude_file_list=None):
exclude_list = exclude_file_list or []
for item in os.listdir(dir_path):
path = os.path.join(dir_path, item)
if os.path.isdir(path):
shutil.rmtree(path)
elif item not in exclude_list:
os.remove(path)
def _clean_out_dir(msg):
print(msg)
clean_dir(OUT_DIR, ["README.md", ".gitignore"])
def parse_ninja_output_line(line):
if line.startswith(NINJA_FAILURE_PREFIX):
return _NINJA_FAILURE_MSG, None, None
elif line.startswith(FAILURE_MSG_PREFIX):
components = line.split(RESULT_MSG_SEP)
log_file = components[2] if len(components) == 3 else None
return _TEST_MODULE_FAIL_MSG, components[1], log_file
elif line.startswith(PASS_MSG_PREFIX):
_, mod_name = line.split(RESULT_MSG_SEP)
return _TEST_MODULE_PASS_MSG, mod_name, None
else:
return _NOT_A_MSG, None, None
def failure_msg(mod_name, log_file):
components = [FAILURE_MSG_PREFIX, mod_name]
if log_file:
components.append(log_file)
return RESULT_MSG_SEP.join(components)
def pass_msg(mod_name):
return RESULT_MSG_SEP.join([PASS_MSG_PREFIX, mod_name])
def run_cmd(cmd, cwd=None, pipe=True):
process_options = {}
if pipe:
process_options = {
"stdout": subprocess.PIPE,
"stderr": subprocess.STDOUT,
}
if cwd:
process_options["cwd"] = cwd
process = subprocess.Popen(cmd, **process_options)
stdout, _ = process.communicate()
if pipe and sys.version_info.major >= 3:
stdout = stdout.decode("utf-8")
return process.returncode, stdout
def run_cmake(force_clean=False, log_output=False, debug_build=False):
current_config = BuildConfig.current_build_config(debug_build)
if force_clean:
_clean_out_dir("Force-cleaning 'out' directory.")
elif BuildConfig.read_cached_config() != current_config:
_clean_out_dir(
"Previous build config was different; cleaning 'out' directory.\n")
else:
print("Running with build config same as cached build config; "
"not cleaning 'out' directory.\n")
if os.path.exists(os.path.join(OUT_DIR, "build.ninja")):
msg = "Running CMake skipped as the build.ninja file is present ...\n"
print(msg)
if log_output:
with open(CMAKE_LOG, "w") as cmake_log:
cmake_log.write(msg)
return True
print("Running CMake ...\n")
cmd = ["cmake", PYTYPE_SRC_ROOT, "-G", "Ninja",
"-DPython_ADDITIONAL_VERSIONS=%s" % current_config.py_version]
if debug_build:
cmd.append("-DCMAKE_BUILD_TYPE=Debug")
returncode, stdout = run_cmd(cmd, cwd=OUT_DIR)
print(stdout)
if log_output:
with open(CMAKE_LOG, "w") as cmake_log:
cmake_log.write(stdout)
if returncode != 0:
print(">>> FAILED: CMake command '%s'" % " ".join(cmd))
if log_output:
print(">>> Full CMake output is available in '%s'." % CMAKE_LOG)
return False
current_config.save_to_cache_file()
return True
class FailCollector(object):
def __init__(self):
self._failures = []
def add_failure(self, mod_name, log_file):
self._failures.append((mod_name, log_file))
def print_report(self, verbose):
num_failures = len(self._failures)
if num_failures == 0:
return
print("\n%d test module(s) failed: \n" % num_failures)
for mod_name, log_file in self._failures:
msg = "** %s" % mod_name
if log_file:
msg += " - %s" % log_file
print(msg)
if log_file and verbose:
with open(log_file.strip(), 'r') as f:
print(f.read(), file=sys.stderr)
def run_ninja(targets, fail_collector=None, fail_fast=False, verbose=False):
cmd = ["ninja", "-k", "1" if fail_fast else "100000"] + targets
process = subprocess.Popen(cmd, cwd=OUT_DIR,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
failed_targets = []
print_if_verbose = False
with open(NINJA_LOG, "w") as ninja_log:
while True:
line = process.stdout.readline()
if not line:
break
if sys.version_info.major >= 3:
line = line.decode("utf-8")
ninja_log.write(line)
msg_type, modname, logfile = parse_ninja_output_line(line)
if msg_type == _NINJA_FAILURE_MSG:
failed_targets.append(line[len(NINJA_FAILURE_PREFIX):].strip())
print_if_verbose = True
if msg_type == _TEST_MODULE_PASS_MSG or msg_type == _TEST_MODULE_FAIL_MSG:
print(line)
if msg_type == _TEST_MODULE_FAIL_MSG:
fail_collector.add_failure(modname, logfile)
print_if_verbose = False
if verbose and print_if_verbose:
print(line.rstrip())
if failed_targets:
summary_hdr = ">>> Found Ninja target failures (includes test failures):"
print("\n" + summary_hdr)
ninja_log.write("\n" + summary_hdr + "\n")
for t in failed_targets:
target = " - %s" % t
print(target)
ninja_log.write(target + "\n")
process.wait()
if process.returncode == 0:
return True
else:
print(">>> FAILED: Ninja command '%s'." % " ".join(cmd))
print(">>> Run it in the 'out' directory to reproduce.")
print(">>> Full Ninja output is available in '%s'." % NINJA_LOG)
print(">>> Failing test modules (if any) will be reported below.")
return False
def generate_files():
if not run_cmake(force_clean=True):
return "Running CMake failed!"
ninja_cmd = ["ninja", "pytype.pyi.parser_gen", "pytype.pyi.lexer"]
print("Building flex and bison outputs ...\n")
returncode, stdout = run_cmd(ninja_cmd, cwd=OUT_DIR)
if returncode != 0:
return "Error generating the Flex and Bison outputs:\n%s" % stdout
for gen_file in GEN_FILE_LIST:
print("Copying %s to source tree ...\n" % gen_file)
shutil.copy(os.path.join(OUT_PYI_DIR, gen_file),
os.path.join(SRC_PYI_DIR, gen_file))
return None
def clean_generated_files():
for gen_file in GEN_FILE_LIST:
print("Deleting %s from source tree ...\n" % gen_file)
os.remove(os.path.join(SRC_PYI_DIR, gen_file))
| true | true |
f7f8b5e6443c454c806ae74762d1ab9410daa794 | 3,303 | py | Python | pilot/util/constants.py | MihaMuskinja/pilot2 | b40c07baa84f910089c75b8be964199a1ccc5a1f | [
"Apache-2.0"
] | null | null | null | pilot/util/constants.py | MihaMuskinja/pilot2 | b40c07baa84f910089c75b8be964199a1ccc5a1f | [
"Apache-2.0"
] | null | null | null | pilot/util/constants.py | MihaMuskinja/pilot2 | b40c07baa84f910089c75b8be964199a1ccc5a1f | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Authors:
# - Mario Lassnig, mario.lassnig@cern.ch, 2017
# - Paul Nilsson, paul.nilsson@cern.ch, 2018-2019
from os import environ
# Pilot version
RELEASE = '2' # released number should be fixed at 2 for Pilot 2
VERSION = '4' # version number is '1' for first real Pilot 2 release, '0' until then, increased for bigger updates
REVISION = '1' # revision number should be reset to '0' for every new version release, increased for small updates
BUILD = '1' # build number should be reset to '1' for every new development cycle
SUCCESS = 0
FAILURE = 1
ERRNO_NOJOBS = 20
# Sorting order constants
UTILITY_BEFORE_PAYLOAD = 0
UTILITY_WITH_PAYLOAD = 1
UTILITY_AFTER_PAYLOAD_STARTED = 2
UTILITY_AFTER_PAYLOAD_FINISHED = 3
UTILITY_WITH_STAGEIN = 4
# Timing constants that allow for additional constants to be defined for values before the pilot is started, ie for
# wrapper timing purposes.
PILOT_START_TIME = 'PILOT_START_TIME'
PILOT_MULTIJOB_START_TIME = 'PILOT_MULTIJOB_START_TIME'
PILOT_PRE_GETJOB = 'PILOT_PRE_GETJOB'
PILOT_POST_GETJOB = 'PILOT_POST_GETJOB' # note: PILOT_POST_GETJOB corresponds to START_TIME in Pilot 1
PILOT_PRE_SETUP = 'PILOT_PRE_SETUP'
PILOT_POST_SETUP = 'PILOT_POST_SETUP'
PILOT_PRE_STAGEIN = 'PILOT_PRE_STAGEIN'
PILOT_POST_STAGEIN = 'PILOT_POST_STAGEIN'
PILOT_PRE_PAYLOAD = 'PILOT_PRE_PAYLOAD'
PILOT_POST_PAYLOAD = 'PILOT_POST_PAYLOAD'
PILOT_PRE_STAGEOUT = 'PILOT_PRE_STAGEOUT'
PILOT_POST_STAGEOUT = 'PILOT_POST_STAGEOUT'
PILOT_PRE_FINAL_UPDATE = 'PILOT_PRE_FINAL_UPDATE'
PILOT_POST_FINAL_UPDATE = 'PILOT_POST_FINAL_UPDATE'
PILOT_END_TIME = 'PILOT_END_TIME'
PILOT_KILL_SIGNAL = 'PILOT_KILL_SIGNAL'
# Keep track of log transfers
LOG_TRANSFER_NOT_DONE = 'NOT_DONE'
LOG_TRANSFER_IN_PROGRESS = 'IN_PROGRESS'
LOG_TRANSFER_DONE = 'DONE'
LOG_TRANSFER_FAILED = 'FAILED'
# Keep track of server updates
SERVER_UPDATE_NOT_DONE = 'NOT_DONE'
SERVER_UPDATE_RUNNING = 'RUNNING'
SERVER_UPDATE_UPDATING = 'UPDATING_FINAL'
SERVER_UPDATE_FINAL = 'DONE_FINAL'
SERVER_UPDATE_TROUBLE = 'LOST_HEARTBEAT'
# How long should the pilot wait before it should commit suicide after it has received a kill signal?
MAX_KILL_WAIT_TIME = 120 # twenty minutes
def get_pilot_version():
"""
Return the current Pilot version string with the format <release>.<version>.<revision> (<build>).
E.g. pilot_version = '2.1.3 (12)'
:return: version string.
"""
return '{release}.{version}.{revision} ({build})'.format(release=RELEASE,
version=VERSION,
revision=REVISION,
build=BUILD)
def get_rucio_client_version():
"""
Return the current Rucio client version string using the environmental variable ATLAS_LOCAL_RUCIOCLIENTS_VERSION.
If the environmental variable is not set, then an empty string will be returned.
:return: $ATLAS_LOCAL_RUCIOCLIENTS_VERSION (string).
"""
return environ.get('ATLAS_LOCAL_RUCIOCLIENTS_VERSION', '')
| 37.11236 | 117 | 0.734787 |
from os import environ
RELEASE = '2'
VERSION = '4'
REVISION = '1'
BUILD = '1'
SUCCESS = 0
FAILURE = 1
ERRNO_NOJOBS = 20
UTILITY_BEFORE_PAYLOAD = 0
UTILITY_WITH_PAYLOAD = 1
UTILITY_AFTER_PAYLOAD_STARTED = 2
UTILITY_AFTER_PAYLOAD_FINISHED = 3
UTILITY_WITH_STAGEIN = 4
PILOT_START_TIME = 'PILOT_START_TIME'
PILOT_MULTIJOB_START_TIME = 'PILOT_MULTIJOB_START_TIME'
PILOT_PRE_GETJOB = 'PILOT_PRE_GETJOB'
PILOT_POST_GETJOB = 'PILOT_POST_GETJOB'
PILOT_PRE_SETUP = 'PILOT_PRE_SETUP'
PILOT_POST_SETUP = 'PILOT_POST_SETUP'
PILOT_PRE_STAGEIN = 'PILOT_PRE_STAGEIN'
PILOT_POST_STAGEIN = 'PILOT_POST_STAGEIN'
PILOT_PRE_PAYLOAD = 'PILOT_PRE_PAYLOAD'
PILOT_POST_PAYLOAD = 'PILOT_POST_PAYLOAD'
PILOT_PRE_STAGEOUT = 'PILOT_PRE_STAGEOUT'
PILOT_POST_STAGEOUT = 'PILOT_POST_STAGEOUT'
PILOT_PRE_FINAL_UPDATE = 'PILOT_PRE_FINAL_UPDATE'
PILOT_POST_FINAL_UPDATE = 'PILOT_POST_FINAL_UPDATE'
PILOT_END_TIME = 'PILOT_END_TIME'
PILOT_KILL_SIGNAL = 'PILOT_KILL_SIGNAL'
LOG_TRANSFER_NOT_DONE = 'NOT_DONE'
LOG_TRANSFER_IN_PROGRESS = 'IN_PROGRESS'
LOG_TRANSFER_DONE = 'DONE'
LOG_TRANSFER_FAILED = 'FAILED'
SERVER_UPDATE_NOT_DONE = 'NOT_DONE'
SERVER_UPDATE_RUNNING = 'RUNNING'
SERVER_UPDATE_UPDATING = 'UPDATING_FINAL'
SERVER_UPDATE_FINAL = 'DONE_FINAL'
SERVER_UPDATE_TROUBLE = 'LOST_HEARTBEAT'
MAX_KILL_WAIT_TIME = 120
def get_pilot_version():
return '{release}.{version}.{revision} ({build})'.format(release=RELEASE,
version=VERSION,
revision=REVISION,
build=BUILD)
def get_rucio_client_version():
return environ.get('ATLAS_LOCAL_RUCIOCLIENTS_VERSION', '')
| true | true |
f7f8b6c7b14117056da60262db675f8233e8c587 | 2,154 | py | Python | evennia/game_template/server/conf/at_search.py | Jaykingamez/evennia | cf7cab1fea99ede3efecb70a65c3eb0fba1d3745 | [
"BSD-3-Clause"
] | 1,544 | 2015-01-01T22:16:31.000Z | 2022-03-31T19:17:45.000Z | evennia/game_template/server/conf/at_search.py | Jaykingamez/evennia | cf7cab1fea99ede3efecb70a65c3eb0fba1d3745 | [
"BSD-3-Clause"
] | 1,686 | 2015-01-02T18:26:31.000Z | 2022-03-31T20:12:03.000Z | evennia/game_template/server/conf/at_search.py | Jaykingamez/evennia | cf7cab1fea99ede3efecb70a65c3eb0fba1d3745 | [
"BSD-3-Clause"
] | 867 | 2015-01-02T21:01:54.000Z | 2022-03-29T00:28:27.000Z | """
Search and multimatch handling
This module allows for overloading two functions used by Evennia's
search functionality:
at_search_result:
This is called whenever a result is returned from an object
search (a common operation in commands). It should (together
with at_multimatch_input below) define some way to present and
differentiate between multiple matches (by default these are
presented as 1-ball, 2-ball etc)
at_multimatch_input:
This is called with a search term and should be able to
identify if the user wants to separate a multimatch-result
(such as that from a previous search). By default, this
function understands input on the form 1-ball, 2-ball etc as
indicating that the 1st or 2nd match for "ball" should be
used.
This module is not called by default, to use it, add the following
line to your settings file:
SEARCH_AT_RESULT = "server.conf.at_search.at_search_result"
"""
def at_search_result(matches, caller, query="", quiet=False, **kwargs):
"""
This is a generic hook for handling all processing of a search
result, including error reporting.
Args:
matches (list): This is a list of 0, 1 or more typeclass instances,
the matched result of the search. If 0, a nomatch error should
be echoed, and if >1, multimatch errors should be given. Only
if a single match should the result pass through.
caller (Object): The object performing the search and/or which should
receive error messages.
query (str, optional): The search query used to produce `matches`.
quiet (bool, optional): If `True`, no messages will be echoed to caller
on errors.
Keyword Args:
nofound_string (str): Replacement string to echo on a notfound error.
multimatch_string (str): Replacement string to echo on a multimatch error.
Returns:
processed_result (Object or None): This is always a single result
or `None`. If `None`, any error reporting/handling should
already have happened.
"""
| 39.163636 | 82 | 0.687094 |
def at_search_result(matches, caller, query="", quiet=False, **kwargs):
| true | true |
f7f8b6e145f8deecf92aca43092f6102a9273755 | 407 | py | Python | backend-python/aiqa_geo_django/wsgi.py | aiqa/geo-docker-django | 87dbb841ce79d43222b7a03f708b142dc4de36de | [
"MIT"
] | 1 | 2020-08-26T17:59:26.000Z | 2020-08-26T17:59:26.000Z | backend-python/aiqa_geo_django/wsgi.py | aiqa/geo-docker-django | 87dbb841ce79d43222b7a03f708b142dc4de36de | [
"MIT"
] | 12 | 2020-06-06T00:56:38.000Z | 2022-02-19T00:17:10.000Z | backend-python/aiqa_geo_django/wsgi.py | aiqa/geo-docker-django | 87dbb841ce79d43222b7a03f708b142dc4de36de | [
"MIT"
] | 1 | 2022-03-16T14:00:24.000Z | 2022-03-16T14:00:24.000Z | """
WSGI config for aiqa_geo_django project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'aiqa_geo_django.settings')
application = get_wsgi_application()
| 23.941176 | 78 | 0.793612 |
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'aiqa_geo_django.settings')
application = get_wsgi_application()
| true | true |
f7f8b6f0fcdc6ccedf7c7153c6f0a944e309844b | 13,723 | py | Python | astlib/asdl.py | cgsdfc/pyast | 75bd766a420bdaf5742e85b1a584046a9bebf5a4 | [
"MIT"
] | null | null | null | astlib/asdl.py | cgsdfc/pyast | 75bd766a420bdaf5742e85b1a584046a9bebf5a4 | [
"MIT"
] | null | null | null | astlib/asdl.py | cgsdfc/pyast | 75bd766a420bdaf5742e85b1a584046a9bebf5a4 | [
"MIT"
] | null | null | null | # Copyright (c) 2020 cgsdfc
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
#-------------------------------------------------------------------------------
# Parser for ASDL [1] definition files. Reads in an ASDL description and parses
# it into an AST that describes it.
#
# The EBNF we're parsing here: Figure 1 of the paper [1]. Extended to support
# modules and attributes after a product. Words starting with Capital letters
# are terminals. Literal tokens are in "double quotes". Others are
# non-terminals. Id is either TokenId or ConstructorId.
#
# module ::= "module" Id "{" [definitions] "}"
# definitions ::= { TypeId "=" type }
# type ::= product | sum
# product ::= fields ["attributes" fields]
# fields ::= "(" { field, "," } field ")"
# field ::= TypeId ["?" | "*"] [Id]
# sum ::= constructor { "|" constructor } ["attributes" fields]
# constructor ::= ConstructorId [fields]
#
# [1] "The Zephyr Abstract Syntax Description Language" by Wang, et. al. See
# http://asdl.sourceforge.net/
#-------------------------------------------------------------------------------
from collections import namedtuple
import re
__all__ = [
'builtin_types', 'parse', 'AST', 'Module', 'Type', 'Constructor', 'Field',
'Sum', 'Product', 'VisitorBase', 'Check', 'check'
]
# The following classes define nodes into which the ASDL description is parsed.
# Note: this is a "meta-AST". ASDL files (such as Python.asdl) describe the AST
# structure used by a programming language. But ASDL files themselves need to be
# parsed. This module parses ASDL files and uses a simple AST to represent them.
# See the EBNF at the top of the file to understand the logical connection
# between the various node types.
builtin_types = {
'identifier', 'string', 'bytes', 'int', 'object', 'singleton', 'constant'
}
class AST:
def __repr__(self):
raise NotImplementedError
class Module(AST):
def __init__(self, name, dfns):
self.name = name
self.dfns = dfns
self.types = {type.name: type.value for type in dfns}
def __repr__(self):
return 'Module({0.name}, {0.dfns})'.format(self)
class Type(AST):
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return 'Type({0.name}, {0.value})'.format(self)
class Constructor(AST):
def __init__(self, name, fields=None):
self.name = name
self.fields = fields or []
def __repr__(self):
return 'Constructor({0.name}, {0.fields})'.format(self)
class Field(AST):
def __init__(self, type, name=None, seq=False, opt=False):
self.type = type
self.name = name
self.seq = seq
self.opt = opt
def __repr__(self):
if self.seq:
extra = ", seq=True"
elif self.opt:
extra = ", opt=True"
else:
extra = ""
if self.name is None:
return 'Field({0.type}{1})'.format(self, extra)
else:
return 'Field({0.type}, {0.name}{1})'.format(self, extra)
class Sum(AST):
def __init__(self, types, attributes=None):
self.types = types
self.attributes = attributes or []
def __repr__(self):
if self.attributes:
return 'Sum({0.types}, {0.attributes})'.format(self)
else:
return 'Sum({0.types})'.format(self)
class Product(AST):
def __init__(self, fields, attributes=None):
self.fields = fields
self.attributes = attributes or []
def __repr__(self):
if self.attributes:
return 'Product({0.fields}, {0.attributes})'.format(self)
else:
return 'Product({0.fields})'.format(self)
# A generic visitor for the meta-AST that describes ASDL. This can be used by
# emitters. Note that this visitor does not provide a generic visit method, so a
# subclass needs to define visit methods from visitModule to as deep as the
# interesting node.
# We also define a Check visitor that makes sure the parsed ASDL is well-formed.
class VisitorBase(object):
"""Generic tree visitor for ASTs."""
def __init__(self):
self.cache = {}
def visit(self, obj, *args):
klass = obj.__class__
meth = self.cache.get(klass)
if meth is None:
methname = "visit" + klass.__name__
meth = getattr(self, methname, None)
self.cache[klass] = meth
if meth:
try:
return meth(obj, *args)
except Exception as e:
# print("Error visiting %r: %s" % (obj, e))
raise
class DefaultVisitor(VisitorBase):
"""A visitor with default implementation of `visit()` methods.
"""
def visitModule(self, mod):
for dfn in mod.dfns:
self.visit(dfn)
def visitType(self, type):
self.visit(type.value, str(type.name))
def visitSum(self, sum, name):
for t in sum.types:
self.visit(t, name)
def visitConstructor(self, cons, name):
key = str(cons.name)
for f in cons.fields:
self.visit(f, key)
def visitField(self, field, name):
pass
def visitProduct(self, prod, name):
for f in prod.fields:
self.visit(f, name)
class Check(VisitorBase):
"""A visitor that checks a parsed ASDL tree for correctness.
Errors are printed and accumulated.
"""
def __init__(self):
super(Check, self).__init__()
self.cons = {}
self.errors = 0
self.types = {}
def visitModule(self, mod):
for dfn in mod.dfns:
self.visit(dfn)
def visitType(self, type):
self.visit(type.value, str(type.name))
def visitSum(self, sum, name):
for t in sum.types:
self.visit(t, name)
def visitConstructor(self, cons, name):
key = str(cons.name)
conflict = self.cons.get(key)
if conflict is None:
self.cons[key] = name
else:
print('Redefinition of constructor {}'.format(key))
print('Defined in {} and {}'.format(conflict, name))
self.errors += 1
for f in cons.fields:
self.visit(f, key)
def visitField(self, field, name):
key = str(field.type)
l = self.types.setdefault(key, [])
l.append(name)
def visitProduct(self, prod, name):
for f in prod.fields:
self.visit(f, name)
def check(mod):
"""Check the parsed ASDL tree for correctness.
Return True if success. For failure, the errors are printed out and False
is returned.
"""
v = Check()
v.visit(mod)
for t in v.types:
if t not in mod.types and not t in builtin_types:
v.errors += 1
uses = ", ".join(v.types[t])
print('Undefined type {}, used in {}'.format(t, uses))
return not v.errors
# The ASDL parser itself comes next. The only interesting external interface
# here is the top-level parse function.
def parse(filename):
"""Parse ASDL from the given file and return a Module node describing it."""
with open(filename) as f:
parser = ASDLParser()
return parser.parse(f.read())
# Types for describing tokens in an ASDL specification.
class TokenKind:
"""TokenKind is provides a scope for enumerated token kinds."""
(ConstructorId, TypeId, Equals, Comma, Question, Pipe, Asterisk, LParen,
RParen, LBrace, RBrace) = range(11)
operator_table = {
'=': Equals,
',': Comma,
'?': Question,
'|': Pipe,
'(': LParen,
')': RParen,
'*': Asterisk,
'{': LBrace,
'}': RBrace
}
Token = namedtuple('Token', 'kind value lineno')
class ASDLSyntaxError(Exception):
def __init__(self, msg, lineno=None):
self.msg = msg
self.lineno = lineno or '<unknown>'
def __str__(self):
return 'Syntax error on line {0.lineno}: {0.msg}'.format(self)
def tokenize_asdl(buf):
"""Tokenize the given buffer. Yield Token objects."""
for lineno, line in enumerate(buf.splitlines(), 1):
for m in re.finditer(r'\s*(\w+|--.*|.)', line.strip()):
c = m.group(1)
if c[0].isalpha():
# Some kind of identifier
if c[0].isupper():
yield Token(TokenKind.ConstructorId, c, lineno)
else:
yield Token(TokenKind.TypeId, c, lineno)
elif c[:2] == '--':
# Comment
break
else:
# Operators
try:
op_kind = TokenKind.operator_table[c]
except KeyError:
raise ASDLSyntaxError('Invalid operator %s' % c, lineno)
yield Token(op_kind, c, lineno)
class ASDLParser:
"""Parser for ASDL files.
Create, then call the parse method on a buffer containing ASDL.
This is a simple recursive descent parser that uses tokenize_asdl for the
lexing.
"""
def __init__(self):
self._tokenizer = None
self.cur_token = None
def parse(self, buf):
"""Parse the ASDL in the buffer and return an AST with a Module root.
"""
self._tokenizer = tokenize_asdl(buf)
self._advance()
return self._parse_module()
def _parse_module(self):
if self._at_keyword('module'):
self._advance()
else:
raise ASDLSyntaxError(
'Expected "module" (found {})'.format(self.cur_token.value),
self.cur_token.lineno)
name = self._match(self._id_kinds)
self._match(TokenKind.LBrace)
defs = self._parse_definitions()
self._match(TokenKind.RBrace)
return Module(name, defs)
def _parse_definitions(self):
defs = []
while self.cur_token.kind == TokenKind.TypeId:
typename = self._advance()
self._match(TokenKind.Equals)
type = self._parse_type()
defs.append(Type(typename, type))
return defs
def _parse_type(self):
if self.cur_token.kind == TokenKind.LParen:
# If we see a (, it's a product
return self._parse_product()
else:
# Otherwise it's a sum. Look for ConstructorId
sumlist = [
Constructor(self._match(TokenKind.ConstructorId),
self._parse_optional_fields())
]
while self.cur_token.kind == TokenKind.Pipe:
# More constructors
self._advance()
sumlist.append(
Constructor(self._match(TokenKind.ConstructorId),
self._parse_optional_fields()))
return Sum(sumlist, self._parse_optional_attributes())
def _parse_product(self):
return Product(self._parse_fields(), self._parse_optional_attributes())
def _parse_fields(self):
fields = []
self._match(TokenKind.LParen)
while self.cur_token.kind == TokenKind.TypeId:
typename = self._advance()
is_seq, is_opt = self._parse_optional_field_quantifier()
id = (self._advance()
if self.cur_token.kind in self._id_kinds else None)
fields.append(Field(typename, id, seq=is_seq, opt=is_opt))
if self.cur_token.kind == TokenKind.RParen:
break
elif self.cur_token.kind == TokenKind.Comma:
self._advance()
self._match(TokenKind.RParen)
return fields
def _parse_optional_fields(self):
if self.cur_token.kind == TokenKind.LParen:
return self._parse_fields()
else:
return None
def _parse_optional_attributes(self):
if self._at_keyword('attributes'):
self._advance()
return self._parse_fields()
else:
return None
def _parse_optional_field_quantifier(self):
is_seq, is_opt = False, False
if self.cur_token.kind == TokenKind.Asterisk:
is_seq = True
self._advance()
elif self.cur_token.kind == TokenKind.Question:
is_opt = True
self._advance()
return is_seq, is_opt
def _advance(self):
""" Return the value of the current token and read the next one into
self.cur_token.
"""
cur_val = None if self.cur_token is None else self.cur_token.value
try:
self.cur_token = next(self._tokenizer)
except StopIteration:
self.cur_token = None
return cur_val
_id_kinds = (TokenKind.ConstructorId, TokenKind.TypeId)
def _match(self, kind):
"""The 'match' primitive of RD parsers.
* Verifies that the current token is of the given kind (kind can
be a tuple, in which the kind must match one of its members).
* Returns the value of the current token
* Reads in the next token
"""
if (isinstance(kind, tuple) and self.cur_token.kind in kind
or self.cur_token.kind == kind):
value = self.cur_token.value
self._advance()
return value
else:
raise ASDLSyntaxError(
'Unmatched {} (found {})'.format(kind, self.cur_token.kind),
self.cur_token.lineno)
def _at_keyword(self, keyword):
return (self.cur_token.kind == TokenKind.TypeId
and self.cur_token.value == keyword)
| 31.33105 | 80 | 0.578008 |
# modules and attributes after a product. Words starting with Capital letters
# are terminals. Literal tokens are in "double quotes". Others are
# non-terminals. Id is either TokenId or ConstructorId.
#
# module ::= "module" Id "{" [definitions] "}"
# definitions ::= { TypeId "=" type }
# type ::= product | sum
# product ::= fields ["attributes" fields]
# fields ::= "(" { field, "," } field ")"
# field ::= TypeId ["?" | "*"] [Id]
# sum ::= constructor { "|" constructor } ["attributes" fields]
# constructor ::= ConstructorId [fields]
#
# [1] "The Zephyr Abstract Syntax Description Language" by Wang, et. al. See
# http://asdl.sourceforge.net/
#-------------------------------------------------------------------------------
from collections import namedtuple
import re
__all__ = [
'builtin_types', 'parse', 'AST', 'Module', 'Type', 'Constructor', 'Field',
'Sum', 'Product', 'VisitorBase', 'Check', 'check'
]
# The following classes define nodes into which the ASDL description is parsed.
# Note: this is a "meta-AST". ASDL files (such as Python.asdl) describe the AST
# structure used by a programming language. But ASDL files themselves need to be
# parsed. This module parses ASDL files and uses a simple AST to represent them.
# See the EBNF at the top of the file to understand the logical connection
# between the various node types.
builtin_types = {
'identifier', 'string', 'bytes', 'int', 'object', 'singleton', 'constant'
}
class AST:
def __repr__(self):
raise NotImplementedError
class Module(AST):
def __init__(self, name, dfns):
self.name = name
self.dfns = dfns
self.types = {type.name: type.value for type in dfns}
def __repr__(self):
return 'Module({0.name}, {0.dfns})'.format(self)
class Type(AST):
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return 'Type({0.name}, {0.value})'.format(self)
class Constructor(AST):
def __init__(self, name, fields=None):
self.name = name
self.fields = fields or []
def __repr__(self):
return 'Constructor({0.name}, {0.fields})'.format(self)
class Field(AST):
def __init__(self, type, name=None, seq=False, opt=False):
self.type = type
self.name = name
self.seq = seq
self.opt = opt
def __repr__(self):
if self.seq:
extra = ", seq=True"
elif self.opt:
extra = ", opt=True"
else:
extra = ""
if self.name is None:
return 'Field({0.type}{1})'.format(self, extra)
else:
return 'Field({0.type}, {0.name}{1})'.format(self, extra)
class Sum(AST):
def __init__(self, types, attributes=None):
self.types = types
self.attributes = attributes or []
def __repr__(self):
if self.attributes:
return 'Sum({0.types}, {0.attributes})'.format(self)
else:
return 'Sum({0.types})'.format(self)
class Product(AST):
def __init__(self, fields, attributes=None):
self.fields = fields
self.attributes = attributes or []
def __repr__(self):
if self.attributes:
return 'Product({0.fields}, {0.attributes})'.format(self)
else:
return 'Product({0.fields})'.format(self)
# A generic visitor for the meta-AST that describes ASDL. This can be used by
# emitters. Note that this visitor does not provide a generic visit method, so a
# subclass needs to define visit methods from visitModule to as deep as the
# interesting node.
# We also define a Check visitor that makes sure the parsed ASDL is well-formed.
class VisitorBase(object):
def __init__(self):
self.cache = {}
def visit(self, obj, *args):
klass = obj.__class__
meth = self.cache.get(klass)
if meth is None:
methname = "visit" + klass.__name__
meth = getattr(self, methname, None)
self.cache[klass] = meth
if meth:
try:
return meth(obj, *args)
except Exception as e:
# print("Error visiting %r: %s" % (obj, e))
raise
class DefaultVisitor(VisitorBase):
def visitModule(self, mod):
for dfn in mod.dfns:
self.visit(dfn)
def visitType(self, type):
self.visit(type.value, str(type.name))
def visitSum(self, sum, name):
for t in sum.types:
self.visit(t, name)
def visitConstructor(self, cons, name):
key = str(cons.name)
for f in cons.fields:
self.visit(f, key)
def visitField(self, field, name):
pass
def visitProduct(self, prod, name):
for f in prod.fields:
self.visit(f, name)
class Check(VisitorBase):
def __init__(self):
super(Check, self).__init__()
self.cons = {}
self.errors = 0
self.types = {}
def visitModule(self, mod):
for dfn in mod.dfns:
self.visit(dfn)
def visitType(self, type):
self.visit(type.value, str(type.name))
def visitSum(self, sum, name):
for t in sum.types:
self.visit(t, name)
def visitConstructor(self, cons, name):
key = str(cons.name)
conflict = self.cons.get(key)
if conflict is None:
self.cons[key] = name
else:
print('Redefinition of constructor {}'.format(key))
print('Defined in {} and {}'.format(conflict, name))
self.errors += 1
for f in cons.fields:
self.visit(f, key)
def visitField(self, field, name):
key = str(field.type)
l = self.types.setdefault(key, [])
l.append(name)
def visitProduct(self, prod, name):
for f in prod.fields:
self.visit(f, name)
def check(mod):
v = Check()
v.visit(mod)
for t in v.types:
if t not in mod.types and not t in builtin_types:
v.errors += 1
uses = ", ".join(v.types[t])
print('Undefined type {}, used in {}'.format(t, uses))
return not v.errors
# The ASDL parser itself comes next. The only interesting external interface
# here is the top-level parse function.
def parse(filename):
with open(filename) as f:
parser = ASDLParser()
return parser.parse(f.read())
# Types for describing tokens in an ASDL specification.
class TokenKind:
(ConstructorId, TypeId, Equals, Comma, Question, Pipe, Asterisk, LParen,
RParen, LBrace, RBrace) = range(11)
operator_table = {
'=': Equals,
',': Comma,
'?': Question,
'|': Pipe,
'(': LParen,
')': RParen,
'*': Asterisk,
'{': LBrace,
'}': RBrace
}
Token = namedtuple('Token', 'kind value lineno')
class ASDLSyntaxError(Exception):
def __init__(self, msg, lineno=None):
self.msg = msg
self.lineno = lineno or '<unknown>'
def __str__(self):
return 'Syntax error on line {0.lineno}: {0.msg}'.format(self)
def tokenize_asdl(buf):
for lineno, line in enumerate(buf.splitlines(), 1):
for m in re.finditer(r'\s*(\w+|--.*|.)', line.strip()):
c = m.group(1)
if c[0].isalpha():
# Some kind of identifier
if c[0].isupper():
yield Token(TokenKind.ConstructorId, c, lineno)
else:
yield Token(TokenKind.TypeId, c, lineno)
elif c[:2] == '--':
# Comment
break
else:
# Operators
try:
op_kind = TokenKind.operator_table[c]
except KeyError:
raise ASDLSyntaxError('Invalid operator %s' % c, lineno)
yield Token(op_kind, c, lineno)
class ASDLParser:
def __init__(self):
self._tokenizer = None
self.cur_token = None
def parse(self, buf):
self._tokenizer = tokenize_asdl(buf)
self._advance()
return self._parse_module()
def _parse_module(self):
if self._at_keyword('module'):
self._advance()
else:
raise ASDLSyntaxError(
'Expected "module" (found {})'.format(self.cur_token.value),
self.cur_token.lineno)
name = self._match(self._id_kinds)
self._match(TokenKind.LBrace)
defs = self._parse_definitions()
self._match(TokenKind.RBrace)
return Module(name, defs)
def _parse_definitions(self):
defs = []
while self.cur_token.kind == TokenKind.TypeId:
typename = self._advance()
self._match(TokenKind.Equals)
type = self._parse_type()
defs.append(Type(typename, type))
return defs
def _parse_type(self):
if self.cur_token.kind == TokenKind.LParen:
# If we see a (, it's a product
return self._parse_product()
else:
sumlist = [
Constructor(self._match(TokenKind.ConstructorId),
self._parse_optional_fields())
]
while self.cur_token.kind == TokenKind.Pipe:
# More constructors
self._advance()
sumlist.append(
Constructor(self._match(TokenKind.ConstructorId),
self._parse_optional_fields()))
return Sum(sumlist, self._parse_optional_attributes())
def _parse_product(self):
return Product(self._parse_fields(), self._parse_optional_attributes())
def _parse_fields(self):
fields = []
self._match(TokenKind.LParen)
while self.cur_token.kind == TokenKind.TypeId:
typename = self._advance()
is_seq, is_opt = self._parse_optional_field_quantifier()
id = (self._advance()
if self.cur_token.kind in self._id_kinds else None)
fields.append(Field(typename, id, seq=is_seq, opt=is_opt))
if self.cur_token.kind == TokenKind.RParen:
break
elif self.cur_token.kind == TokenKind.Comma:
self._advance()
self._match(TokenKind.RParen)
return fields
def _parse_optional_fields(self):
if self.cur_token.kind == TokenKind.LParen:
return self._parse_fields()
else:
return None
def _parse_optional_attributes(self):
if self._at_keyword('attributes'):
self._advance()
return self._parse_fields()
else:
return None
def _parse_optional_field_quantifier(self):
is_seq, is_opt = False, False
if self.cur_token.kind == TokenKind.Asterisk:
is_seq = True
self._advance()
elif self.cur_token.kind == TokenKind.Question:
is_opt = True
self._advance()
return is_seq, is_opt
def _advance(self):
cur_val = None if self.cur_token is None else self.cur_token.value
try:
self.cur_token = next(self._tokenizer)
except StopIteration:
self.cur_token = None
return cur_val
_id_kinds = (TokenKind.ConstructorId, TokenKind.TypeId)
def _match(self, kind):
if (isinstance(kind, tuple) and self.cur_token.kind in kind
or self.cur_token.kind == kind):
value = self.cur_token.value
self._advance()
return value
else:
raise ASDLSyntaxError(
'Unmatched {} (found {})'.format(kind, self.cur_token.kind),
self.cur_token.lineno)
def _at_keyword(self, keyword):
return (self.cur_token.kind == TokenKind.TypeId
and self.cur_token.value == keyword)
| true | true |
f7f8b75db2f5f84e26592d92dfd2f31034826a0c | 5,465 | py | Python | tests/test_sdk_client.py | maddie-vargo/code42cli | fde4a70d4810923b668e8ca2d8d00af75c567dd1 | [
"MIT"
] | null | null | null | tests/test_sdk_client.py | maddie-vargo/code42cli | fde4a70d4810923b668e8ca2d8d00af75c567dd1 | [
"MIT"
] | null | null | null | tests/test_sdk_client.py | maddie-vargo/code42cli | fde4a70d4810923b668e8ca2d8d00af75c567dd1 | [
"MIT"
] | null | null | null | from io import StringIO
import py42.sdk
import py42.settings.debug as debug
import pytest
from py42.exceptions import Py42MFARequiredError
from py42.exceptions import Py42UnauthorizedError
from requests import Response
from requests.exceptions import ConnectionError
from requests.exceptions import HTTPError
from requests.exceptions import RequestException
from .conftest import create_mock_profile
from code42cli.errors import Code42CLIError
from code42cli.errors import LoggedCLIError
from code42cli.main import cli
from code42cli.options import CLIState
from code42cli.sdk_client import create_sdk
@pytest.fixture
def sdk_logger(mocker):
return mocker.patch("code42cli.sdk_client.logger")
@pytest.fixture
def mock_sdk_factory(mocker):
return mocker.patch("py42.sdk.from_local_account")
@pytest.fixture
def mock_profile_with_password():
profile = create_mock_profile()
def mock_get_password():
return "Test Password"
profile.get_password = mock_get_password
return profile
@pytest.fixture
def requests_exception(mocker):
mock_response = mocker.MagicMock(spec=Response)
mock_exception = mocker.MagicMock(spec=RequestException)
mock_exception.response = mock_response
return mock_exception
def test_create_sdk_when_profile_has_ssl_errors_disabled_sets_py42_setting_and_prints_warning(
profile, mocker, capsys
):
mock_py42 = mocker.patch("code42cli.sdk_client.py42")
profile.ignore_ssl_errors = "True"
create_sdk(profile, False)
output = capsys.readouterr()
assert not mock_py42.settings.verify_ssl_certs
assert (
f"Warning: Profile '{profile.name}' has SSL verification disabled. Adding certificate "
"verification is strongly advised." in output.err
)
def test_create_sdk_when_py42_exception_occurs_raises_and_logs_cli_error(
sdk_logger, mock_sdk_factory, requests_exception, mock_profile_with_password
):
mock_sdk_factory.side_effect = Py42UnauthorizedError(requests_exception)
with pytest.raises(Code42CLIError) as err:
create_sdk(mock_profile_with_password, False)
assert "Invalid credentials for user" in err.value.message
assert sdk_logger.log_error.call_count == 1
assert "Failure in HTTP call" in str(sdk_logger.log_error.call_args[0][0])
def test_create_sdk_when_connection_exception_occurs_raises_and_logs_cli_error(
sdk_logger, mock_sdk_factory, mock_profile_with_password
):
mock_sdk_factory.side_effect = ConnectionError("connection message")
with pytest.raises(LoggedCLIError) as err:
create_sdk(mock_profile_with_password, False)
assert "Problem connecting to" in err.value.message
assert sdk_logger.log_error.call_count == 1
assert "connection message" in str(sdk_logger.log_error.call_args[0][0])
def test_create_sdk_when_unknown_exception_occurs_raises_and_logs_cli_error(
sdk_logger, mock_sdk_factory, mock_profile_with_password
):
mock_sdk_factory.side_effect = Exception("test message")
with pytest.raises(LoggedCLIError) as err:
create_sdk(mock_profile_with_password, False)
assert "Unknown problem validating" in err.value.message
assert sdk_logger.log_error.call_count == 1
assert "test message" in str(sdk_logger.log_error.call_args[0][0])
def test_create_sdk_when_told_to_debug_turns_on_debug(
mock_sdk_factory, mock_profile_with_password
):
create_sdk(mock_profile_with_password, True)
assert py42.settings.debug.level == debug.DEBUG
def test_create_sdk_uses_given_credentials(
mock_sdk_factory, mock_profile_with_password
):
create_sdk(mock_profile_with_password, False)
mock_sdk_factory.assert_called_once_with(
"example.com", "foo", "Test Password", totp=None
)
def test_create_sdk_connection_when_mfa_required_exception_raised_prompts_for_totp(
mocker, monkeypatch, mock_sdk_factory, capsys, mock_profile_with_password
):
monkeypatch.setattr("sys.stdin", StringIO("101010"))
response = mocker.MagicMock(spec=Response)
mock_sdk_factory.side_effect = [
Py42MFARequiredError(HTTPError(response=response)),
None,
]
create_sdk(mock_profile_with_password, False)
output = capsys.readouterr()
assert "Multi-factor authentication required. Enter TOTP:" in output.out
def test_create_sdk_connection_when_mfa_token_invalid_raises_expected_cli_error(
mocker, mock_sdk_factory, mock_profile_with_password
):
response = mocker.MagicMock(spec=Response)
response.text = '{"data":null,"error":[{"primaryErrorKey":"INVALID_TIME_BASED_ONE_TIME_PASSWORD","otherErrors":null}],"warnings":null}'
mock_sdk_factory.side_effect = Py42UnauthorizedError(HTTPError(response=response))
with pytest.raises(Code42CLIError) as err:
create_sdk(mock_profile_with_password, False, totp="1234")
assert str(err.value) == "Invalid TOTP token for user foo."
def test_totp_option_when_passed_is_passed_to_sdk_initialization(
mocker, profile, runner
):
mock_py42 = mocker.patch("code42cli.sdk_client.py42.sdk.from_local_account")
cli_state = CLIState()
totp = "1234"
profile.authority_url = "example.com"
profile.username = "user"
profile.get_password.return_value = "password"
cli_state._profile = profile
runner.invoke(cli, ["users", "list", "--totp", totp], obj=cli_state)
mock_py42.assert_called_once_with(
profile.authority_url, profile.username, "password", totp=totp
)
| 34.371069 | 139 | 0.782068 | from io import StringIO
import py42.sdk
import py42.settings.debug as debug
import pytest
from py42.exceptions import Py42MFARequiredError
from py42.exceptions import Py42UnauthorizedError
from requests import Response
from requests.exceptions import ConnectionError
from requests.exceptions import HTTPError
from requests.exceptions import RequestException
from .conftest import create_mock_profile
from code42cli.errors import Code42CLIError
from code42cli.errors import LoggedCLIError
from code42cli.main import cli
from code42cli.options import CLIState
from code42cli.sdk_client import create_sdk
@pytest.fixture
def sdk_logger(mocker):
return mocker.patch("code42cli.sdk_client.logger")
@pytest.fixture
def mock_sdk_factory(mocker):
return mocker.patch("py42.sdk.from_local_account")
@pytest.fixture
def mock_profile_with_password():
profile = create_mock_profile()
def mock_get_password():
return "Test Password"
profile.get_password = mock_get_password
return profile
@pytest.fixture
def requests_exception(mocker):
mock_response = mocker.MagicMock(spec=Response)
mock_exception = mocker.MagicMock(spec=RequestException)
mock_exception.response = mock_response
return mock_exception
def test_create_sdk_when_profile_has_ssl_errors_disabled_sets_py42_setting_and_prints_warning(
profile, mocker, capsys
):
mock_py42 = mocker.patch("code42cli.sdk_client.py42")
profile.ignore_ssl_errors = "True"
create_sdk(profile, False)
output = capsys.readouterr()
assert not mock_py42.settings.verify_ssl_certs
assert (
f"Warning: Profile '{profile.name}' has SSL verification disabled. Adding certificate "
"verification is strongly advised." in output.err
)
def test_create_sdk_when_py42_exception_occurs_raises_and_logs_cli_error(
sdk_logger, mock_sdk_factory, requests_exception, mock_profile_with_password
):
mock_sdk_factory.side_effect = Py42UnauthorizedError(requests_exception)
with pytest.raises(Code42CLIError) as err:
create_sdk(mock_profile_with_password, False)
assert "Invalid credentials for user" in err.value.message
assert sdk_logger.log_error.call_count == 1
assert "Failure in HTTP call" in str(sdk_logger.log_error.call_args[0][0])
def test_create_sdk_when_connection_exception_occurs_raises_and_logs_cli_error(
sdk_logger, mock_sdk_factory, mock_profile_with_password
):
mock_sdk_factory.side_effect = ConnectionError("connection message")
with pytest.raises(LoggedCLIError) as err:
create_sdk(mock_profile_with_password, False)
assert "Problem connecting to" in err.value.message
assert sdk_logger.log_error.call_count == 1
assert "connection message" in str(sdk_logger.log_error.call_args[0][0])
def test_create_sdk_when_unknown_exception_occurs_raises_and_logs_cli_error(
sdk_logger, mock_sdk_factory, mock_profile_with_password
):
mock_sdk_factory.side_effect = Exception("test message")
with pytest.raises(LoggedCLIError) as err:
create_sdk(mock_profile_with_password, False)
assert "Unknown problem validating" in err.value.message
assert sdk_logger.log_error.call_count == 1
assert "test message" in str(sdk_logger.log_error.call_args[0][0])
def test_create_sdk_when_told_to_debug_turns_on_debug(
mock_sdk_factory, mock_profile_with_password
):
create_sdk(mock_profile_with_password, True)
assert py42.settings.debug.level == debug.DEBUG
def test_create_sdk_uses_given_credentials(
mock_sdk_factory, mock_profile_with_password
):
create_sdk(mock_profile_with_password, False)
mock_sdk_factory.assert_called_once_with(
"example.com", "foo", "Test Password", totp=None
)
def test_create_sdk_connection_when_mfa_required_exception_raised_prompts_for_totp(
mocker, monkeypatch, mock_sdk_factory, capsys, mock_profile_with_password
):
monkeypatch.setattr("sys.stdin", StringIO("101010"))
response = mocker.MagicMock(spec=Response)
mock_sdk_factory.side_effect = [
Py42MFARequiredError(HTTPError(response=response)),
None,
]
create_sdk(mock_profile_with_password, False)
output = capsys.readouterr()
assert "Multi-factor authentication required. Enter TOTP:" in output.out
def test_create_sdk_connection_when_mfa_token_invalid_raises_expected_cli_error(
mocker, mock_sdk_factory, mock_profile_with_password
):
response = mocker.MagicMock(spec=Response)
response.text = '{"data":null,"error":[{"primaryErrorKey":"INVALID_TIME_BASED_ONE_TIME_PASSWORD","otherErrors":null}],"warnings":null}'
mock_sdk_factory.side_effect = Py42UnauthorizedError(HTTPError(response=response))
with pytest.raises(Code42CLIError) as err:
create_sdk(mock_profile_with_password, False, totp="1234")
assert str(err.value) == "Invalid TOTP token for user foo."
def test_totp_option_when_passed_is_passed_to_sdk_initialization(
mocker, profile, runner
):
mock_py42 = mocker.patch("code42cli.sdk_client.py42.sdk.from_local_account")
cli_state = CLIState()
totp = "1234"
profile.authority_url = "example.com"
profile.username = "user"
profile.get_password.return_value = "password"
cli_state._profile = profile
runner.invoke(cli, ["users", "list", "--totp", totp], obj=cli_state)
mock_py42.assert_called_once_with(
profile.authority_url, profile.username, "password", totp=totp
)
| true | true |
f7f8b75f9fe8621c2b9fbdba5fe4a6d7353a71c4 | 925 | py | Python | test/record/parser/test_response_whois_nic_fr_fr_property_status_missing.py | huyphan/pyyawhois | 77fb2f73a9c67989f1d41d98f37037406a69d136 | [
"MIT"
] | null | null | null | test/record/parser/test_response_whois_nic_fr_fr_property_status_missing.py | huyphan/pyyawhois | 77fb2f73a9c67989f1d41d98f37037406a69d136 | [
"MIT"
] | null | null | null | test/record/parser/test_response_whois_nic_fr_fr_property_status_missing.py | huyphan/pyyawhois | 77fb2f73a9c67989f1d41d98f37037406a69d136 | [
"MIT"
] | null | null | null |
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# spec/fixtures/responses/whois.nic.fr/fr/property_status_missing
#
# and regenerate the tests with the following script
#
# $ scripts/generate_tests.py
#
from nose.tools import *
from dateutil.parser import parse as time_parse
import yawhois
class TestWhoisNicFrFrPropertyStatusMissing(object):
def setUp(self):
fixture_path = "spec/fixtures/responses/whois.nic.fr/fr/property_status_missing.txt"
host = "whois.nic.fr"
part = yawhois.record.Part(open(fixture_path, "r").read(), host)
self.record = yawhois.record.Record(None, [part])
def test_status(self):
eq_(self.record.status, 'available')
def test_available(self):
eq_(self.record.available, True)
def test_registered(self):
eq_(self.record.registered, False)
| 28.90625 | 92 | 0.699459 |
from nose.tools import *
from dateutil.parser import parse as time_parse
import yawhois
class TestWhoisNicFrFrPropertyStatusMissing(object):
def setUp(self):
fixture_path = "spec/fixtures/responses/whois.nic.fr/fr/property_status_missing.txt"
host = "whois.nic.fr"
part = yawhois.record.Part(open(fixture_path, "r").read(), host)
self.record = yawhois.record.Record(None, [part])
def test_status(self):
eq_(self.record.status, 'available')
def test_available(self):
eq_(self.record.available, True)
def test_registered(self):
eq_(self.record.registered, False)
| true | true |
f7f8b8acb5b5b9732a69cb1704d24ff8e4f740cc | 2,555 | py | Python | assets/agent.py | helderpsilva/tictactoe_reinforcement_learning | 2d7abfb1832545d7287f84f1f7cf4f94cdb8adbb | [
"MIT"
] | 1 | 2021-09-05T13:06:43.000Z | 2021-09-05T13:06:43.000Z | assets/agent.py | helderpsilva/tictactoe_reinforcement_learning | 2d7abfb1832545d7287f84f1f7cf4f94cdb8adbb | [
"MIT"
] | null | null | null | assets/agent.py | helderpsilva/tictactoe_reinforcement_learning | 2d7abfb1832545d7287f84f1f7cf4f94cdb8adbb | [
"MIT"
] | null | null | null | # importar librarias necessarias.
import numpy as np
class Agent():
"""Criação da entidade agente"""
# O símbolo é X ou 0
# O epsilon é a probabilidade que o agente tem de fazer uma escolha aleatória
# O learning rate é a taxa de aprendizagem
def __init__(self, symbol, epsilon = 0.05, learning_rate=0.2, name=None):
self.name = name
self.epsilon = epsilon
self.learning_rate = learning_rate
self.symbol = symbol
self.history = []
# memória do jogador (iniciada com base em value_function.py)
def value_function(self, V):
self.V = V
def make_move(self, environment):
"""Função responsável por executar jogadas"""
# Loop que procura todas as jogadas disponíveis
available_moves = []
for row in range(3):
for column in range(3):
if environment.board[row,column] == 0:
available_moves.append((row,column))
random_choice = np.random.random()
# Escolha aleatória com base no epsilon do agente
if random_choice < self.epsilon:
move_index = np.random.choice(len(available_moves))
player_move = available_moves[move_index]
else:
board_list = []
current_board = environment.board.copy()
for move in available_moves:
future_board = current_board.copy()
future_board[move[0], move[1]] = self.symbol
board_list.append(future_board.copy())
# Entre todas as jogadas possíveis, escolhe a que maximiza a função v
states = [environment.game_status(board) for board in board_list]
values = [self.V[state] for state in states]
best_move = np.argmax(values)
player_move = available_moves[best_move]
environment.board[player_move[0], player_move[1]] = self.symbol
def update_history(self, s):
self.history.append(s)
def update(self, environment):
"""Função responsável pela aprendizagem do agente"""
reward = environment.reward(self.symbol)
target = reward
# Atualização dos valores da função v com base no outcome do jogo
for state in reversed(self.history):
value = self.V[state] + self.learning_rate*(target - self.V[state])
self.V[state] = value
target = value
self.history = [] | 34.527027 | 81 | 0.589432 |
import numpy as np
class Agent():
def __init__(self, symbol, epsilon = 0.05, learning_rate=0.2, name=None):
self.name = name
self.epsilon = epsilon
self.learning_rate = learning_rate
self.symbol = symbol
self.history = []
def value_function(self, V):
self.V = V
def make_move(self, environment):
available_moves = []
for row in range(3):
for column in range(3):
if environment.board[row,column] == 0:
available_moves.append((row,column))
random_choice = np.random.random()
if random_choice < self.epsilon:
move_index = np.random.choice(len(available_moves))
player_move = available_moves[move_index]
else:
board_list = []
current_board = environment.board.copy()
for move in available_moves:
future_board = current_board.copy()
future_board[move[0], move[1]] = self.symbol
board_list.append(future_board.copy())
states = [environment.game_status(board) for board in board_list]
values = [self.V[state] for state in states]
best_move = np.argmax(values)
player_move = available_moves[best_move]
environment.board[player_move[0], player_move[1]] = self.symbol
def update_history(self, s):
self.history.append(s)
def update(self, environment):
reward = environment.reward(self.symbol)
target = reward
for state in reversed(self.history):
value = self.V[state] + self.learning_rate*(target - self.V[state])
self.V[state] = value
target = value
self.history = [] | true | true |
f7f8b9f7af4f546a04bf2214b67f2f46a6d670f0 | 474 | py | Python | data/scripts/templates/object/tangible/medicine/crafted/shared_crafted_stimpack_sm_s1_e.py | obi-two/GameServer | 7d37024e2291a97d49522610cd8f1dbe5666afc2 | [
"MIT"
] | 20 | 2015-02-23T15:11:56.000Z | 2022-03-18T20:56:48.000Z | data/scripts/templates/object/tangible/medicine/crafted/shared_crafted_stimpack_sm_s1_e.py | apathyboy/swganh | 665128efe9154611dec4cb5efc61d246dd095984 | [
"MIT"
] | null | null | null | data/scripts/templates/object/tangible/medicine/crafted/shared_crafted_stimpack_sm_s1_e.py | apathyboy/swganh | 665128efe9154611dec4cb5efc61d246dd095984 | [
"MIT"
] | 20 | 2015-04-04T16:35:59.000Z | 2022-03-24T14:54:37.000Z | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/medicine/crafted/shared_crafted_stimpack_sm_s1_e.iff"
result.attribute_template_id = 7
result.stfName("medicine_name","stimpack_sm_s1_e")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | 27.882353 | 89 | 0.742616 | true | true | |
f7f8ba2ca7e4b9864e16b3b6608a8c74cd53b859 | 2,311 | py | Python | adminmgr/media/code/A3/task3/BD_026_109_110_ufytlDQ.py | IamMayankThakur/test-bigdata | cef633eb394419b955bdce479699d0115d8f99c3 | [
"Apache-2.0"
] | 9 | 2019-11-08T02:05:27.000Z | 2021-12-13T12:06:35.000Z | adminmgr/media/code/A3/task3/BD_026_109_110_ufytlDQ.py | IamMayankThakur/test-bigdata | cef633eb394419b955bdce479699d0115d8f99c3 | [
"Apache-2.0"
] | 6 | 2019-11-27T03:23:16.000Z | 2021-06-10T19:15:13.000Z | adminmgr/media/code/A3/task3/BD_026_109_110_ufytlDQ.py | IamMayankThakur/test-bigdata | cef633eb394419b955bdce479699d0115d8f99c3 | [
"Apache-2.0"
] | 4 | 2019-11-26T17:04:27.000Z | 2021-12-13T11:57:03.000Z | import findspark
findspark.init()
from pyspark import SparkConf,SparkContext
from pyspark.streaming import StreamingContext
from pyspark.sql import Row,SQLContext
import sys
import requests
def aggregate_tweets_count(new_values, total_sum):
return sum(new_values) + (total_sum or 0)
def get_sql_context_instance(spark_context):
if ('sqlContextSingletonInstance' not in globals()):
globals()['sqlContextSingletonInstance'] = SQLContext(spark_context)
return globals()['sqlContextSingletonInstance']
def process_rdd(time, rdd):
#print("----------=========- %s -=========----------" % str(time))
try:
sql_context = get_sql_context_instance(rdd.context)
row_rdd = rdd.map(lambda w: Row(hashtag=w[0], frequency=w[1]))
hashtags_df = sql_context.createDataFrame(row_rdd)
hashtags_df.registerTempTable("hashtags")
h_query = sql_context.sql("select hashtag, frequency from hashtags where hashtag<>'' order by frequency desc, hashtag asc limit 5")
#hashtag_counts_df.show(5)
hashtag_select = h_query.select("hashtag")
hashtag_map = hashtag_select.rdd.map(lambda row : row[0])
ll = hashtag_map.collect()
#ll=hashtag_counts_df.select("hashtag").rdd.map(lambda row : row[0]).collect()
print(','.join(ll))
#hashtag_counts_df.sort("frequency")
#rdd.show()
#hashtag_counts_df.show()
except:
e = sys.exc_info()[0]
#print("Error: %s" % e)
def split_map(x):
a= x.split(';')[7]
b= a.split(',')
temp(b)
def temp(x):
for y in x:
yield (y,1)
conf=SparkConf()
conf.setAppName("BigData")
sc=SparkContext(conf=conf)
batch_size=int(sys.argv[2])
ssc=StreamingContext(sc,batch_size)
ssc.checkpoint("home/checkpoint_BIGDATA")
dataStream=ssc.socketTextStream("localhost",9009)
# dataStream.pprint()
words_hash=dataStream.flatMap(split_map)
# OR
#tweet=dataStream.map(lambda l:l.split(";")[7])
#words=tweet.flatMap(lambda t: t.split(","))
#words_hash=words.map(lambda w: (w,1))
#words_hash.pprint()
win=int(sys.argv[1])
count=words_hash.reduceByKeyAndWindow((lambda x,y:x+y),(lambda x,y:x-y),win,1)
#count.pprint(5)
#TO maintain state
#totalcount=words_hash.updateStateByKey(aggregate_tweets_count)
#totalcount.pprint()
#To Perform operation on each RDD
count.foreachRDD(process_rdd)
#totalcount.pprint(5)
ssc.start()
ssc.awaitTermination(25)
ssc.stop()
| 27.188235 | 134 | 0.727823 | import findspark
findspark.init()
from pyspark import SparkConf,SparkContext
from pyspark.streaming import StreamingContext
from pyspark.sql import Row,SQLContext
import sys
import requests
def aggregate_tweets_count(new_values, total_sum):
return sum(new_values) + (total_sum or 0)
def get_sql_context_instance(spark_context):
if ('sqlContextSingletonInstance' not in globals()):
globals()['sqlContextSingletonInstance'] = SQLContext(spark_context)
return globals()['sqlContextSingletonInstance']
def process_rdd(time, rdd):
try:
sql_context = get_sql_context_instance(rdd.context)
row_rdd = rdd.map(lambda w: Row(hashtag=w[0], frequency=w[1]))
hashtags_df = sql_context.createDataFrame(row_rdd)
hashtags_df.registerTempTable("hashtags")
h_query = sql_context.sql("select hashtag, frequency from hashtags where hashtag<>'' order by frequency desc, hashtag asc limit 5")
hashtag_select = h_query.select("hashtag")
hashtag_map = hashtag_select.rdd.map(lambda row : row[0])
ll = hashtag_map.collect()
print(','.join(ll))
except:
e = sys.exc_info()[0]
def split_map(x):
a= x.split(';')[7]
b= a.split(',')
temp(b)
def temp(x):
for y in x:
yield (y,1)
conf=SparkConf()
conf.setAppName("BigData")
sc=SparkContext(conf=conf)
batch_size=int(sys.argv[2])
ssc=StreamingContext(sc,batch_size)
ssc.checkpoint("home/checkpoint_BIGDATA")
dataStream=ssc.socketTextStream("localhost",9009)
words_hash=dataStream.flatMap(split_map)
win=int(sys.argv[1])
count=words_hash.reduceByKeyAndWindow((lambda x,y:x+y),(lambda x,y:x-y),win,1)
count.foreachRDD(process_rdd)
ssc.start()
ssc.awaitTermination(25)
ssc.stop()
| true | true |
f7f8ba5245d8fbc310f93776b81795296f910b3f | 313 | py | Python | brapci-py/brapci/source/forms.py | ReneFGJ/Brapci | 1e31502d0e5e80995824304ca9daf4816d69926f | [
"MIT"
] | null | null | null | brapci-py/brapci/source/forms.py | ReneFGJ/Brapci | 1e31502d0e5e80995824304ca9daf4816d69926f | [
"MIT"
] | 2 | 2015-01-09T12:19:00.000Z | 2015-01-21T14:05:06.000Z | brapci-py/brapci/source/forms.py | ReneFGJ/Brapci | 1e31502d0e5e80995824304ca9daf4816d69926f | [
"MIT"
] | null | null | null | from django import forms
from .models import Source
class SourceForm(forms.ModelForm):
class Meta:
model = Source
fields = ['id_jnl','jnl_name','jnl_issn_impresso']
class SourceFormConfirm(forms.ModelForm):
class Meta:
model = Source
fields = ['id_jnl'] | 26.083333 | 59 | 0.629393 | from django import forms
from .models import Source
class SourceForm(forms.ModelForm):
class Meta:
model = Source
fields = ['id_jnl','jnl_name','jnl_issn_impresso']
class SourceFormConfirm(forms.ModelForm):
class Meta:
model = Source
fields = ['id_jnl'] | true | true |
f7f8bc285abe6adfcd859b4030edc00a0cd7066e | 61,842 | py | Python | salt/modules/zypper.py | Jille/salt | 286eaf923782851c9b6602583050be804c181a9a | [
"Apache-2.0"
] | null | null | null | salt/modules/zypper.py | Jille/salt | 286eaf923782851c9b6602583050be804c181a9a | [
"Apache-2.0"
] | null | null | null | salt/modules/zypper.py | Jille/salt | 286eaf923782851c9b6602583050be804c181a9a | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
'''
Package support for openSUSE via the zypper package manager
:depends: - ``rpm`` Python module. Install with ``zypper install rpm-python``
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
# Import python libs
from __future__ import absolute_import
import copy
import fnmatch
import logging
import re
import os
import time
import datetime
from salt.utils.versions import LooseVersion
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin,no-name-in-module
import salt.ext.six as six
from salt.exceptions import SaltInvocationError
import salt.utils.event
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
# pylint: enable=import-error,redefined-builtin,no-name-in-module
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
# Import salt libs
import salt.utils
import salt.utils.pkg
import salt.utils.systemd
from salt.exceptions import (
CommandExecutionError, MinionError)
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is openSUSE
'''
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
'''
Zypper parallel caller.
Validates the result and either raises an exception or reports an error.
Allows serial zypper calls (first came, first won).
'''
SUCCESS_EXIT_CODES = [0, 100, 101, 102, 103]
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
'''
Constructor
'''
self.__called = False
self._reset()
def _reset(self):
'''
Resets values of the call setup.
:return:
'''
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = {'SALT_RUNNING': "1"} # Subject to change
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
def __call__(self, *args, **kwargs):
'''
:param args:
:param kwargs:
:return:
'''
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
return self
def __getattr__(self, item):
'''
Call configurator.
:param item:
:return:
'''
# Reset after the call
if self.__called:
self._reset()
self.__called = False
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
'''
Is this is an error code?
:return:
'''
return self.exit_code not in self.SUCCESS_EXIT_CODES
def _is_lock(self):
'''
Is this is a lock error code?
:return:
'''
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
'''
Check and set the result of a zypper command. In case of an error,
either raise a CommandExecutionError or extract the error.
result
The result of a zypper command called with cmd.run_all
'''
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
'''
Call Zypper.
:param state:
:return:
'''
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh:
self.__cmd.append('--no-refresh')
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1" # Disables locking for read-only operations. Do not try that at home!
# Zypper call will stuck here waiting, if another zypper hangs until forever.
# However, Zypper lock needs to be always respected.
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug("Calling Zypper: " + ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: {0}".format(str(data)))
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not len(self.error_msg),
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return self._is_xml_mode() and dom.parseString(self.__call_result['stdout']) or self.__call_result['stdout']
__zypper__ = _Zypper()
class Wildcard(object):
'''
.. versionadded:: 2017.7.0
Converts string wildcard to a zypper query.
Example:
'1.2.3.4*' is '1.2.3.4.whatever.is.here' and is equal to:
'1.2.3.4 >= and < 1.2.3.5'
:param ptn: Pattern
:return: Query range
'''
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
'''
:type zypper: a reference to an instance of a _Zypper class.
'''
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
'''
Convert a string wildcard to a zypper query.
:param pkg_name:
:param pkg_version:
:return:
'''
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version) # Dissects possible operator
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
'''
Get available versions of the package.
:return:
'''
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
'''
Get available difference between next possible matches.
:return:
'''
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
'''
Stash operator from the version, if any.
:return:
'''
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def list_upgrades(refresh=True, **kwargs):
'''
List all available package upgrades on this system
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if refresh:
refresh_db()
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = str(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__.nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
# Provide a list_updates function for those used to using zypper list-updates
list_updates = salt.utils.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
:param names:
Names of the packages to get information about.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url,
summary, description.
:param errors:
Handle RPM field errors. If 'ignore' is chosen, then various mistakes are simply ignored and omitted
from the texts or strings. If 'report' is chonen, then a field with a mistake is not returned, instead
a 'N/A (broken)' (not available, broken) text is placed.
Valid attributes are:
ignore, report
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=ignore
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,vendor errors=report
'''
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if isinstance(value, six.string_types):
# Check, if string is encoded in a proper UTF-8
if six.PY3:
value_ = value.encode('UTF-8', 'ignore').decode('UTF-8', 'ignore')
else:
value_ = value.decode('UTF-8', 'ignore').encode('UTF-8', 'ignore')
if value != value_:
value = kwargs.get('errors', 'ignore') == 'ignore' and value_ or 'N/A (invalid UTF-8)'
log.error('Package {0} has bad UTF-8 code in {1}: {2}'.format(pkg_name, key, value))
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
ret[pkg_name] = t_nfo
return ret
def info_available(*names, **kwargs):
'''
Return the information of the named package available for the system.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
CLI example:
.. code-block:: bash
salt '*' pkg.info_available <package1>
salt '*' pkg.info_available <package1> <package2> <package3> ...
'''
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
# Refresh db before extracting the latest package
if kwargs.get('refresh', True):
refresh_db()
pkg_info = []
batch = names[:]
batch_size = 200
# Run in batches
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__.nolock.call('info', '-t', 'package', *batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower() == 'yes' and True or False
return ret
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
dict will be returned for that package.
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
CLI example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
# Return a string if only one package name passed
if len(names) == 1 and len(ret):
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed or not.
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
# The "not not" tactic is intended here as it forces the return to be False.
return not not latest_version(name, **kwargs) # pylint: disable=C0113
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty dict if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False):
'''
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if ver1 < ver2, 0 if
ver1 == ver2, and 1 if ver1 > ver2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed as a dict with versions
as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
removed:
not supported
purge_desired:
not supported
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
if 'pkg.list_pkgs' in __context__:
if versions_as_list:
return __context__['pkg.list_pkgs']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs'])
__salt__['pkg_resource.stringify'](ret)
return ret
cmd = ['rpm', '-qa', '--queryformat', '%{NAME}_|-%{VERSION}_|-%{RELEASE}_|-%|EPOCH?{%{EPOCH}}:{}|\\n']
ret = {}
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
name, pkgver, rel, epoch = line.split('_|-')
if epoch:
pkgver = '{0}:{1}'.format(epoch, pkgver)
if rel:
pkgver += '-{0}'.format(rel)
__salt__['pkg_resource.add_pkg'](ret, name, pkgver)
__salt__['pkg_resource.sort_pkglist'](ret)
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_configured_repos():
'''
Get all the info about repositories from the configurations.
'''
repos_cfg = configparser.ConfigParser()
repos_cfg.read([REPOS + '/' + fname for fname in os.listdir(REPOS)])
return repos_cfg
def _get_repo_info(alias, repos_cfg=None):
'''
Get one repo meta-data.
'''
try:
meta = dict((repos_cfg or _get_configured_repos()).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo.
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo alias
'''
return _get_repo_info(repo)
def list_repos():
'''
Lists all repos.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos_cfg = _get_configured_repos()
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg)
return all_repos
def del_repo(repo):
'''
Delete a repo.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos()
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__.xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo or alias
alias by which the zypper refers to the repo
url, mirrorlist or baseurl
the URL for zypper to reference
enabled
enable or disable (True or False) repository,
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repository.
cache
Enable or disable (True or False) RPM files caching.
gpgcheck
Enable or disable (True or False) GOG check for this repository.
gpgautoimport
Automatically trust and import new repository.
Key/Value pairs may also be removed from a repo's configuration by setting
a key to a blank value. Bear in mind that a name cannot be deleted, and a
url can only be deleted if a mirrorlist is specified (or vice versa).
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo alias alias=new_alias
salt '*' pkg.mod_repo alias url= mirrorlist=http://host.com/
'''
repos_cfg = _get_configured_repos()
added = False
# An attempt to add new one?
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
# Is there already such repo under different alias?
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg)
# Complete user URL, in case it is not
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme, # pylint: disable=E1123
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
# Add new repo
__zypper__.xml.call('ar', url, repo)
# Verify the repository has been added
repos_cfg = _get_configured_repos()
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
# Note: zypper does not support changing the baseurl
# we need to remove the repository and add it again with the new baseurl
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo)
return mod_repo(repo, **repo_info)
# Modify added or existing repo according to the options
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__.refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
# when used with "zypper ar --refresh" or "zypper mr --refresh"
# --gpg-auto-import-keys is not doing anything
# so we need to specifically refresh here with --gpg-auto-import-keys
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__.xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo)
if comment:
repo['comment'] = comment
return repo
def refresh_db():
'''
Force a repository refresh by calling ``zypper refresh --force``, return a dict::
{'<database name>': Bool}
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__.refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package(s), add refresh=True to force a 'zypper refresh'
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either ``pkgs`` or ``sources`` is passed. Additionally,
please note that this option can only be used to install packages from
a software repository. To install a package file manually, use the
``sources`` option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
fromrepo
Specify a package repository to install from.
downloadonly
Only download the packages, do not install.
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
version
Can be either a version number, or the combination of a comparison
operator (<, >, <=, >=, =) and a version number (ex. '>1.2.3-4').
This parameter is ignored if ``pkgs`` or ``sources`` is passed.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version. As with the ``version`` parameter above, comparison operators
can be used to target a specific version of a package.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4"}]'
salt '*' pkg.install pkgs='["foo", {"bar": "<1.2.3-4"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
ignore_repo_failure
Zypper returns error code 106 if one of the repositories are not available for various reasons.
In case to set strict check, this parameter needs to be set to True. Default: False.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
if refresh:
refresh_db()
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if pkg_params is None or len(pkg_params) == 0:
return {}
version_num = Wildcard(__zypper__)(name, version)
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches()
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append(advisory_id)
else:
targets = pkg_params
old = list_pkgs() if not downloadonly else list_downloaded()
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'{0}\''.format(fromrepo))
else:
fromrepoopt = ''
cmd_install = ['install', '--name', '--auto-agree-with-licenses']
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
errors = []
if pkg_type == 'advisory':
targets = ["patch:{0}".format(t) for t in targets]
# Split the targets into batches of 500 packages each, so that
# the maximal length of the command line is not broken
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure).call(*cmd)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs() if not downloadonly else list_downloaded()
# Handle packages which report multiple new versions
# (affects only kernel packages at this point)
for pkg_name in new:
pkg_data = new[pkg_name]
if isinstance(pkg_data, six.string_types):
new[pkg_name] = pkg_data.split(',')[-1]
ret = salt.utils.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
**kwargs): # pylint: disable=unused-argument
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Run a full system upgrade, a zypper upgrade
refresh
force a refresh if set to True (default).
If set to False it depends on zypper if a refresh is
executed.
dryrun
If set to True, it creates a debug solver log file and then perform
a dry-run upgrade (no changes are made). Default: False
dist_upgrade
Perform a system dist-upgrade. Default: False
fromrepo
Specify a list of package repositories to upgrade from. Default: None
novendorchange
If set to True, no allow vendor changes. Default: False
skip_verify
Skip the GPG verification check (e.g., ``--no-gpg-checks``)
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
salt '*' pkg.upgrade dist-upgrade=True fromrepo='["MyRepoName"]' novendorchange=True
salt '*' pkg.upgrade dist-upgrade=True dryrun=True
'''
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db()
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: {0}'.format(fromrepo))
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope()).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs()
__zypper__(systemd_scope=_systemd_scope()).noraise.call(*cmd_update)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
# Handle packages which report multiple new versions
# (affects only kernel packages at this point)
for pkg in new:
new[pkg] = new[pkg].split(',')[-1]
ret = salt.utils.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None):
'''
Remove and purge do identical things but with different Zypper commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
targets = [target for target in pkg_params if target in old]
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope).call('remove', *targets[:500])
targets = targets[500:]
__context__.pop('pkg.list_pkgs', None)
ret = salt.utils.compare_dicts(old, list_pkgs())
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages with ``zypper -n remove``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs)
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any zypper commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Recursively remove a package and all dependencies which were installed
with it, this will call a ``zypper -n remove -u``
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(name=name, pkgs=pkgs)
def list_locks():
'''
List current package locks.
Return a dict containing the locked package with attributes::
{'<package>': {'case_sensitive': '<case_sensitive>',
'match_type': '<match_type>'
'type': '<type>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locks
'''
locks = {}
if os.path.exists(LOCKS):
with salt.utils.fopen(LOCKS) as fhr:
for meta in [item.split('\n') for item in fhr.read().split('\n\n')]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
return locks
def clean_locks():
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}
if not os.path.exists("/etc/zypp/locks"):
return out
for node in __zypper__.xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def remove_lock(packages, **kwargs): # pylint: disable=unused-argument
'''
Remove specified package lock.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove_lock <package name>
salt '*' pkg.remove_lock <package1>,<package2>,<package3>
salt '*' pkg.remove_lock pkgs='["foo", "bar"]'
'''
locks = list_locks()
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__.call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def add_lock(packages, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>,<package2>,<package3>
salt '*' pkg.add_lock pkgs='["foo", "bar"]'
'''
locks = list_locks()
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__.call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
'''
Runs an rpm -Va on a system, and returns the results in a dict
Files with an attribute of config, doc, ghost, license or readme in the
package header can be ignored using the ``ignore_types`` keyword argument
CLI Example:
.. code-block:: bash
salt '*' pkg.verify
salt '*' pkg.verify httpd
salt '*' pkg.verify 'httpd postfix'
salt '*' pkg.verify 'httpd postfix' ignore_types=['config','doc']
'''
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages):
'''
List the files that belong to a package. Not specifying any packages will
return a list of *every* file on the system's rpm database (not generally
recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of *every* file on the system's
rpm database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_dict'](*packages)
def modified(*packages, **flags):
'''
List the modified files that belong to a package. Not specifying any packages
will return a list of _all_ modified files on the system's RPM database.
.. versionadded:: 2015.5.0
Filtering by flags (True or False):
size
Include only files where size changed.
mode
Include only files which file's mode has been changed.
checksum
Include only files which MD5 checksum has been changed.
device
Include only files which major and minor numbers has been changed.
symlink
Include only files which are symbolic link contents.
owner
Include only files where owner has been changed.
group
Include only files where group has been changed.
time
Include only files where modification time of the file has been changed.
capabilities
Include only files where capabilities differ or not. Note: supported only on newer RPM versions.
CLI Examples:
.. code-block:: bash
salt '*' pkg.modified
salt '*' pkg.modified httpd
salt '*' pkg.modified httpd postfix
salt '*' pkg.modified httpd owner=True group=False
'''
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths):
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. If a single path is passed, a string will be returned,
and if multiple paths are passed, a dictionary of file/package name
pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
return __salt__['lowpkg.owner'](*paths)
def _get_patterns(installed_only=None):
'''
List all known patterns in repos.
'''
patterns = {}
for element in __zypper__.nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False):
'''
List all known patterns from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patterns
'''
if refresh:
refresh_db()
return _get_patterns()
def list_installed_patterns():
'''
List installed patterns on the system.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patterns
'''
return _get_patterns(installed_only=True)
def search(criteria, refresh=False):
'''
List known packags, available to the system.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.search <criteria>
'''
if refresh:
refresh_db()
solvables = __zypper__.nolock.xml.call('se', criteria).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in [slv for slv in solvables
if slv.getAttribute('status') == 'not-installed'
and slv.getAttribute('kind') == 'package']:
out[solvable.getAttribute('name')] = {'summary': solvable.getAttribute('summary')}
return out
def _get_first_aggregate_text(node_list):
'''
Extract text from the first occurred DOM aggregate.
'''
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False):
'''
List all available or installed SUSE products.
all
List all products available or only installed. Default is False.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
Includes handling for OEM products, which read the OEM productline file
and overwrite the release value.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_products
salt '*' pkg.list_products all=True
'''
if refresh:
refresh_db()
ret = list()
OEM_PATH = "/var/lib/suseRegister/OEM"
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__.nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.fopen(oem_file, 'r') as rfile:
oem_release = rfile.readline().strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
CLI example:
.. code-block:: bash
salt '*' pkg.download httpd
salt '*' pkg.download httpd postfix
'''
if not packages:
raise SaltInvocationError('No packages specified')
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db()
pkg_ret = {}
for dld_result in __zypper__.xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path']):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded():
'''
.. versionadded:: 2017.7.0
List prefetched packages downloaded by Zypper in the local disk.
CLI example:
.. code-block:: bash
salt '*' pkg.list_downloaded
'''
CACHE_DIR = '/var/cache/zypp/packages/'
ret = {}
for root, dirnames, filenames in os.walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths):
'''
Return a formatted diff between current files and original in a package.
NOTE: this function includes all files (configuration and not), but does
not work on binary content.
:param path: Full path to the installed file
:return: Difference string or raises and exception if examined file is binary.
CLI example:
.. code-block:: bash
salt '*' pkg.diff /etc/apache2/httpd.conf /etc/sudoers
'''
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys())
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False):
'''
List all known patches in repos.
'''
patches = {}
for element in __zypper__.nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False):
'''
.. versionadded:: 2017.7.0
List all known advisory patches from available repos.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_patches
'''
if refresh:
refresh_db()
return _get_patches()
def list_installed_patches():
'''
.. versionadded:: 2017.7.0
List installed advisory patches on the system.
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_installed_patches
'''
return _get_patches(installed_only=True)
| 31.092006 | 124 | 0.60045 |
from __future__ import absolute_import
import copy
import fnmatch
import logging
import re
import os
import time
import datetime
from salt.utils.versions import LooseVersion
import salt.ext.six as six
from salt.exceptions import SaltInvocationError
import salt.utils.event
from salt.ext.six.moves import configparser
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse
from xml.dom import minidom as dom
from xml.parsers.expat import ExpatError
import salt.utils
import salt.utils.pkg
import salt.utils.systemd
from salt.exceptions import (
CommandExecutionError, MinionError)
log = logging.getLogger(__name__)
HAS_ZYPP = False
ZYPP_HOME = '/etc/zypp'
LOCKS = '{0}/locks'.format(ZYPP_HOME)
REPOS = '{0}/repos.d'.format(ZYPP_HOME)
DEFAULT_PRIORITY = 99
__virtualname__ = 'pkg'
def __virtual__():
if __grains__.get('os_family', '') != 'Suse':
return (False, "Module zypper: non SUSE OS not suppored by zypper package manager")
# Not all versions of SUSE use zypper, check that it is available
if not salt.utils.which('zypper'):
return (False, "Module zypper: zypper package manager not found")
return __virtualname__
class _Zypper(object):
SUCCESS_EXIT_CODES = [0, 100, 101, 102, 103]
LOCK_EXIT_CODE = 7
XML_DIRECTIVES = ['-x', '--xmlout']
ZYPPER_LOCK = '/var/run/zypp.pid'
TAG_RELEASED = 'zypper/released'
TAG_BLOCKED = 'zypper/blocked'
def __init__(self):
self.__called = False
self._reset()
def _reset(self):
self.__cmd = ['zypper', '--non-interactive']
self.__exit_code = 0
self.__call_result = dict()
self.__error_msg = ''
self.__env = {'SALT_RUNNING': "1"} # Subject to change
# Call config
self.__xml = False
self.__no_lock = False
self.__no_raise = False
self.__refresh = False
self.__ignore_repo_failure = False
self.__systemd_scope = False
def __call__(self, *args, **kwargs):
# Ignore exit code for 106 (repo is not available)
if 'no_repo_failure' in kwargs:
self.__ignore_repo_failure = kwargs['no_repo_failure']
if 'systemd_scope' in kwargs:
self.__systemd_scope = kwargs['systemd_scope']
return self
def __getattr__(self, item):
# Reset after the call
if self.__called:
self._reset()
self.__called = False
if item == 'xml':
self.__xml = True
elif item == 'nolock':
self.__no_lock = True
elif item == 'noraise':
self.__no_raise = True
elif item == 'refreshable':
self.__refresh = True
elif item == 'call':
return self.__call
else:
return self.__dict__[item]
# Prevent the use of "refreshable" together with "nolock".
if self.__no_lock:
self.__no_lock = not self.__refresh
return self
@property
def exit_code(self):
return self.__exit_code
@exit_code.setter
def exit_code(self, exit_code):
self.__exit_code = int(exit_code or '0')
@property
def error_msg(self):
return self.__error_msg
@error_msg.setter
def error_msg(self, msg):
if self._is_error():
self.__error_msg = msg and os.linesep.join(msg) or "Check Zypper's logs."
@property
def stdout(self):
return self.__call_result.get('stdout', '')
@property
def stderr(self):
return self.__call_result.get('stderr', '')
@property
def pid(self):
return self.__call_result.get('pid', '')
def _is_error(self):
return self.exit_code not in self.SUCCESS_EXIT_CODES
def _is_lock(self):
return self.exit_code == self.LOCK_EXIT_CODE
def _is_xml_mode(self):
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False
def _check_result(self):
if not self.__call_result:
raise CommandExecutionError('No output result from Zypper?')
self.exit_code = self.__call_result['retcode']
if self._is_lock():
return False
if self._is_error():
_error_msg = list()
if not self._is_xml_mode():
msg = self.__call_result['stderr'] and self.__call_result['stderr'].strip() or ""
if msg:
_error_msg.append(msg)
else:
try:
doc = dom.parseString(self.__call_result['stdout'])
except ExpatError as err:
log.error(err)
doc = None
if doc:
msg_nodes = doc.getElementsByTagName('message')
for node in msg_nodes:
if node.getAttribute('type') == 'error':
_error_msg.append(node.childNodes[0].nodeValue)
elif self.__call_result['stderr'].strip():
_error_msg.append(self.__call_result['stderr'].strip())
self.error_msg = _error_msg
return True
def __call(self, *args, **kwargs):
self.__called = True
if self.__xml:
self.__cmd.append('--xmlout')
if not self.__refresh:
self.__cmd.append('--no-refresh')
self.__cmd.extend(args)
kwargs['output_loglevel'] = 'trace'
kwargs['python_shell'] = False
kwargs['env'] = self.__env.copy()
if self.__no_lock:
kwargs['env']['ZYPP_READONLY_HACK'] = "1"
was_blocked = False
while True:
cmd = []
if self.__systemd_scope:
cmd.extend(['systemd-run', '--scope'])
cmd.extend(self.__cmd)
log.debug("Calling Zypper: " + ' '.join(cmd))
self.__call_result = __salt__['cmd.run_all'](cmd, **kwargs)
if self._check_result():
break
if os.path.exists(self.ZYPPER_LOCK):
try:
with salt.utils.fopen(self.ZYPPER_LOCK) as rfh:
data = __salt__['ps.proc_info'](int(rfh.readline()),
attrs=['pid', 'name', 'cmdline', 'create_time'])
data['cmdline'] = ' '.join(data['cmdline'])
data['info'] = 'Blocking process created at {0}.'.format(
datetime.datetime.utcfromtimestamp(data['create_time']).isoformat())
data['success'] = True
except Exception as err:
data = {'info': 'Unable to retrieve information about blocking process: {0}'.format(err.message),
'success': False}
else:
data = {'info': 'Zypper is locked, but no Zypper lock has been found.', 'success': False}
if not data['success']:
log.debug("Unable to collect data about blocking process.")
else:
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: {0}".format(str(data)))
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
was_blocked = True
if was_blocked:
__salt__['event.fire_master']({'success': not len(self.error_msg),
'info': self.error_msg or 'Zypper has been released'},
self.TAG_RELEASED)
if self.error_msg and not self.__no_raise and not self.__ignore_repo_failure:
raise CommandExecutionError('Zypper command failure: {0}'.format(self.error_msg))
return self._is_xml_mode() and dom.parseString(self.__call_result['stdout']) or self.__call_result['stdout']
__zypper__ = _Zypper()
class Wildcard(object):
Z_OP = ['<', '<=', '=', '>=', '>']
def __init__(self, zypper):
self.name = None
self.version = None
self.zypper = zypper
self._attr_solvable_version = 'edition'
self._op = None
def __call__(self, pkg_name, pkg_version):
if pkg_version:
self.name = pkg_name
self._set_version(pkg_version)
versions = sorted([LooseVersion(vrs)
for vrs in self._get_scope_versions(self._get_available_versions())])
return versions and '{0}{1}'.format(self._op or '', versions[-1]) or None
def _get_available_versions(self):
solvables = self.zypper.nolock.xml.call('se', '-xv', self.name).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError('No packages found matching \'{0}\''.format(self.name))
return sorted(set([slv.getAttribute(self._attr_solvable_version)
for slv in solvables if slv.getAttribute(self._attr_solvable_version)]))
def _get_scope_versions(self, pkg_versions):
get_in_versions = []
for p_version in pkg_versions:
if fnmatch.fnmatch(p_version, self.version):
get_in_versions.append(p_version)
return get_in_versions
def _set_version(self, version):
if not version:
return
exact_version = re.sub(r'[<>=+]*', '', version)
self._op = version.replace(exact_version, '') or None
if self._op and self._op not in self.Z_OP:
raise CommandExecutionError('Zypper do not supports operator "{0}".'.format(self._op))
self.version = exact_version
def _systemd_scope():
return salt.utils.systemd.has_scope(__context__) \
and __salt__['config.get']('systemd.scope', True)
def list_upgrades(refresh=True, **kwargs):
if refresh:
refresh_db()
ret = dict()
cmd = ['list-updates']
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = str(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__.nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
ret[update_node.getAttribute('name')] = update_node.getAttribute('edition')
return ret
list_updates = salt.utils.alias_function(list_upgrades, 'list_updates')
def info_installed(*names, **kwargs):
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
t_nfo = dict()
for key, value in pkg_nfo.items():
if isinstance(value, six.string_types):
if six.PY3:
value_ = value.encode('UTF-8', 'ignore').decode('UTF-8', 'ignore')
else:
value_ = value.decode('UTF-8', 'ignore').encode('UTF-8', 'ignore')
if value != value_:
value = kwargs.get('errors', 'ignore') == 'ignore' and value_ or 'N/A (invalid UTF-8)'
log.error('Package {0} has bad UTF-8 code in {1}: {2}'.format(pkg_name, key, value))
if key == 'source_rpm':
t_nfo['source'] = value
else:
t_nfo[key] = value
ret[pkg_name] = t_nfo
return ret
def info_available(*names, **kwargs):
ret = {}
if not names:
return ret
else:
names = sorted(list(set(names)))
if kwargs.get('refresh', True):
refresh_db()
pkg_info = []
batch = names[:]
batch_size = 200
while batch:
pkg_info.extend(re.split(r"Information for package*",
__zypper__.nolock.call('info', '-t', 'package', *batch[:batch_size])))
batch = batch[batch_size:]
for pkg_data in pkg_info:
nfo = {}
for line in [data for data in pkg_data.split('\n') if ':' in data]:
if line.startswith('-----'):
continue
kw = [data.strip() for data in line.split(':', 1)]
if len(kw) == 2 and kw[1]:
nfo[kw[0].lower()] = kw[1]
if nfo.get('name'):
name = nfo.pop('name')
ret[name] = nfo
if nfo.get('status'):
nfo['status'] = nfo.get('status')
if nfo.get('installed'):
nfo['installed'] = nfo.get('installed').lower() == 'yes' and True or False
return ret
def latest_version(*names, **kwargs):
ret = dict()
if not names:
return ret
names = sorted(list(set(names)))
package_info = info_available(*names, **kwargs)
for name in names:
pkg_info = package_info.get(name, {})
status = pkg_info.get('status', '').lower()
if status.find('not installed') > -1 or status.find('out-of-date') > -1:
ret[name] = pkg_info.get('version')
if len(names) == 1 and len(ret):
return ret[names[0]]
return ret
available_version = salt.utils.alias_function(latest_version, 'available_version')
def upgrade_available(name, **kwargs):
return not not latest_version(name, **kwargs)
def version(*names, **kwargs):
return __salt__['pkg_resource.version'](*names, **kwargs) or {}
def version_cmp(ver1, ver2, ignore_epoch=False):
return __salt__['lowpkg.version_cmp'](ver1, ver2, ignore_epoch=ignore_epoch)
def list_pkgs(versions_as_list=False, **kwargs):
versions_as_list = salt.utils.is_true(versions_as_list)
if any([salt.utils.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
if 'pkg.list_pkgs' in __context__:
if versions_as_list:
return __context__['pkg.list_pkgs']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs'])
__salt__['pkg_resource.stringify'](ret)
return ret
cmd = ['rpm', '-qa', '--queryformat', '%{NAME}_|-%{VERSION}_|-%{RELEASE}_|-%|EPOCH?{%{EPOCH}}:{}|\\n']
ret = {}
for line in __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False).splitlines():
name, pkgver, rel, epoch = line.split('_|-')
if epoch:
pkgver = '{0}:{1}'.format(epoch, pkgver)
if rel:
pkgver += '-{0}'.format(rel)
__salt__['pkg_resource.add_pkg'](ret, name, pkgver)
__salt__['pkg_resource.sort_pkglist'](ret)
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_configured_repos():
repos_cfg = configparser.ConfigParser()
repos_cfg.read([REPOS + '/' + fname for fname in os.listdir(REPOS)])
return repos_cfg
def _get_repo_info(alias, repos_cfg=None):
try:
meta = dict((repos_cfg or _get_configured_repos()).items(alias))
meta['alias'] = alias
for key, val in six.iteritems(meta):
if val in ['0', '1']:
meta[key] = int(meta[key]) == 1
elif val == 'NONE':
meta[key] = None
return meta
except (ValueError, configparser.NoSectionError):
return {}
def get_repo(repo, **kwargs):
return _get_repo_info(repo)
def list_repos():
repos_cfg = _get_configured_repos()
all_repos = {}
for alias in repos_cfg.sections():
all_repos[alias] = _get_repo_info(alias, repos_cfg=repos_cfg)
return all_repos
def del_repo(repo):
repos_cfg = _get_configured_repos()
for alias in repos_cfg.sections():
if alias == repo:
doc = __zypper__.xml.call('rr', '--loose-auth', '--loose-query', alias)
msg = doc.getElementsByTagName('message')
if doc.getElementsByTagName('progress') and msg:
return {
repo: True,
'message': msg[0].childNodes[0].nodeValue,
}
raise CommandExecutionError('Repository \'{0}\' not found.'.format(repo))
def mod_repo(repo, **kwargs):
repos_cfg = _get_configured_repos()
added = False
if repo not in repos_cfg.sections():
url = kwargs.get('url', kwargs.get('mirrorlist', kwargs.get('baseurl')))
if not url:
raise CommandExecutionError(
'Repository \'{0}\' not found, and neither \'baseurl\' nor '
'\'mirrorlist\' was specified'.format(repo)
)
if not _urlparse(url).scheme:
raise CommandExecutionError(
'Repository \'{0}\' not found and URL for baseurl/mirrorlist '
'is malformed'.format(repo)
)
for alias in repos_cfg.sections():
repo_meta = _get_repo_info(alias, repos_cfg=repos_cfg)
new_url = _urlparse(url)
if not new_url.path:
new_url = _urlparse.ParseResult(scheme=new_url.scheme,
netloc=new_url.netloc,
path='/',
params=new_url.params,
query=new_url.query,
fragment=new_url.fragment)
base_url = _urlparse(repo_meta['baseurl'])
if new_url == base_url:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(
repo,
alias
)
)
__zypper__.xml.call('ar', url, repo)
repos_cfg = _get_configured_repos()
if repo not in repos_cfg.sections():
raise CommandExecutionError(
'Failed add new repository \'{0}\' for unspecified reason. '
'Please check zypper logs.'.format(repo))
added = True
repo_info = _get_repo_info(repo)
if (
not added and 'baseurl' in kwargs and
not (kwargs['baseurl'] == repo_info['baseurl'])
):
repo_info.update(kwargs)
repo_info.setdefault('cache', False)
del_repo(repo)
return mod_repo(repo, **repo_info)
cmd_opt = []
global_cmd_opt = []
call_refresh = False
if 'enabled' in kwargs:
cmd_opt.append(kwargs['enabled'] and '--enable' or '--disable')
if 'refresh' in kwargs:
cmd_opt.append(kwargs['refresh'] and '--refresh' or '--no-refresh')
if 'cache' in kwargs:
cmd_opt.append(
kwargs['cache'] and '--keep-packages' or '--no-keep-packages'
)
if 'gpgcheck' in kwargs:
cmd_opt.append(kwargs['gpgcheck'] and '--gpgcheck' or '--no-gpgcheck')
if 'priority' in kwargs:
cmd_opt.append("--priority={0}".format(kwargs.get('priority', DEFAULT_PRIORITY)))
if 'humanname' in kwargs:
cmd_opt.append("--name='{0}'".format(kwargs.get('humanname')))
if kwargs.get('gpgautoimport') is True:
global_cmd_opt.append('--gpg-auto-import-keys')
call_refresh = True
if cmd_opt:
cmd_opt = global_cmd_opt + ['mr'] + cmd_opt + [repo]
__zypper__.refreshable.xml.call(*cmd_opt)
comment = None
if call_refresh:
refresh_opts = global_cmd_opt + ['refresh'] + [repo]
__zypper__.xml.call(*refresh_opts)
elif not added and not cmd_opt:
comment = 'Specified arguments did not result in modification of repo'
repo = get_repo(repo)
if comment:
repo['comment'] = comment
return repo
def refresh_db():
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
out = __zypper__.refreshable.call('refresh', '--force')
for line in out.splitlines():
if not line:
continue
if line.strip().startswith('Repository') and '\'' in line:
try:
key = line.split('\'')[1].strip()
if 'is up to date' in line:
ret[key] = False
except IndexError:
continue
elif line.strip().startswith('Building') and '\'' in line:
key = line.split('\'')[1].strip()
if 'done' in line:
ret[key] = True
return ret
def install(name=None,
refresh=False,
fromrepo=None,
pkgs=None,
sources=None,
downloadonly=None,
skip_verify=False,
version=None,
ignore_repo_failure=False,
**kwargs):
if refresh:
refresh_db()
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](name, pkgs, sources, **kwargs)
except MinionError as exc:
raise CommandExecutionError(exc)
if pkg_params is None or len(pkg_params) == 0:
return {}
version_num = Wildcard(__zypper__)(name, version)
if pkg_type == 'repository':
targets = []
for param, version_num in six.iteritems(pkg_params):
if version_num is None:
log.debug('targeting package: %s', param)
targets.append(param)
else:
prefix, verstr = salt.utils.pkg.split_comparison(version_num)
if not prefix:
prefix = '='
target = '{0}{1}{2}'.format(param, prefix, verstr)
log.debug('targeting package: %s', target)
targets.append(target)
elif pkg_type == 'advisory':
targets = []
cur_patches = list_patches()
for advisory_id in pkg_params:
if advisory_id not in cur_patches:
raise CommandExecutionError('Advisory id "{0}" not found'.format(advisory_id))
else:
targets.append(advisory_id)
else:
targets = pkg_params
old = list_pkgs() if not downloadonly else list_downloaded()
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'{0}\''.format(fromrepo))
else:
fromrepoopt = ''
cmd_install = ['install', '--name', '--auto-agree-with-licenses']
if not refresh:
cmd_install.insert(0, '--no-refresh')
if skip_verify:
cmd_install.insert(0, '--no-gpg-checks')
if downloadonly:
cmd_install.append('--download-only')
if fromrepo:
cmd_install.extend(fromrepoopt)
errors = []
if pkg_type == 'advisory':
targets = ["patch:{0}".format(t) for t in targets]
systemd_scope = _systemd_scope()
while targets:
cmd = cmd_install + targets[:500]
targets = targets[500:]
for line in __zypper__(no_repo_failure=ignore_repo_failure, systemd_scope=systemd_scope).call(*cmd).splitlines():
match = re.match(r"^The selected package '([^']+)'.+has lower version", line)
if match:
downgrades.append(match.group(1))
while downgrades:
cmd = cmd_install + ['--force'] + downgrades[:500]
downgrades = downgrades[500:]
__zypper__(no_repo_failure=ignore_repo_failure).call(*cmd)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs() if not downloadonly else list_downloaded()
# Handle packages which report multiple new versions
# (affects only kernel packages at this point)
for pkg_name in new:
pkg_data = new[pkg_name]
if isinstance(pkg_data, six.string_types):
new[pkg_name] = pkg_data.split(',')[-1]
ret = salt.utils.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered {0} package(s)'.format(
'downloading' if downloadonly else 'installing'
),
info={'errors': errors, 'changes': ret}
)
return ret
def upgrade(refresh=True,
dryrun=False,
dist_upgrade=False,
fromrepo=None,
novendorchange=False,
skip_verify=False,
**kwargs): # pylint: disable=unused-argument
cmd_update = (['dist-upgrade'] if dist_upgrade else ['update']) + ['--auto-agree-with-licenses']
if skip_verify:
# The '--no-gpg-checks' needs to be placed before the Zypper command.
cmd_update.insert(0, '--no-gpg-checks')
if refresh:
refresh_db()
if dryrun:
cmd_update.append('--dry-run')
if dist_upgrade:
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: {0}'.format(fromrepo))
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
if __grains__['osrelease_info'][0] > 11:
cmd_update.append('--no-allow-vendor-change')
log.info('Disabling vendor changes')
else:
log.warning('Disabling vendor changes is not supported on this Zypper version')
if dryrun:
# Creates a solver test case for debugging.
log.info('Executing debugsolver and performing a dry-run dist-upgrade')
__zypper__(systemd_scope=_systemd_scope()).noraise.call(*cmd_update + ['--debug-solver'])
old = list_pkgs()
__zypper__(systemd_scope=_systemd_scope()).noraise.call(*cmd_update)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
# Handle packages which report multiple new versions
# (affects only kernel packages at this point)
for pkg in new:
new[pkg] = new[pkg].split(',')[-1]
ret = salt.utils.compare_dicts(old, new)
if __zypper__.exit_code not in __zypper__.SUCCESS_EXIT_CODES:
result = {
'retcode': __zypper__.exit_code,
'stdout': __zypper__.stdout,
'stderr': __zypper__.stderr,
'pid': __zypper__.pid,
}
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
if dryrun:
ret = (__zypper__.stdout + os.linesep + __zypper__.stderr).strip()
return ret
def _uninstall(name=None, pkgs=None):
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
targets = [target for target in pkg_params if target in old]
if not targets:
return {}
systemd_scope = _systemd_scope()
errors = []
while targets:
__zypper__(systemd_scope=systemd_scope).call('remove', *targets[:500])
targets = targets[500:]
__context__.pop('pkg.list_pkgs', None)
ret = salt.utils.compare_dicts(old, list_pkgs())
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
return _uninstall(name=name, pkgs=pkgs)
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
return _uninstall(name=name, pkgs=pkgs)
def list_locks():
locks = {}
if os.path.exists(LOCKS):
with salt.utils.fopen(LOCKS) as fhr:
for meta in [item.split('\n') for item in fhr.read().split('\n\n')]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
lock.update(dict([tuple([i.strip() for i in element.split(':', 1)]), ]))
if lock.get('solvable_name'):
locks[lock.pop('solvable_name')] = lock
return locks
def clean_locks():
LCK = "removed"
out = {LCK: 0}
if not os.path.exists("/etc/zypp/locks"):
return out
for node in __zypper__.xml.call('cl').getElementsByTagName("message"):
text = node.childNodes[0].nodeValue.lower()
if text.startswith(LCK):
out[LCK] = text.split(" ")[1]
break
return out
def remove_lock(packages, **kwargs): # pylint: disable=unused-argument
locks = list_locks()
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
removed = []
missing = []
for pkg in packages:
if locks.get(pkg):
removed.append(pkg)
else:
missing.append(pkg)
if removed:
__zypper__.call('rl', *removed)
return {'removed': len(removed), 'not_found': missing}
def add_lock(packages, **kwargs): # pylint: disable=unused-argument
locks = list_locks()
added = []
try:
packages = list(__salt__['pkg_resource.parse_targets'](packages)[0].keys())
except MinionError as exc:
raise CommandExecutionError(exc)
for pkg in packages:
if not locks.get(pkg):
added.append(pkg)
if added:
__zypper__.call('al', *added)
return {'added': len(added), 'packages': added}
def verify(*names, **kwargs):
return __salt__['lowpkg.verify'](*names, **kwargs)
def file_list(*packages):
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages):
return __salt__['lowpkg.file_dict'](*packages)
def modified(*packages, **flags):
return __salt__['lowpkg.modified'](*packages, **flags)
def owner(*paths):
return __salt__['lowpkg.owner'](*paths)
def _get_patterns(installed_only=None):
patterns = {}
for element in __zypper__.nolock.xml.call('se', '-t', 'pattern').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patterns[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patterns
def list_patterns(refresh=False):
if refresh:
refresh_db()
return _get_patterns()
def list_installed_patterns():
return _get_patterns(installed_only=True)
def search(criteria, refresh=False):
if refresh:
refresh_db()
solvables = __zypper__.nolock.xml.call('se', criteria).getElementsByTagName('solvable')
if not solvables:
raise CommandExecutionError(
'No packages found matching \'{0}\''.format(criteria)
)
out = {}
for solvable in [slv for slv in solvables
if slv.getAttribute('status') == 'not-installed'
and slv.getAttribute('kind') == 'package']:
out[solvable.getAttribute('name')] = {'summary': solvable.getAttribute('summary')}
return out
def _get_first_aggregate_text(node_list):
if not node_list:
return ''
out = []
for node in node_list[0].childNodes:
if node.nodeType == dom.Document.TEXT_NODE:
out.append(node.nodeValue)
return '\n'.join(out)
def list_products(all=False, refresh=False):
if refresh:
refresh_db()
ret = list()
OEM_PATH = "/var/lib/suseRegister/OEM"
cmd = list()
if not all:
cmd.append('--disable-repos')
cmd.append('products')
if not all:
cmd.append('-i')
product_list = __zypper__.nolock.xml.call(*cmd).getElementsByTagName('product-list')
if not product_list:
return ret # No products found
for prd in product_list[0].getElementsByTagName('product'):
p_nfo = dict()
for k_p_nfo, v_p_nfo in prd.attributes.items():
if k_p_nfo in ['isbase', 'installed']:
p_nfo[k_p_nfo] = bool(v_p_nfo in ['true', '1'])
elif v_p_nfo:
p_nfo[k_p_nfo] = v_p_nfo
eol = prd.getElementsByTagName('endoflife')
if eol:
p_nfo['eol'] = eol[0].getAttribute('text')
p_nfo['eol_t'] = int(eol[0].getAttribute('time_t') or 0)
p_nfo['description'] = " ".join(
[line.strip() for line in _get_first_aggregate_text(
prd.getElementsByTagName('description')
).split(os.linesep)]
)
if 'productline' in p_nfo and p_nfo['productline']:
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.fopen(oem_file, 'r') as rfile:
oem_release = rfile.readline().strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
return ret
def download(*packages, **kwargs):
if not packages:
raise SaltInvocationError('No packages specified')
refresh = kwargs.get('refresh', False)
if refresh:
refresh_db()
pkg_ret = {}
for dld_result in __zypper__.xml.call('download', *packages).getElementsByTagName("download-result"):
repo = dld_result.getElementsByTagName("repository")[0]
path = dld_result.getElementsByTagName("localfile")[0].getAttribute("path")
pkg_info = {
'repository-name': repo.getAttribute('name'),
'repository-alias': repo.getAttribute('alias'),
'path': path,
}
key = _get_first_aggregate_text(
dld_result.getElementsByTagName('name')
)
if __salt__['lowpkg.checksum'](pkg_info['path']):
pkg_ret[key] = pkg_info
if pkg_ret:
failed = [pkg for pkg in packages if pkg not in pkg_ret]
if failed:
pkg_ret['_error'] = ('The following package(s) failed to download: {0}'.format(', '.join(failed)))
return pkg_ret
raise CommandExecutionError(
'Unable to download packages: {0}'.format(', '.join(packages))
)
def list_downloaded():
CACHE_DIR = '/var/cache/zypp/packages/'
ret = {}
for root, dirnames, filenames in os.walk(CACHE_DIR):
for filename in fnmatch.filter(filenames, '*.rpm'):
package_path = os.path.join(root, filename)
pkg_info = __salt__['lowpkg.bin_pkg_info'](package_path)
pkg_timestamp = int(os.path.getctime(package_path))
ret.setdefault(pkg_info['name'], {})[pkg_info['version']] = {
'path': package_path,
'size': os.path.getsize(package_path),
'creation_date_time_t': pkg_timestamp,
'creation_date_time': datetime.datetime.utcfromtimestamp(pkg_timestamp).isoformat(),
}
return ret
def diff(*paths):
ret = {}
pkg_to_paths = {}
for pth in paths:
pth_pkg = __salt__['lowpkg.owner'](pth)
if not pth_pkg:
ret[pth] = os.path.exists(pth) and 'Not managed' or 'N/A'
else:
if pkg_to_paths.get(pth_pkg) is None:
pkg_to_paths[pth_pkg] = []
pkg_to_paths[pth_pkg].append(pth)
if pkg_to_paths:
local_pkgs = __salt__['pkg.download'](*pkg_to_paths.keys())
for pkg, files in six.iteritems(pkg_to_paths):
for path in files:
ret[path] = __salt__['lowpkg.diff'](
local_pkgs[pkg]['path'],
path
) or 'Unchanged'
return ret
def _get_patches(installed_only=False):
patches = {}
for element in __zypper__.nolock.xml.call('se', '-t', 'patch').getElementsByTagName('solvable'):
installed = element.getAttribute('status') == 'installed'
if (installed_only and installed) or not installed_only:
patches[element.getAttribute('name')] = {
'installed': installed,
'summary': element.getAttribute('summary'),
}
return patches
def list_patches(refresh=False):
if refresh:
refresh_db()
return _get_patches()
def list_installed_patches():
return _get_patches(installed_only=True)
| true | true |
f7f8bc36e3301cc58f737c081a0d83f639a1e0a2 | 3,270 | py | Python | readme_metrics/Metrics.py | readmeio/metrics-sdks-python | 02bc6e486260641f1a62760d20370157a4928af6 | [
"0BSD"
] | 2 | 2020-09-23T04:44:22.000Z | 2021-07-06T18:14:11.000Z | readme_metrics/Metrics.py | readmeio/metrics-sdks-python | 02bc6e486260641f1a62760d20370157a4928af6 | [
"0BSD"
] | null | null | null | readme_metrics/Metrics.py | readmeio/metrics-sdks-python | 02bc6e486260641f1a62760d20370157a4928af6 | [
"0BSD"
] | 1 | 2020-09-23T04:44:25.000Z | 2020-09-23T04:44:25.000Z | import atexit
import math
import queue
import threading
import requests
import json
import importlib
from readme_metrics import MetricsApiConfig
from readme_metrics.publisher import publish_batch
from readme_metrics.PayloadBuilder import PayloadBuilder
from readme_metrics.ResponseInfoWrapper import ResponseInfoWrapper
class Metrics:
"""
This is the internal central controller class invoked by the ReadMe middleware. It
queues requests for submission. The submission is processed by readme_metrics.publisher.publish_batch().
"""
PACKAGE_NAME: str = "readme/metrics"
def __init__(self, config: MetricsApiConfig):
"""
Constructs and initializes the ReadMe Metrics controller class with the
specified configuration.
Args:
config (MetricsApiConfig): Running configuration
"""
self.config = config
self.payload_builder = PayloadBuilder(
config.DENYLIST,
config.ALLOWLIST,
config.IS_DEVELOPMENT_MODE,
config.GROUPING_FUNCTION,
config.LOGGER,
)
self.queue = queue.Queue()
atexit.register(self.exit_handler)
def process(self, request, response: ResponseInfoWrapper) -> None:
"""Enqueues a request/response combination to be submitted the API.
Args:
request (Request): Request object from your WSGI server
response (ResponseInfoWrapper): Response object
"""
if not self.host_allowed(request.environ["HTTP_HOST"]):
self.config.LOGGER.debug(
f"Not enqueueing request, host {request.environ['HTTP_HOST']} not in ALLOWED_HTTP_HOSTS"
)
return
payload = self.payload_builder(request, response)
if payload is None:
# PayloadBuilder returns None when the grouping function returns
# None (an indication that the request should not be logged.)
self.config.LOGGER.debug(
f"Not enqueueing request, grouping function returned None"
)
return
self.queue.put(payload)
if self.queue.qsize() >= self.config.BUFFER_LENGTH:
args = (self.config, self.queue)
if self.config.IS_BACKGROUND_MODE:
thread = threading.Thread(target=publish_batch, daemon=True, args=args)
thread.start()
else:
publish_batch(*args)
def exit_handler(self) -> None:
if not self.queue.empty():
args = (self.config, self.queue)
for _ in range(math.ceil(self.queue.qsize() / self.config.BUFFER_LENGTH)):
if self.config.IS_BACKGROUND_MODE:
thread = threading.Thread(
target=publish_batch, daemon=True, args=args
)
thread.start()
else:
publish_batch(*args)
self.queue.join()
def host_allowed(self, host):
if self.config.ALLOWED_HTTP_HOSTS:
return host in self.config.ALLOWED_HTTP_HOSTS
else:
# If the allowed_http_hosts has not been set (None by default), send off the data to be queued
return True
| 34.787234 | 108 | 0.625688 | import atexit
import math
import queue
import threading
import requests
import json
import importlib
from readme_metrics import MetricsApiConfig
from readme_metrics.publisher import publish_batch
from readme_metrics.PayloadBuilder import PayloadBuilder
from readme_metrics.ResponseInfoWrapper import ResponseInfoWrapper
class Metrics:
PACKAGE_NAME: str = "readme/metrics"
def __init__(self, config: MetricsApiConfig):
self.config = config
self.payload_builder = PayloadBuilder(
config.DENYLIST,
config.ALLOWLIST,
config.IS_DEVELOPMENT_MODE,
config.GROUPING_FUNCTION,
config.LOGGER,
)
self.queue = queue.Queue()
atexit.register(self.exit_handler)
def process(self, request, response: ResponseInfoWrapper) -> None:
if not self.host_allowed(request.environ["HTTP_HOST"]):
self.config.LOGGER.debug(
f"Not enqueueing request, host {request.environ['HTTP_HOST']} not in ALLOWED_HTTP_HOSTS"
)
return
payload = self.payload_builder(request, response)
if payload is None:
self.config.LOGGER.debug(
f"Not enqueueing request, grouping function returned None"
)
return
self.queue.put(payload)
if self.queue.qsize() >= self.config.BUFFER_LENGTH:
args = (self.config, self.queue)
if self.config.IS_BACKGROUND_MODE:
thread = threading.Thread(target=publish_batch, daemon=True, args=args)
thread.start()
else:
publish_batch(*args)
def exit_handler(self) -> None:
if not self.queue.empty():
args = (self.config, self.queue)
for _ in range(math.ceil(self.queue.qsize() / self.config.BUFFER_LENGTH)):
if self.config.IS_BACKGROUND_MODE:
thread = threading.Thread(
target=publish_batch, daemon=True, args=args
)
thread.start()
else:
publish_batch(*args)
self.queue.join()
def host_allowed(self, host):
if self.config.ALLOWED_HTTP_HOSTS:
return host in self.config.ALLOWED_HTTP_HOSTS
else:
return True
| true | true |
f7f8bda4ed682df102a1df0273464045520e3003 | 3,317 | py | Python | tests/compat/test_gecko42.py | magopian/amo-validator | bc0ac7519d1d7b6b266fc66d3eee49c63073f58a | [
"BSD-3-Clause"
] | null | null | null | tests/compat/test_gecko42.py | magopian/amo-validator | bc0ac7519d1d7b6b266fc66d3eee49c63073f58a | [
"BSD-3-Clause"
] | null | null | null | tests/compat/test_gecko42.py | magopian/amo-validator | bc0ac7519d1d7b6b266fc66d3eee49c63073f58a | [
"BSD-3-Clause"
] | null | null | null | from helper import CompatTestCase
from validator.chromemanifest import ChromeManifest
from validator.compat import FX42_DEFINITION
from validator.errorbundler import ErrorBundle
from validator.testcases import content
class TestFX42Compat(CompatTestCase):
"""Test that compatibility tests for Gecko 42 are properly executed."""
VERSION = FX42_DEFINITION
def test_parseContentType(self):
self.run_script_for_compat("""
var netutil = Components
.classes["@mozilla.org/network/util;1"]
.getService(Components.interfaces.nsINetUtil);
netutil.parseContentType('text/html', 'utf-8', {});
""")
self.assert_compat_error()
def test_newTab_xul(self):
"""Tests that the newTab.xul overlay is not in the chrome.manifest."""
err = ErrorBundle()
assert content.test_newTab_xul(err, None) is None
err.save_resource('chrome.manifest',
ChromeManifest('foo bar', 'chrome.manifest'))
content.test_newTab_xul(err, None)
assert not err.failed()
err.save_resource(
'chrome.manifest',
ChromeManifest(
('overlay chrome://browser/content/newtab/newTab.xul '
'chrome://ch/content/newtab/index.xul'),
'chrome.manifest'))
content.test_newTab_xul(err, None)
assert err.failed()
assert not err.errors
assert len(err.warnings) == 1
assert err.warnings[0]['compatibility_type'] == 'error'
def test_mozRequestAnimationFrame(self):
self.run_script_for_compat("""
// Don't flag comments: window.mozRequestAnimationFrame()
window.requestAnimationFrame();
""")
assert not self.compat_err.errors
assert not self.compat_err.warnings
self.run_script_for_compat("""
window.mozRequestAnimationFrame();
""")
self.assert_compat_error()
def _test_nsIPermissionManager(self, method):
self.run_script_for_compat("""
var perms = Cc["@mozilla.org/permissionmanager;1"]
.getService(Ci.nsIPermissionManager);
%s
""" % method)
self.assert_compat_error()
def _test_ServicesPerms(self, method):
self.run_script_for_compat("""
Components.utils.import("resource://gre/modules/Services.jsm");
var perms = Services.perms;
%s
""" % method)
self.assert_compat_error()
def test_nsIPermissionManagerMethods(self):
methods = ("perms.add(url, 'cookie', 1);",
"perms.addFromPrincipal(url, 'cookie', 1);",
"perms.remove('yahoo.com', 'cookie');",
"perms.removeFromPrincipal('yahoo.com', 'cookie');",
"perms.removeAll();",
"perms.testExactPermission(url, cookie);"
"perms.testExactPermissionFromPrincipal(url, cookie);",
"perms.testPermission(url, cookie);",
"perms.testPermissionFromPrincipal(url, cookie);")
for method in methods:
yield self._test_nsIPermissionManager, method
for method in methods:
yield self._test_ServicesPerms, method
| 36.855556 | 78 | 0.609587 | from helper import CompatTestCase
from validator.chromemanifest import ChromeManifest
from validator.compat import FX42_DEFINITION
from validator.errorbundler import ErrorBundle
from validator.testcases import content
class TestFX42Compat(CompatTestCase):
VERSION = FX42_DEFINITION
def test_parseContentType(self):
self.run_script_for_compat("""
var netutil = Components
.classes["@mozilla.org/network/util;1"]
.getService(Components.interfaces.nsINetUtil);
netutil.parseContentType('text/html', 'utf-8', {});
""")
self.assert_compat_error()
def test_newTab_xul(self):
err = ErrorBundle()
assert content.test_newTab_xul(err, None) is None
err.save_resource('chrome.manifest',
ChromeManifest('foo bar', 'chrome.manifest'))
content.test_newTab_xul(err, None)
assert not err.failed()
err.save_resource(
'chrome.manifest',
ChromeManifest(
('overlay chrome://browser/content/newtab/newTab.xul '
'chrome://ch/content/newtab/index.xul'),
'chrome.manifest'))
content.test_newTab_xul(err, None)
assert err.failed()
assert not err.errors
assert len(err.warnings) == 1
assert err.warnings[0]['compatibility_type'] == 'error'
def test_mozRequestAnimationFrame(self):
self.run_script_for_compat("""
// Don't flag comments: window.mozRequestAnimationFrame()
window.requestAnimationFrame();
""")
assert not self.compat_err.errors
assert not self.compat_err.warnings
self.run_script_for_compat("""
window.mozRequestAnimationFrame();
""")
self.assert_compat_error()
def _test_nsIPermissionManager(self, method):
self.run_script_for_compat("""
var perms = Cc["@mozilla.org/permissionmanager;1"]
.getService(Ci.nsIPermissionManager);
%s
""" % method)
self.assert_compat_error()
def _test_ServicesPerms(self, method):
self.run_script_for_compat("""
Components.utils.import("resource://gre/modules/Services.jsm");
var perms = Services.perms;
%s
""" % method)
self.assert_compat_error()
def test_nsIPermissionManagerMethods(self):
methods = ("perms.add(url, 'cookie', 1);",
"perms.addFromPrincipal(url, 'cookie', 1);",
"perms.remove('yahoo.com', 'cookie');",
"perms.removeFromPrincipal('yahoo.com', 'cookie');",
"perms.removeAll();",
"perms.testExactPermission(url, cookie);"
"perms.testExactPermissionFromPrincipal(url, cookie);",
"perms.testPermission(url, cookie);",
"perms.testPermissionFromPrincipal(url, cookie);")
for method in methods:
yield self._test_nsIPermissionManager, method
for method in methods:
yield self._test_ServicesPerms, method
| true | true |
f7f8bdcc7fcb5863849a2cc23f70fcb47ff4fba7 | 1,316 | py | Python | src/sage/combinat/posets/all.py | UCD4IDS/sage | 43474c96d533fd396fe29fe0782d44dc7f5164f7 | [
"BSL-1.0"
] | 1,742 | 2015-01-04T07:06:13.000Z | 2022-03-30T11:32:52.000Z | src/sage/combinat/posets/all.py | UCD4IDS/sage | 43474c96d533fd396fe29fe0782d44dc7f5164f7 | [
"BSL-1.0"
] | 66 | 2015-03-19T19:17:24.000Z | 2022-03-16T11:59:30.000Z | src/sage/combinat/posets/all.py | UCD4IDS/sage | 43474c96d533fd396fe29fe0782d44dc7f5164f7 | [
"BSL-1.0"
] | 495 | 2015-01-10T10:23:18.000Z | 2022-03-24T22:06:11.000Z | r"""
Posets
Common posets can be accessed through ``posets.<tab>`` and are listed in the
posets catalog:
- :ref:`Catalog of posets and lattices <sage.combinat.posets.poset_examples>`
Poset-related classes:
- :ref:`sage.combinat.posets.posets`
- :ref:`sage.combinat.posets.lattices`
- :ref:`sage.combinat.posets.linear_extensions`
- :ref:`sage.combinat.posets.d_complete`
- :ref:`sage.combinat.posets.forest`
- :ref:`sage.combinat.posets.mobile`
- :ref:`sage.combinat.posets.incidence_algebras`
- :ref:`sage.combinat.posets.cartesian_product`
- :ref:`sage.combinat.posets.moebius_algebra`
- :ref:`sage.combinat.tamari_lattices`
- :ref:`sage.combinat.interval_posets`
- :ref:`sage.combinat.shard_order`
If you are looking for Poset-related :mod:`categories
<sage.categories.category>`, see
:class:`~sage.categories.posets.Posets`,
:class:`~sage.categories.finite_posets.FinitePosets`,
:class:`~sage.categories.lattice_posets.LatticePosets` and
:class:`~sage.categories.finite_lattice_posets.FiniteLatticePosets`.
"""
# install the docstring of this module to the containing package
from sage.misc.namespace_package import install_doc
install_doc(__package__, __doc__)
from .posets import Poset
from .lattices import LatticePoset, MeetSemilattice, JoinSemilattice
from .poset_examples import posets, Posets
| 29.909091 | 77 | 0.784195 |
from sage.misc.namespace_package import install_doc
install_doc(__package__, __doc__)
from .posets import Poset
from .lattices import LatticePoset, MeetSemilattice, JoinSemilattice
from .poset_examples import posets, Posets
| true | true |
f7f8be728eeb09194cffabc3e87854db1a2d9bad | 10,905 | py | Python | qa/pull-tester/rpc-tests.py | ctwiz/stardust | 0d237784267413e4076ec872e34393d26ad9aa03 | [
"MIT"
] | null | null | null | qa/pull-tester/rpc-tests.py | ctwiz/stardust | 0d237784267413e4076ec872e34393d26ad9aa03 | [
"MIT"
] | null | null | null | qa/pull-tester/rpc-tests.py | ctwiz/stardust | 0d237784267413e4076ec872e34393d26ad9aa03 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Stardust Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
Run Regression Test Suite
This module calls down into individual test cases via subprocess. It will
forward all unrecognized arguments onto the individual test scripts, other
than:
- `-extended`: run the "extended" test suite in addition to the basic one.
- `-win`: signal that this is running in a Windows environment, and we
should run the tests.
- `--coverage`: this generates a basic coverage report for the RPC
interface.
For a description of arguments recognized by test scripts, see
`qa/pull-tester/test_framework/test_framework.py:StardustTestFramework.main`.
"""
import os
import time
import shutil
import sys
import subprocess
import tempfile
import re
sys.path.append("qa/pull-tester/")
from tests_config import *
BOLD = ("","")
if os.name == 'posix':
# primitive formatting on supported
# terminal via ANSI escape sequences:
BOLD = ('\033[0m', '\033[1m')
RPC_TESTS_DIR = SRCDIR + '/qa/rpc-tests/'
#If imported values are not defined then set to zero (or disabled)
if 'ENABLE_WALLET' not in vars():
ENABLE_WALLET=0
if 'ENABLE_STARDUSTD' not in vars():
ENABLE_STARDUSTD=0
if 'ENABLE_UTILS' not in vars():
ENABLE_UTILS=0
if 'ENABLE_ZMQ' not in vars():
ENABLE_ZMQ=0
ENABLE_COVERAGE=0
#Create a set to store arguments and create the passon string
opts = set()
passon_args = []
PASSON_REGEX = re.compile("^--")
PARALLEL_REGEX = re.compile('^-parallel=')
print_help = False
run_parallel = 4
for arg in sys.argv[1:]:
if arg == "--help" or arg == "-h" or arg == "-?":
print_help = True
break
if arg == '--coverage':
ENABLE_COVERAGE = 1
elif PASSON_REGEX.match(arg):
passon_args.append(arg)
elif PARALLEL_REGEX.match(arg):
run_parallel = int(arg.split(sep='=', maxsplit=1)[1])
else:
opts.add(arg)
#Set env vars
if "STARDUSTD" not in os.environ:
os.environ["STARDUSTD"] = BUILDDIR + '/src/stardustd' + EXEEXT
if "STARDUSTCLI" not in os.environ:
os.environ["STARDUSTCLI"] = BUILDDIR + '/src/stardust-cli' + EXEEXT
if EXEEXT == ".exe" and "-win" not in opts:
# https://github.com/stardust/stardust/commit/d52802551752140cf41f0d9a225a43e84404d3e9
# https://github.com/stardust/stardust/pull/5677#issuecomment-136646964
print("Win tests currently disabled by default. Use -win option to enable")
sys.exit(0)
if not (ENABLE_WALLET == 1 and ENABLE_UTILS == 1 and ENABLE_STARDUSTD == 1):
print("No rpc tests to run. Wallet, utils, and stardustd must all be enabled")
sys.exit(0)
# python3-zmq may not be installed. Handle this gracefully and with some helpful info
if ENABLE_ZMQ:
try:
import zmq
except ImportError as e:
print("WARNING: \"import zmq\" failed. Set ENABLE_ZMQ=0 or " \
"to run zmq tests, see dependency info in /qa/README.md.")
ENABLE_ZMQ=0
#Tests
testScripts = [
# longest test should go first, to favor running tests in parallel
'p2p-fullblocktest.py',
'walletbackup.py',
'bip68-112-113-p2p.py',
'wallet.py',
'wallet-hd.py',
'wallet-dump.py',
'listtransactions.py',
'receivedby.py',
'mempool_resurrect_test.py',
'txn_doublespend.py --mineblock',
'txn_clone.py',
'getchaintips.py',
'rawtransactions.py',
'rest.py',
'mempool_spendcoinbase.py',
'mempool_reorg.py',
'mempool_limit.py',
'httpbasics.py',
'multi_rpc.py',
'zapwallettxes.py',
'proxy_test.py',
'merkle_blocks.py',
'fundrawtransaction.py',
'signrawtransactions.py',
'nodehandling.py',
'reindex.py',
'decodescript.py',
'blockchain.py',
'disablewallet.py',
'sendheaders.py',
'keypool.py',
'prioritise_transaction.py',
'invalidblockrequest.py',
'invalidtxrequest.py',
'abandonconflict.py',
'p2p-versionbits-warning.py',
'p2p-segwit.py',
'segwit.py',
'importprunedfunds.py',
'signmessages.py',
'p2p-compactblocks.py',
]
if ENABLE_ZMQ:
testScripts.append('zmq_test.py')
testScriptsExt = [
'bip9-softforks.py',
'bip65-cltv.py',
'bip65-cltv-p2p.py',
'bip68-sequence.py',
'bipdersig-p2p.py',
'bipdersig.py',
'getblocktemplate_longpoll.py',
'getblocktemplate_proposals.py',
'txn_doublespend.py',
'txn_clone.py --mineblock',
'forknotify.py',
'invalidateblock.py',
'rpcbind_test.py',
'smartfees.py',
'maxblocksinflight.py',
'p2p-acceptblock.py',
'mempool_packages.py',
'maxuploadtarget.py',
'replace-by-fee.py',
'p2p-feefilter.py',
'pruning.py', # leave pruning last as it takes a REALLY long time
]
def runtests():
test_list = []
if '-extended' in opts:
test_list = testScripts + testScriptsExt
elif len(opts) == 0 or (len(opts) == 1 and "-win" in opts):
test_list = testScripts
else:
for t in testScripts + testScriptsExt:
if t in opts or re.sub(".py$", "", t) in opts:
test_list.append(t)
if print_help:
# Only print help of the first script and exit
subprocess.check_call((RPC_TESTS_DIR + test_list[0]).split() + ['-h'])
sys.exit(0)
coverage = None
if ENABLE_COVERAGE:
coverage = RPCCoverage()
print("Initializing coverage directory at %s\n" % coverage.dir)
flags = ["--srcdir=%s/src" % BUILDDIR] + passon_args
if coverage:
flags.append(coverage.flag)
if len(test_list) > 1 and run_parallel > 1:
# Populate cache
subprocess.check_output([RPC_TESTS_DIR + 'create_cache.py'] + flags)
#Run Tests
max_len_name = len(max(test_list, key=len))
time_sum = 0
time0 = time.time()
job_queue = RPCTestHandler(run_parallel, test_list, flags)
results = BOLD[1] + "%s | %s | %s\n\n" % ("TEST".ljust(max_len_name), "PASSED", "DURATION") + BOLD[0]
all_passed = True
for _ in range(len(test_list)):
(name, stdout, stderr, passed, duration) = job_queue.get_next()
all_passed = all_passed and passed
time_sum += duration
print('\n' + BOLD[1] + name + BOLD[0] + ":")
print(stdout)
print('stderr:\n' if not stderr == '' else '', stderr)
results += "%s | %s | %s s\n" % (name.ljust(max_len_name), str(passed).ljust(6), duration)
print("Pass: %s%s%s, Duration: %s s\n" % (BOLD[1], passed, BOLD[0], duration))
results += BOLD[1] + "\n%s | %s | %s s (accumulated)" % ("ALL".ljust(max_len_name), str(all_passed).ljust(6), time_sum) + BOLD[0]
print(results)
print("\nRuntime: %s s" % (int(time.time() - time0)))
if coverage:
coverage.report_rpc_coverage()
print("Cleaning up coverage data")
coverage.cleanup()
sys.exit(not all_passed)
class RPCTestHandler:
"""
Trigger the testscrips passed in via the list.
"""
def __init__(self, num_tests_parallel, test_list=None, flags=None):
assert(num_tests_parallel >= 1)
self.num_jobs = num_tests_parallel
self.test_list = test_list
self.flags = flags
self.num_running = 0
self.jobs = []
def get_next(self):
while self.num_running < self.num_jobs and self.test_list:
# Add tests
self.num_running += 1
t = self.test_list.pop(0)
port_seed = ["--portseed=%s" % len(self.test_list)]
self.jobs.append((t,
time.time(),
subprocess.Popen((RPC_TESTS_DIR + t).split() + self.flags + port_seed,
universal_newlines=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)))
if not self.jobs:
raise IndexError('pop from empty list')
while True:
# Return first proc that finishes
time.sleep(.5)
for j in self.jobs:
(name, time0, proc) = j
if proc.poll() is not None:
(stdout, stderr) = proc.communicate(timeout=3)
passed = stderr == "" and proc.returncode == 0
self.num_running -= 1
self.jobs.remove(j)
return name, stdout, stderr, passed, int(time.time() - time0)
print('.', end='', flush=True)
class RPCCoverage(object):
"""
Coverage reporting utilities for pull-tester.
Coverage calculation works by having each test script subprocess write
coverage files into a particular directory. These files contain the RPC
commands invoked during testing, as well as a complete listing of RPC
commands per `stardust-cli help` (`rpc_interface.txt`).
After all tests complete, the commands run are combined and diff'd against
the complete list to calculate uncovered RPC commands.
See also: qa/rpc-tests/test_framework/coverage.py
"""
def __init__(self):
self.dir = tempfile.mkdtemp(prefix="coverage")
self.flag = '--coveragedir=%s' % self.dir
def report_rpc_coverage(self):
"""
Print out RPC commands that were unexercised by tests.
"""
uncovered = self._get_uncovered_rpc_commands()
if uncovered:
print("Uncovered RPC commands:")
print("".join((" - %s\n" % i) for i in sorted(uncovered)))
else:
print("All RPC commands covered.")
def cleanup(self):
return shutil.rmtree(self.dir)
def _get_uncovered_rpc_commands(self):
"""
Return a set of currently untested RPC commands.
"""
# This is shared from `qa/rpc-tests/test-framework/coverage.py`
REFERENCE_FILENAME = 'rpc_interface.txt'
COVERAGE_FILE_PREFIX = 'coverage.'
coverage_ref_filename = os.path.join(self.dir, REFERENCE_FILENAME)
coverage_filenames = set()
all_cmds = set()
covered_cmds = set()
if not os.path.isfile(coverage_ref_filename):
raise RuntimeError("No coverage reference found")
with open(coverage_ref_filename, 'r') as f:
all_cmds.update([i.strip() for i in f.readlines()])
for root, dirs, files in os.walk(self.dir):
for filename in files:
if filename.startswith(COVERAGE_FILE_PREFIX):
coverage_filenames.add(os.path.join(root, filename))
for filename in coverage_filenames:
with open(filename, 'r') as f:
covered_cmds.update([i.strip() for i in f.readlines()])
return all_cmds - covered_cmds
if __name__ == '__main__':
runtests()
| 31.700581 | 133 | 0.6221 |
import os
import time
import shutil
import sys
import subprocess
import tempfile
import re
sys.path.append("qa/pull-tester/")
from tests_config import *
BOLD = ("","")
if os.name == 'posix':
BOLD = ('\033[0m', '\033[1m')
RPC_TESTS_DIR = SRCDIR + '/qa/rpc-tests/'
if 'ENABLE_WALLET' not in vars():
ENABLE_WALLET=0
if 'ENABLE_STARDUSTD' not in vars():
ENABLE_STARDUSTD=0
if 'ENABLE_UTILS' not in vars():
ENABLE_UTILS=0
if 'ENABLE_ZMQ' not in vars():
ENABLE_ZMQ=0
ENABLE_COVERAGE=0
opts = set()
passon_args = []
PASSON_REGEX = re.compile("^--")
PARALLEL_REGEX = re.compile('^-parallel=')
print_help = False
run_parallel = 4
for arg in sys.argv[1:]:
if arg == "--help" or arg == "-h" or arg == "-?":
print_help = True
break
if arg == '--coverage':
ENABLE_COVERAGE = 1
elif PASSON_REGEX.match(arg):
passon_args.append(arg)
elif PARALLEL_REGEX.match(arg):
run_parallel = int(arg.split(sep='=', maxsplit=1)[1])
else:
opts.add(arg)
if "STARDUSTD" not in os.environ:
os.environ["STARDUSTD"] = BUILDDIR + '/src/stardustd' + EXEEXT
if "STARDUSTCLI" not in os.environ:
os.environ["STARDUSTCLI"] = BUILDDIR + '/src/stardust-cli' + EXEEXT
if EXEEXT == ".exe" and "-win" not in opts:
urrently disabled by default. Use -win option to enable")
sys.exit(0)
if not (ENABLE_WALLET == 1 and ENABLE_UTILS == 1 and ENABLE_STARDUSTD == 1):
print("No rpc tests to run. Wallet, utils, and stardustd must all be enabled")
sys.exit(0)
if ENABLE_ZMQ:
try:
import zmq
except ImportError as e:
print("WARNING: \"import zmq\" failed. Set ENABLE_ZMQ=0 or " \
"to run zmq tests, see dependency info in /qa/README.md.")
ENABLE_ZMQ=0
testScripts = [
'p2p-fullblocktest.py',
'walletbackup.py',
'bip68-112-113-p2p.py',
'wallet.py',
'wallet-hd.py',
'wallet-dump.py',
'listtransactions.py',
'receivedby.py',
'mempool_resurrect_test.py',
'txn_doublespend.py --mineblock',
'txn_clone.py',
'getchaintips.py',
'rawtransactions.py',
'rest.py',
'mempool_spendcoinbase.py',
'mempool_reorg.py',
'mempool_limit.py',
'httpbasics.py',
'multi_rpc.py',
'zapwallettxes.py',
'proxy_test.py',
'merkle_blocks.py',
'fundrawtransaction.py',
'signrawtransactions.py',
'nodehandling.py',
'reindex.py',
'decodescript.py',
'blockchain.py',
'disablewallet.py',
'sendheaders.py',
'keypool.py',
'prioritise_transaction.py',
'invalidblockrequest.py',
'invalidtxrequest.py',
'abandonconflict.py',
'p2p-versionbits-warning.py',
'p2p-segwit.py',
'segwit.py',
'importprunedfunds.py',
'signmessages.py',
'p2p-compactblocks.py',
]
if ENABLE_ZMQ:
testScripts.append('zmq_test.py')
testScriptsExt = [
'bip9-softforks.py',
'bip65-cltv.py',
'bip65-cltv-p2p.py',
'bip68-sequence.py',
'bipdersig-p2p.py',
'bipdersig.py',
'getblocktemplate_longpoll.py',
'getblocktemplate_proposals.py',
'txn_doublespend.py',
'txn_clone.py --mineblock',
'forknotify.py',
'invalidateblock.py',
'rpcbind_test.py',
'smartfees.py',
'maxblocksinflight.py',
'p2p-acceptblock.py',
'mempool_packages.py',
'maxuploadtarget.py',
'replace-by-fee.py',
'p2p-feefilter.py',
'pruning.py',
]
def runtests():
test_list = []
if '-extended' in opts:
test_list = testScripts + testScriptsExt
elif len(opts) == 0 or (len(opts) == 1 and "-win" in opts):
test_list = testScripts
else:
for t in testScripts + testScriptsExt:
if t in opts or re.sub(".py$", "", t) in opts:
test_list.append(t)
if print_help:
subprocess.check_call((RPC_TESTS_DIR + test_list[0]).split() + ['-h'])
sys.exit(0)
coverage = None
if ENABLE_COVERAGE:
coverage = RPCCoverage()
print("Initializing coverage directory at %s\n" % coverage.dir)
flags = ["--srcdir=%s/src" % BUILDDIR] + passon_args
if coverage:
flags.append(coverage.flag)
if len(test_list) > 1 and run_parallel > 1:
subprocess.check_output([RPC_TESTS_DIR + 'create_cache.py'] + flags)
max_len_name = len(max(test_list, key=len))
time_sum = 0
time0 = time.time()
job_queue = RPCTestHandler(run_parallel, test_list, flags)
results = BOLD[1] + "%s | %s | %s\n\n" % ("TEST".ljust(max_len_name), "PASSED", "DURATION") + BOLD[0]
all_passed = True
for _ in range(len(test_list)):
(name, stdout, stderr, passed, duration) = job_queue.get_next()
all_passed = all_passed and passed
time_sum += duration
print('\n' + BOLD[1] + name + BOLD[0] + ":")
print(stdout)
print('stderr:\n' if not stderr == '' else '', stderr)
results += "%s | %s | %s s\n" % (name.ljust(max_len_name), str(passed).ljust(6), duration)
print("Pass: %s%s%s, Duration: %s s\n" % (BOLD[1], passed, BOLD[0], duration))
results += BOLD[1] + "\n%s | %s | %s s (accumulated)" % ("ALL".ljust(max_len_name), str(all_passed).ljust(6), time_sum) + BOLD[0]
print(results)
print("\nRuntime: %s s" % (int(time.time() - time0)))
if coverage:
coverage.report_rpc_coverage()
print("Cleaning up coverage data")
coverage.cleanup()
sys.exit(not all_passed)
class RPCTestHandler:
def __init__(self, num_tests_parallel, test_list=None, flags=None):
assert(num_tests_parallel >= 1)
self.num_jobs = num_tests_parallel
self.test_list = test_list
self.flags = flags
self.num_running = 0
self.jobs = []
def get_next(self):
while self.num_running < self.num_jobs and self.test_list:
self.num_running += 1
t = self.test_list.pop(0)
port_seed = ["--portseed=%s" % len(self.test_list)]
self.jobs.append((t,
time.time(),
subprocess.Popen((RPC_TESTS_DIR + t).split() + self.flags + port_seed,
universal_newlines=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)))
if not self.jobs:
raise IndexError('pop from empty list')
while True:
time.sleep(.5)
for j in self.jobs:
(name, time0, proc) = j
if proc.poll() is not None:
(stdout, stderr) = proc.communicate(timeout=3)
passed = stderr == "" and proc.returncode == 0
self.num_running -= 1
self.jobs.remove(j)
return name, stdout, stderr, passed, int(time.time() - time0)
print('.', end='', flush=True)
class RPCCoverage(object):
def __init__(self):
self.dir = tempfile.mkdtemp(prefix="coverage")
self.flag = '--coveragedir=%s' % self.dir
def report_rpc_coverage(self):
uncovered = self._get_uncovered_rpc_commands()
if uncovered:
print("Uncovered RPC commands:")
print("".join((" - %s\n" % i) for i in sorted(uncovered)))
else:
print("All RPC commands covered.")
def cleanup(self):
return shutil.rmtree(self.dir)
def _get_uncovered_rpc_commands(self):
REFERENCE_FILENAME = 'rpc_interface.txt'
COVERAGE_FILE_PREFIX = 'coverage.'
coverage_ref_filename = os.path.join(self.dir, REFERENCE_FILENAME)
coverage_filenames = set()
all_cmds = set()
covered_cmds = set()
if not os.path.isfile(coverage_ref_filename):
raise RuntimeError("No coverage reference found")
with open(coverage_ref_filename, 'r') as f:
all_cmds.update([i.strip() for i in f.readlines()])
for root, dirs, files in os.walk(self.dir):
for filename in files:
if filename.startswith(COVERAGE_FILE_PREFIX):
coverage_filenames.add(os.path.join(root, filename))
for filename in coverage_filenames:
with open(filename, 'r') as f:
covered_cmds.update([i.strip() for i in f.readlines()])
return all_cmds - covered_cmds
if __name__ == '__main__':
runtests()
| true | true |
f7f8be9d8015dfeda464d09109d65cc93cb2aef8 | 4,661 | py | Python | preprocessing/smri/extract_freesurfer_metrics.py | GalBenZvi/BrainPrint | 8dda22f130f60bac66fe05f0f5163ee3680616f5 | [
"Apache-2.0"
] | null | null | null | preprocessing/smri/extract_freesurfer_metrics.py | GalBenZvi/BrainPrint | 8dda22f130f60bac66fe05f0f5163ee3680616f5 | [
"Apache-2.0"
] | 1 | 2021-08-12T07:54:37.000Z | 2021-08-12T07:54:37.000Z | preprocessing/smri/extract_freesurfer_metrics.py | GalBenZvi/BrainPrint | 8dda22f130f60bac66fe05f0f5163ee3680616f5 | [
"Apache-2.0"
] | 1 | 2021-08-08T11:56:19.000Z | 2021-08-08T11:56:19.000Z | import os
from nipype.interfaces import ants
from pathlib import Path
from numpy import fabs
from pandas.core.reshape.merge import merge
def get_subject_files(derivatives_dir: Path, subj_id: str) -> dict:
"""
Finds subject's relevant files as were derived from FS's analysis pipeline
Parameters
----------
derivatives_dir : Path
Path to main derivatives directory (underwhich there will be "freesurfer" and "fmriprep" subdirectories)
subj_id : str
Subject's identifier (sub-xxx)
Returns
-------
dict
A dictionary with keys representing relevant files
"""
subj_dict = {}
for hemi in ["lh", "rh"]:
for val in ["thickness", "volume", "sulc", "white"]:
subj_dict[f"{hemi}_{val}"] = (
derivatives_dir
/ "freesurfer"
/ subj_id
/ "surf"
/ f"{hemi}.{val}"
)
subj_dict["ribbon"] = (
derivatives_dir / "freesurfer" / subj_id / "mri" / "ribbon.mgz"
)
anat_dir = derivatives_dir / "fmriprep" / subj_id / "anat"
if anat_dir.exists():
subj_dict["FS_transform"] = (
anat_dir / f"{subj_id}_from-fsnative_to-T1w_mode-image_xfm.txt"
)
subj_dict["anat"] = anat_dir / f"{subj_id}_desc-preproc_T1w.nii.gz"
subj_dict["output_dir"] = anat_dir
else:
session = [
ses.name
for ses in derivatives_dir.glob(f"fmriprep/{subj_id}/ses-*")
][0]
anat_dir = derivatives_dir / "fmriprep" / subj_id / session / "anat"
subj_dict["FS_transform"] = (
anat_dir
/ f"{subj_id}_{session}_from-fsnative_to-T1w_mode-image_xfm.txt"
)
subj_dict["anat"] = (
anat_dir / f"{subj_id}_{session}_desc-preproc_T1w.nii.gz"
)
subj_dict["output_dir"] = anat_dir
to_process = True
flags = [val.exists() for val in subj_dict.values()]
if not all(flags):
print(f"Couldn't find neccesary files for {subj_id}:")
for key, val in subj_dict.items():
if not val.exists():
print(key)
to_process = False
return subj_dict, to_process
def surface_to_volume(subj_dict: dict, subj_id: str) -> dict:
"""
Utilizes Freesurfer's mri_surf2vol to transfrom the parametric surface to volumes in subject's space
Parameters
----------
subj_dict : dict
[description]
Returns
-------
dict
[description]
"""
ribbon = subj_dict.get("ribbon")
out_dir = ribbon.parent
for metric in ["thickness", "volume", "sulc"]:
out_file = out_dir / f"{subj_id}_{metric}.nii.gz"
subj_dict[f"FS_{metric}"] = out_file
if out_file.exists():
continue
cmd = f"mri_surf2vol --o {out_file}"
for hemi in ["lh", "rh"]:
white, val = [
subj_dict.get(f"{hemi}_{val}") for val in ["white", metric]
]
cmd += f" --so {white} {val}"
cmd += f" --ribbon {ribbon}"
print(cmd)
os.system(cmd)
return subj_dict
def transform_coords(subj_dict: dict, subj_id: str) -> dict:
"""
Utilizes ANTs' ApplyTransforms to transform metrics' images to "MNI" coordinates
Parameters
----------
subj_dict : dict
[description]
subj_id : str
[description]
Returns
-------
dict
[description]
"""
out_dir, aff, ref = [
subj_dict.get(key) for key in ["output_dir", "FS_transform", "anat"]
]
for metric in ["thickness", "volume", "sulc"]:
input_image = subj_dict.get(f"FS_{metric}")
out_file = out_dir / f"{subj_id}_{metric}.nii.gz"
subj_dict[metric] = out_file
if out_file.exists():
continue
at = ants.ApplyTransforms()
at.inputs.input_image = str(input_image)
at.inputs.reference_image = str(ref)
at.inputs.transforms = str(aff)
at.inputs.output_image = str(out_file)
print(at.cmdline)
at.run()
return subj_dict
if __name__ == "__main__":
derivatives_dir = Path("/media/groot/Yalla/media/MRI/derivatives")
subjects = sorted(
[d.name for d in derivatives_dir.glob("fmriprep/sub-*") if d.is_dir()]
)
for subj in subjects:
try:
subj_dict, to_process = get_subject_files(derivatives_dir, subj)
if not to_process:
continue
subj_dict = surface_to_volume(subj_dict, subj)
subj_dict = transform_coords(subj_dict, subj)
except:
continue
# break
| 31.073333 | 112 | 0.576057 | import os
from nipype.interfaces import ants
from pathlib import Path
from numpy import fabs
from pandas.core.reshape.merge import merge
def get_subject_files(derivatives_dir: Path, subj_id: str) -> dict:
subj_dict = {}
for hemi in ["lh", "rh"]:
for val in ["thickness", "volume", "sulc", "white"]:
subj_dict[f"{hemi}_{val}"] = (
derivatives_dir
/ "freesurfer"
/ subj_id
/ "surf"
/ f"{hemi}.{val}"
)
subj_dict["ribbon"] = (
derivatives_dir / "freesurfer" / subj_id / "mri" / "ribbon.mgz"
)
anat_dir = derivatives_dir / "fmriprep" / subj_id / "anat"
if anat_dir.exists():
subj_dict["FS_transform"] = (
anat_dir / f"{subj_id}_from-fsnative_to-T1w_mode-image_xfm.txt"
)
subj_dict["anat"] = anat_dir / f"{subj_id}_desc-preproc_T1w.nii.gz"
subj_dict["output_dir"] = anat_dir
else:
session = [
ses.name
for ses in derivatives_dir.glob(f"fmriprep/{subj_id}/ses-*")
][0]
anat_dir = derivatives_dir / "fmriprep" / subj_id / session / "anat"
subj_dict["FS_transform"] = (
anat_dir
/ f"{subj_id}_{session}_from-fsnative_to-T1w_mode-image_xfm.txt"
)
subj_dict["anat"] = (
anat_dir / f"{subj_id}_{session}_desc-preproc_T1w.nii.gz"
)
subj_dict["output_dir"] = anat_dir
to_process = True
flags = [val.exists() for val in subj_dict.values()]
if not all(flags):
print(f"Couldn't find neccesary files for {subj_id}:")
for key, val in subj_dict.items():
if not val.exists():
print(key)
to_process = False
return subj_dict, to_process
def surface_to_volume(subj_dict: dict, subj_id: str) -> dict:
ribbon = subj_dict.get("ribbon")
out_dir = ribbon.parent
for metric in ["thickness", "volume", "sulc"]:
out_file = out_dir / f"{subj_id}_{metric}.nii.gz"
subj_dict[f"FS_{metric}"] = out_file
if out_file.exists():
continue
cmd = f"mri_surf2vol --o {out_file}"
for hemi in ["lh", "rh"]:
white, val = [
subj_dict.get(f"{hemi}_{val}") for val in ["white", metric]
]
cmd += f" --so {white} {val}"
cmd += f" --ribbon {ribbon}"
print(cmd)
os.system(cmd)
return subj_dict
def transform_coords(subj_dict: dict, subj_id: str) -> dict:
out_dir, aff, ref = [
subj_dict.get(key) for key in ["output_dir", "FS_transform", "anat"]
]
for metric in ["thickness", "volume", "sulc"]:
input_image = subj_dict.get(f"FS_{metric}")
out_file = out_dir / f"{subj_id}_{metric}.nii.gz"
subj_dict[metric] = out_file
if out_file.exists():
continue
at = ants.ApplyTransforms()
at.inputs.input_image = str(input_image)
at.inputs.reference_image = str(ref)
at.inputs.transforms = str(aff)
at.inputs.output_image = str(out_file)
print(at.cmdline)
at.run()
return subj_dict
if __name__ == "__main__":
derivatives_dir = Path("/media/groot/Yalla/media/MRI/derivatives")
subjects = sorted(
[d.name for d in derivatives_dir.glob("fmriprep/sub-*") if d.is_dir()]
)
for subj in subjects:
try:
subj_dict, to_process = get_subject_files(derivatives_dir, subj)
if not to_process:
continue
subj_dict = surface_to_volume(subj_dict, subj)
subj_dict = transform_coords(subj_dict, subj)
except:
continue
# break
| true | true |
f7f8c08eefc0a72cb6b1ce655d87dbecc1b7c1f1 | 1,819 | py | Python | bonder/check.py | gkrizek/bond | c87d81fca09b056167e8f0a2db63b1338b9c7622 | [
"Apache-2.0"
] | null | null | null | bonder/check.py | gkrizek/bond | c87d81fca09b056167e8f0a2db63b1338b9c7622 | [
"Apache-2.0"
] | null | null | null | bonder/check.py | gkrizek/bond | c87d81fca09b056167e8f0a2db63b1338b9c7622 | [
"Apache-2.0"
] | null | null | null | import click
import json
import subprocess
from sys import exit
def get_unbonded_atom(address):
try:
process = subprocess.check_output("gaiacli account %s" % (address), shell=True, stderr=subprocess.STDOUT)
return {
"success": True,
"output": json.loads(process)
}
except subprocess.CalledProcessError as err:
return {
"success": False,
"output": err.output
}
def bond_steak(address_validator, name, steak, chain_id):
try:
process = subprocess.check_output("gaiacli stake delegate --amount=%s --address-validator=%s --name=%s --chain-id=%s" % (steak, address_validator, name, chain_id), shell=True, stderr=subprocess.STDOUT)
return {
"success": True,
"output": process
}
except subprocess.CalledProcessError as err:
return {
"success": False,
"output": err.output
}
def check_bonder(address, address_validator, chain_id, name, verbose):
if verbose:
click.echo("Checking for address %s" % (address))
account = get_unbonded_atom(address)
if not account['success']:
click.secho("Error getting account information:", fg="red", bold=True)
print(account)
exit(1)
coin_list = account['output']['value']['coins']
for c in coin_list:
if c['denom'] == 'steak':
steak = c['amount']
if verbose:
click.echo("Found %s steak" %(steak))
if steak > 0:
bond = bond_steak(name, address, steak, chain_id)
if not bond['success']:
click.secho("Error bonding steak:", fg="red", bold=True)
print(bond)
exit(1)
click.echo("Successfully bonded %s steak:" % (steak))
print(bond)
return
| 30.316667 | 209 | 0.592084 | import click
import json
import subprocess
from sys import exit
def get_unbonded_atom(address):
try:
process = subprocess.check_output("gaiacli account %s" % (address), shell=True, stderr=subprocess.STDOUT)
return {
"success": True,
"output": json.loads(process)
}
except subprocess.CalledProcessError as err:
return {
"success": False,
"output": err.output
}
def bond_steak(address_validator, name, steak, chain_id):
try:
process = subprocess.check_output("gaiacli stake delegate --amount=%s --address-validator=%s --name=%s --chain-id=%s" % (steak, address_validator, name, chain_id), shell=True, stderr=subprocess.STDOUT)
return {
"success": True,
"output": process
}
except subprocess.CalledProcessError as err:
return {
"success": False,
"output": err.output
}
def check_bonder(address, address_validator, chain_id, name, verbose):
if verbose:
click.echo("Checking for address %s" % (address))
account = get_unbonded_atom(address)
if not account['success']:
click.secho("Error getting account information:", fg="red", bold=True)
print(account)
exit(1)
coin_list = account['output']['value']['coins']
for c in coin_list:
if c['denom'] == 'steak':
steak = c['amount']
if verbose:
click.echo("Found %s steak" %(steak))
if steak > 0:
bond = bond_steak(name, address, steak, chain_id)
if not bond['success']:
click.secho("Error bonding steak:", fg="red", bold=True)
print(bond)
exit(1)
click.echo("Successfully bonded %s steak:" % (steak))
print(bond)
return
| true | true |
f7f8c12eab068c39089ac9ba3ac96405e0a06111 | 6,224 | py | Python | tests/profiler/tensorflow2/test_native_tf2_profiler.py | mchoi8739/sagemaker-debugger | fcc02366d06308642cf96b17aae417db9c1192d5 | [
"Apache-2.0"
] | 2 | 2020-07-28T22:04:02.000Z | 2020-07-31T06:27:35.000Z | tests/profiler/tensorflow2/test_native_tf2_profiler.py | mchoi8739/sagemaker-debugger | fcc02366d06308642cf96b17aae417db9c1192d5 | [
"Apache-2.0"
] | null | null | null | tests/profiler/tensorflow2/test_native_tf2_profiler.py | mchoi8739/sagemaker-debugger | fcc02366d06308642cf96b17aae417db9c1192d5 | [
"Apache-2.0"
] | null | null | null | # Standard Library
import os
# Third Party
import pytest
import tensorflow as tf
from tests.profiler.core.utils import validate_python_profiling_stats
from tests.tensorflow2.utils import ModelType
# First Party
import smdebug.tensorflow as smd
from smdebug.core.collection import CollectionKeys
from smdebug.core.utils import FRAMEWORK
from smdebug.profiler.profiler_config_parser import ProfilerConfigParser
from smdebug.profiler.profiler_constants import (
CPROFILE_NAME,
CPROFILE_STATS_FILENAME,
PYINSTRUMENT_HTML_FILENAME,
PYINSTRUMENT_JSON_FILENAME,
PYINSTRUMENT_NAME,
)
from smdebug.profiler.python_profile_utils import StepPhase
from smdebug.tensorflow import KerasHook as Hook
@pytest.fixture
def native_tf2_cprofile_profiler_config_parser(config_folder, monkeypatch):
config_path = os.path.join(
config_folder, "test_native_tf2_cprofile_profiler_config_parser.json"
)
monkeypatch.setenv("SMPROFILER_CONFIG_PATH", config_path)
return ProfilerConfigParser(FRAMEWORK.TENSORFLOW)
@pytest.fixture
def native_tf2_pyinstrument_profiler_config_parser(config_folder, monkeypatch):
config_path = os.path.join(
config_folder, "test_native_tf2_pyinstrument_profiler_config_parser.json"
)
monkeypatch.setenv("SMPROFILER_CONFIG_PATH", config_path)
return ProfilerConfigParser(FRAMEWORK.TENSORFLOW)
def _helper_native_tf2_gradtape(out_dir, model, dataset, profiler_config_parser):
def get_grads(images, labels):
return model(images, training=True)
@tf.function
def train_step(images, labels):
return tf.reduce_mean(get_grads(images, labels))
hook = Hook(out_dir=out_dir, save_all=True)
# Known issue where logging in a python callback function (i.e. atexit) during pytest causes logging errors.
# See https://github.com/pytest-dev/pytest/issues/5502 for more information.
hook.logger.disabled = True
hook.profiler_config_parser = profiler_config_parser
start_step = profiler_config_parser.config.python_profiling_config.start_step
end_step = start_step + profiler_config_parser.config.python_profiling_config.num_steps
opt = tf.keras.optimizers.Adam()
hook.wrap_optimizer(opt)
for current_step, (data, labels) in enumerate(dataset):
with hook.profiler():
labels = tf.one_hot(labels, depth=10)
with tf.GradientTape() as tape:
logits = train_step(data, labels)
if start_step <= current_step < end_step:
assert profiler_config_parser.python_profiler._start_step == current_step
assert (
profiler_config_parser.python_profiler._start_phase == StepPhase.STEP_START
)
grads = tape.gradient(logits, model.variables)
opt.apply_gradients(zip(grads, model.variables))
hook.save_tensor("inputs", data, CollectionKeys.INPUTS)
hook.save_tensor("logits", logits, CollectionKeys.OUTPUTS)
hook.save_tensor("labels", labels, CollectionKeys.OUTPUTS)
if start_step <= current_step < end_step:
assert profiler_config_parser.python_profiler._start_step == current_step
assert profiler_config_parser.python_profiler._start_phase == StepPhase.STEP_END
# required for these tests since this normally gets called in the cleanup process and we need to stop any ongoing
# profiling and collect post-hook-close Python profiling stats
hook.profiling_end()
def _verify_tensor_names(out_dir):
"""
This verifies the tensor names when debugger is enabled.
"""
trial = smd.create_trial(out_dir)
assert len(trial.steps()) > 0, "Nothing saved at any step."
assert len(trial.tensor_names()) > 0, "Tensors were not saved."
assert trial.tensor_names(collection=CollectionKeys.LOSSES) == ["loss"]
assert len(trial.tensor_names(collection=CollectionKeys.WEIGHTS)) > 0
assert len(trial.tensor_names(collection=CollectionKeys.BIASES)) > 0
assert trial.tensor_names(collection="optimizer_variables") == [
"Adam/beta_1:0",
"Adam/beta_2:0",
"Adam/decay:0",
"Adam/iter:0",
"Adam/learning_rate:0",
]
assert trial.tensor_names(collection=CollectionKeys.INPUTS) == ["inputs"]
assert trial.tensor_names(collection=CollectionKeys.OUTPUTS) == ["labels", "logits"]
@pytest.mark.parametrize("python_profiler_name", [CPROFILE_NAME, PYINSTRUMENT_NAME])
@pytest.mark.parametrize(
"model_type", [ModelType.SEQUENTIAL, ModelType.FUNCTIONAL, ModelType.SUBCLASSED]
)
def test_native_tf2_profiling(
python_profiler_name,
model_type,
tf2_mnist_sequential_model,
tf2_mnist_functional_model,
tf2_mnist_subclassed_model,
native_tf2_cprofile_profiler_config_parser,
native_tf2_pyinstrument_profiler_config_parser,
out_dir,
mnist_dataset,
tf_eager_mode,
):
if model_type == ModelType.SEQUENTIAL:
model = tf2_mnist_sequential_model
elif model_type == ModelType.FUNCTIONAL:
model = tf2_mnist_functional_model
else:
model = tf2_mnist_subclassed_model
if python_profiler_name == CPROFILE_NAME:
profiler_config_parser = native_tf2_cprofile_profiler_config_parser
else:
profiler_config_parser = native_tf2_pyinstrument_profiler_config_parser
assert profiler_config_parser.profiling_enabled
profiler_config_parser.load_config()
profiler_config_parser.start_pre_step_zero_python_profiling()
_helper_native_tf2_gradtape(out_dir, model, mnist_dataset, profiler_config_parser)
# Sanity check debugger output
_verify_tensor_names(out_dir)
# The expected number of stats directories during is (num_steps * 2) + 2. This includes profiling for both
# phases of each step and pre-step zero python profiling and post-hook-close python profiling.
expected_stats_dir_count = (
profiler_config_parser.config.python_profiling_config.num_steps * 2
) + 2
python_stats_dir = os.path.join(out_dir, "framework", "tensorflow", python_profiler_name)
validate_python_profiling_stats(
python_stats_dir, python_profiler_name, expected_stats_dir_count
)
| 39.643312 | 117 | 0.746465 |
import os
import pytest
import tensorflow as tf
from tests.profiler.core.utils import validate_python_profiling_stats
from tests.tensorflow2.utils import ModelType
import smdebug.tensorflow as smd
from smdebug.core.collection import CollectionKeys
from smdebug.core.utils import FRAMEWORK
from smdebug.profiler.profiler_config_parser import ProfilerConfigParser
from smdebug.profiler.profiler_constants import (
CPROFILE_NAME,
CPROFILE_STATS_FILENAME,
PYINSTRUMENT_HTML_FILENAME,
PYINSTRUMENT_JSON_FILENAME,
PYINSTRUMENT_NAME,
)
from smdebug.profiler.python_profile_utils import StepPhase
from smdebug.tensorflow import KerasHook as Hook
@pytest.fixture
def native_tf2_cprofile_profiler_config_parser(config_folder, monkeypatch):
config_path = os.path.join(
config_folder, "test_native_tf2_cprofile_profiler_config_parser.json"
)
monkeypatch.setenv("SMPROFILER_CONFIG_PATH", config_path)
return ProfilerConfigParser(FRAMEWORK.TENSORFLOW)
@pytest.fixture
def native_tf2_pyinstrument_profiler_config_parser(config_folder, monkeypatch):
config_path = os.path.join(
config_folder, "test_native_tf2_pyinstrument_profiler_config_parser.json"
)
monkeypatch.setenv("SMPROFILER_CONFIG_PATH", config_path)
return ProfilerConfigParser(FRAMEWORK.TENSORFLOW)
def _helper_native_tf2_gradtape(out_dir, model, dataset, profiler_config_parser):
def get_grads(images, labels):
return model(images, training=True)
@tf.function
def train_step(images, labels):
return tf.reduce_mean(get_grads(images, labels))
hook = Hook(out_dir=out_dir, save_all=True)
hook.logger.disabled = True
hook.profiler_config_parser = profiler_config_parser
start_step = profiler_config_parser.config.python_profiling_config.start_step
end_step = start_step + profiler_config_parser.config.python_profiling_config.num_steps
opt = tf.keras.optimizers.Adam()
hook.wrap_optimizer(opt)
for current_step, (data, labels) in enumerate(dataset):
with hook.profiler():
labels = tf.one_hot(labels, depth=10)
with tf.GradientTape() as tape:
logits = train_step(data, labels)
if start_step <= current_step < end_step:
assert profiler_config_parser.python_profiler._start_step == current_step
assert (
profiler_config_parser.python_profiler._start_phase == StepPhase.STEP_START
)
grads = tape.gradient(logits, model.variables)
opt.apply_gradients(zip(grads, model.variables))
hook.save_tensor("inputs", data, CollectionKeys.INPUTS)
hook.save_tensor("logits", logits, CollectionKeys.OUTPUTS)
hook.save_tensor("labels", labels, CollectionKeys.OUTPUTS)
if start_step <= current_step < end_step:
assert profiler_config_parser.python_profiler._start_step == current_step
assert profiler_config_parser.python_profiler._start_phase == StepPhase.STEP_END
hook.profiling_end()
def _verify_tensor_names(out_dir):
trial = smd.create_trial(out_dir)
assert len(trial.steps()) > 0, "Nothing saved at any step."
assert len(trial.tensor_names()) > 0, "Tensors were not saved."
assert trial.tensor_names(collection=CollectionKeys.LOSSES) == ["loss"]
assert len(trial.tensor_names(collection=CollectionKeys.WEIGHTS)) > 0
assert len(trial.tensor_names(collection=CollectionKeys.BIASES)) > 0
assert trial.tensor_names(collection="optimizer_variables") == [
"Adam/beta_1:0",
"Adam/beta_2:0",
"Adam/decay:0",
"Adam/iter:0",
"Adam/learning_rate:0",
]
assert trial.tensor_names(collection=CollectionKeys.INPUTS) == ["inputs"]
assert trial.tensor_names(collection=CollectionKeys.OUTPUTS) == ["labels", "logits"]
@pytest.mark.parametrize("python_profiler_name", [CPROFILE_NAME, PYINSTRUMENT_NAME])
@pytest.mark.parametrize(
"model_type", [ModelType.SEQUENTIAL, ModelType.FUNCTIONAL, ModelType.SUBCLASSED]
)
def test_native_tf2_profiling(
python_profiler_name,
model_type,
tf2_mnist_sequential_model,
tf2_mnist_functional_model,
tf2_mnist_subclassed_model,
native_tf2_cprofile_profiler_config_parser,
native_tf2_pyinstrument_profiler_config_parser,
out_dir,
mnist_dataset,
tf_eager_mode,
):
if model_type == ModelType.SEQUENTIAL:
model = tf2_mnist_sequential_model
elif model_type == ModelType.FUNCTIONAL:
model = tf2_mnist_functional_model
else:
model = tf2_mnist_subclassed_model
if python_profiler_name == CPROFILE_NAME:
profiler_config_parser = native_tf2_cprofile_profiler_config_parser
else:
profiler_config_parser = native_tf2_pyinstrument_profiler_config_parser
assert profiler_config_parser.profiling_enabled
profiler_config_parser.load_config()
profiler_config_parser.start_pre_step_zero_python_profiling()
_helper_native_tf2_gradtape(out_dir, model, mnist_dataset, profiler_config_parser)
_verify_tensor_names(out_dir)
expected_stats_dir_count = (
profiler_config_parser.config.python_profiling_config.num_steps * 2
) + 2
python_stats_dir = os.path.join(out_dir, "framework", "tensorflow", python_profiler_name)
validate_python_profiling_stats(
python_stats_dir, python_profiler_name, expected_stats_dir_count
)
| true | true |
f7f8c16bf00732ac72b82b7bc497ecee71107f93 | 13,044 | py | Python | poky/meta/lib/oeqa/utils/commands.py | Eyerunmyden/HWMgmt-MegaRAC-OpenEdition | 72b03e9fc6e2a13184f1c57b8045b616db9b0a6d | [
"Apache-2.0",
"MIT"
] | 14 | 2021-11-04T07:47:37.000Z | 2022-03-21T10:10:30.000Z | poky/meta/lib/oeqa/utils/commands.py | Eyerunmyden/HWMgmt-MegaRAC-OpenEdition | 72b03e9fc6e2a13184f1c57b8045b616db9b0a6d | [
"Apache-2.0",
"MIT"
] | null | null | null | poky/meta/lib/oeqa/utils/commands.py | Eyerunmyden/HWMgmt-MegaRAC-OpenEdition | 72b03e9fc6e2a13184f1c57b8045b616db9b0a6d | [
"Apache-2.0",
"MIT"
] | 6 | 2021-11-02T10:56:19.000Z | 2022-03-06T11:58:20.000Z | #
# Copyright (c) 2013-2014 Intel Corporation
#
# SPDX-License-Identifier: MIT
#
# DESCRIPTION
# This module is mainly used by scripts/oe-selftest and modules under meta/oeqa/selftest
# It provides a class and methods for running commands on the host in a convienent way for tests.
import os
import sys
import signal
import subprocess
import threading
import time
import logging
from oeqa.utils import CommandError
from oeqa.utils import ftools
import re
import contextlib
# Export test doesn't require bb
try:
import bb
except ImportError:
pass
class Command(object):
def __init__(self, command, bg=False, timeout=None, data=None, output_log=None, **options):
self.defaultopts = {
"stdout": subprocess.PIPE,
"stderr": subprocess.STDOUT,
"stdin": None,
"shell": False,
"bufsize": -1,
}
self.cmd = command
self.bg = bg
self.timeout = timeout
self.data = data
self.options = dict(self.defaultopts)
if isinstance(self.cmd, str):
self.options["shell"] = True
if self.data:
self.options['stdin'] = subprocess.PIPE
self.options.update(options)
self.status = None
# We collect chunks of output before joining them at the end.
self._output_chunks = []
self._error_chunks = []
self.output = None
self.error = None
self.threads = []
self.output_log = output_log
self.log = logging.getLogger("utils.commands")
def run(self):
self.process = subprocess.Popen(self.cmd, **self.options)
def readThread(output, stream, logfunc):
if logfunc:
for line in stream:
output.append(line)
logfunc(line.decode("utf-8", errors='replace').rstrip())
else:
output.append(stream.read())
def readStderrThread():
readThread(self._error_chunks, self.process.stderr, self.output_log.error if self.output_log else None)
def readStdoutThread():
readThread(self._output_chunks, self.process.stdout, self.output_log.info if self.output_log else None)
def writeThread():
try:
self.process.stdin.write(self.data)
self.process.stdin.close()
except OSError as ex:
# It's not an error when the command does not consume all
# of our data. subprocess.communicate() also ignores that.
if ex.errno != EPIPE:
raise
# We write in a separate thread because then we can read
# without worrying about deadlocks. The additional thread is
# expected to terminate by itself and we mark it as a daemon,
# so even it should happen to not terminate for whatever
# reason, the main process will still exit, which will then
# kill the write thread.
if self.data:
thread = threading.Thread(target=writeThread, daemon=True)
thread.start()
self.threads.append(thread)
if self.process.stderr:
thread = threading.Thread(target=readStderrThread)
thread.start()
self.threads.append(thread)
if self.output_log:
self.output_log.info('Running: %s' % self.cmd)
thread = threading.Thread(target=readStdoutThread)
thread.start()
self.threads.append(thread)
self.log.debug("Running command '%s'" % self.cmd)
if not self.bg:
if self.timeout is None:
for thread in self.threads:
thread.join()
else:
deadline = time.time() + self.timeout
for thread in self.threads:
timeout = deadline - time.time()
if timeout < 0:
timeout = 0
thread.join(timeout)
self.stop()
def stop(self):
for thread in self.threads:
if thread.isAlive():
self.process.terminate()
# let's give it more time to terminate gracefully before killing it
thread.join(5)
if thread.isAlive():
self.process.kill()
thread.join()
def finalize_output(data):
if not data:
data = ""
else:
data = b"".join(data)
data = data.decode("utf-8", errors='replace').rstrip()
return data
self.output = finalize_output(self._output_chunks)
self._output_chunks = None
# self.error used to be a byte string earlier, probably unintentionally.
# Now it is a normal string, just like self.output.
self.error = finalize_output(self._error_chunks)
self._error_chunks = None
# At this point we know that the process has closed stdout/stderr, so
# it is safe and necessary to wait for the actual process completion.
self.status = self.process.wait()
self.process.stdout.close()
if self.process.stderr:
self.process.stderr.close()
self.log.debug("Command '%s' returned %d as exit code." % (self.cmd, self.status))
# logging the complete output is insane
# bitbake -e output is really big
# and makes the log file useless
if self.status:
lout = "\n".join(self.output.splitlines()[-20:])
self.log.debug("Last 20 lines:\n%s" % lout)
class Result(object):
pass
def runCmd(command, ignore_status=False, timeout=None, assert_error=True,
native_sysroot=None, limit_exc_output=0, output_log=None, **options):
result = Result()
if native_sysroot:
extra_paths = "%s/sbin:%s/usr/sbin:%s/usr/bin" % \
(native_sysroot, native_sysroot, native_sysroot)
extra_libpaths = "%s/lib:%s/usr/lib" % \
(native_sysroot, native_sysroot)
nenv = dict(options.get('env', os.environ))
nenv['PATH'] = extra_paths + ':' + nenv.get('PATH', '')
nenv['LD_LIBRARY_PATH'] = extra_libpaths + ':' + nenv.get('LD_LIBRARY_PATH', '')
options['env'] = nenv
cmd = Command(command, timeout=timeout, output_log=output_log, **options)
cmd.run()
result.command = command
result.status = cmd.status
result.output = cmd.output
result.error = cmd.error
result.pid = cmd.process.pid
if result.status and not ignore_status:
exc_output = result.output
if limit_exc_output > 0:
split = result.output.splitlines()
if len(split) > limit_exc_output:
exc_output = "\n... (last %d lines of output)\n" % limit_exc_output + \
'\n'.join(split[-limit_exc_output:])
if assert_error:
raise AssertionError("Command '%s' returned non-zero exit status %d:\n%s" % (command, result.status, exc_output))
else:
raise CommandError(result.status, command, exc_output)
return result
def bitbake(command, ignore_status=False, timeout=None, postconfig=None, output_log=None, **options):
if postconfig:
postconfig_file = os.path.join(os.environ.get('BUILDDIR'), 'oeqa-post.conf')
ftools.write_file(postconfig_file, postconfig)
extra_args = "-R %s" % postconfig_file
else:
extra_args = ""
if isinstance(command, str):
cmd = "bitbake " + extra_args + " " + command
else:
cmd = [ "bitbake" ] + [a for a in (command + extra_args.split(" ")) if a not in [""]]
try:
return runCmd(cmd, ignore_status, timeout, output_log=output_log, **options)
finally:
if postconfig:
os.remove(postconfig_file)
def get_bb_env(target=None, postconfig=None):
if target:
return bitbake("-e %s" % target, postconfig=postconfig).output
else:
return bitbake("-e", postconfig=postconfig).output
def get_bb_vars(variables=None, target=None, postconfig=None):
"""Get values of multiple bitbake variables"""
bbenv = get_bb_env(target, postconfig=postconfig)
if variables is not None:
variables = list(variables)
var_re = re.compile(r'^(export )?(?P<var>\w+(_.*)?)="(?P<value>.*)"$')
unset_re = re.compile(r'^unset (?P<var>\w+)$')
lastline = None
values = {}
for line in bbenv.splitlines():
match = var_re.match(line)
val = None
if match:
val = match.group('value')
else:
match = unset_re.match(line)
if match:
# Handle [unexport] variables
if lastline.startswith('# "'):
val = lastline.split('"')[1]
if val:
var = match.group('var')
if variables is None:
values[var] = val
else:
if var in variables:
values[var] = val
variables.remove(var)
# Stop after all required variables have been found
if not variables:
break
lastline = line
if variables:
# Fill in missing values
for var in variables:
values[var] = None
return values
def get_bb_var(var, target=None, postconfig=None):
return get_bb_vars([var], target, postconfig)[var]
def get_test_layer():
layers = get_bb_var("BBLAYERS").split()
testlayer = None
for l in layers:
if '~' in l:
l = os.path.expanduser(l)
if "/meta-selftest" in l and os.path.isdir(l):
testlayer = l
break
return testlayer
def create_temp_layer(templayerdir, templayername, priority=999, recipepathspec='recipes-*/*'):
os.makedirs(os.path.join(templayerdir, 'conf'))
with open(os.path.join(templayerdir, 'conf', 'layer.conf'), 'w') as f:
f.write('BBPATH .= ":${LAYERDIR}"\n')
f.write('BBFILES += "${LAYERDIR}/%s/*.bb \\' % recipepathspec)
f.write(' ${LAYERDIR}/%s/*.bbappend"\n' % recipepathspec)
f.write('BBFILE_COLLECTIONS += "%s"\n' % templayername)
f.write('BBFILE_PATTERN_%s = "^${LAYERDIR}/"\n' % templayername)
f.write('BBFILE_PRIORITY_%s = "%d"\n' % (templayername, priority))
f.write('BBFILE_PATTERN_IGNORE_EMPTY_%s = "1"\n' % templayername)
f.write('LAYERSERIES_COMPAT_%s = "${LAYERSERIES_COMPAT_core}"\n' % templayername)
@contextlib.contextmanager
def runqemu(pn, ssh=True, runqemuparams='', image_fstype=None, launch_cmd=None, qemuparams=None, overrides={}, discard_writes=True):
"""
launch_cmd means directly run the command, don't need set rootfs or env vars.
"""
import bb.tinfoil
import bb.build
# Need a non-'BitBake' logger to capture the runner output
targetlogger = logging.getLogger('TargetRunner')
targetlogger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
targetlogger.addHandler(handler)
tinfoil = bb.tinfoil.Tinfoil()
tinfoil.prepare(config_only=False, quiet=True)
try:
tinfoil.logger.setLevel(logging.WARNING)
import oeqa.targetcontrol
recipedata = tinfoil.parse_recipe(pn)
recipedata.setVar("TEST_LOG_DIR", "${WORKDIR}/testimage")
recipedata.setVar("TEST_QEMUBOOT_TIMEOUT", "1000")
# Tell QemuTarget() whether need find rootfs/kernel or not
if launch_cmd:
recipedata.setVar("FIND_ROOTFS", '0')
else:
recipedata.setVar("FIND_ROOTFS", '1')
for key, value in overrides.items():
recipedata.setVar(key, value)
logdir = recipedata.getVar("TEST_LOG_DIR")
qemu = oeqa.targetcontrol.QemuTarget(recipedata, targetlogger, image_fstype)
finally:
# We need to shut down tinfoil early here in case we actually want
# to run tinfoil-using utilities with the running QEMU instance.
# Luckily QemuTarget doesn't need it after the constructor.
tinfoil.shutdown()
try:
qemu.deploy()
try:
qemu.start(params=qemuparams, ssh=ssh, runqemuparams=runqemuparams, launch_cmd=launch_cmd, discard_writes=discard_writes)
except Exception as e:
msg = str(e) + '\nFailed to start QEMU - see the logs in %s' % logdir
if os.path.exists(qemu.qemurunnerlog):
with open(qemu.qemurunnerlog, 'r') as f:
msg = msg + "Qemurunner log output from %s:\n%s" % (qemu.qemurunnerlog, f.read())
raise Exception(msg)
yield qemu
finally:
targetlogger.removeHandler(handler)
qemu.stop()
def updateEnv(env_file):
"""
Source a file and update environment.
"""
cmd = ". %s; env -0" % env_file
result = runCmd(cmd)
for line in result.output.split("\0"):
(key, _, value) = line.partition("=")
os.environ[key] = value
| 35.349593 | 133 | 0.596903 |
import os
import sys
import signal
import subprocess
import threading
import time
import logging
from oeqa.utils import CommandError
from oeqa.utils import ftools
import re
import contextlib
try:
import bb
except ImportError:
pass
class Command(object):
def __init__(self, command, bg=False, timeout=None, data=None, output_log=None, **options):
self.defaultopts = {
"stdout": subprocess.PIPE,
"stderr": subprocess.STDOUT,
"stdin": None,
"shell": False,
"bufsize": -1,
}
self.cmd = command
self.bg = bg
self.timeout = timeout
self.data = data
self.options = dict(self.defaultopts)
if isinstance(self.cmd, str):
self.options["shell"] = True
if self.data:
self.options['stdin'] = subprocess.PIPE
self.options.update(options)
self.status = None
# We collect chunks of output before joining them at the end.
self._output_chunks = []
self._error_chunks = []
self.output = None
self.error = None
self.threads = []
self.output_log = output_log
self.log = logging.getLogger("utils.commands")
def run(self):
self.process = subprocess.Popen(self.cmd, **self.options)
def readThread(output, stream, logfunc):
if logfunc:
for line in stream:
output.append(line)
logfunc(line.decode("utf-8", errors='replace').rstrip())
else:
output.append(stream.read())
def readStderrThread():
readThread(self._error_chunks, self.process.stderr, self.output_log.error if self.output_log else None)
def readStdoutThread():
readThread(self._output_chunks, self.process.stdout, self.output_log.info if self.output_log else None)
def writeThread():
try:
self.process.stdin.write(self.data)
self.process.stdin.close()
except OSError as ex:
# It's not an error when the command does not consume all
if ex.errno != EPIPE:
raise
if self.data:
thread = threading.Thread(target=writeThread, daemon=True)
thread.start()
self.threads.append(thread)
if self.process.stderr:
thread = threading.Thread(target=readStderrThread)
thread.start()
self.threads.append(thread)
if self.output_log:
self.output_log.info('Running: %s' % self.cmd)
thread = threading.Thread(target=readStdoutThread)
thread.start()
self.threads.append(thread)
self.log.debug("Running command '%s'" % self.cmd)
if not self.bg:
if self.timeout is None:
for thread in self.threads:
thread.join()
else:
deadline = time.time() + self.timeout
for thread in self.threads:
timeout = deadline - time.time()
if timeout < 0:
timeout = 0
thread.join(timeout)
self.stop()
def stop(self):
for thread in self.threads:
if thread.isAlive():
self.process.terminate()
thread.join(5)
if thread.isAlive():
self.process.kill()
thread.join()
def finalize_output(data):
if not data:
data = ""
else:
data = b"".join(data)
data = data.decode("utf-8", errors='replace').rstrip()
return data
self.output = finalize_output(self._output_chunks)
self._output_chunks = None
# self.error used to be a byte string earlier, probably unintentionally.
# Now it is a normal string, just like self.output.
self.error = finalize_output(self._error_chunks)
self._error_chunks = None
# At this point we know that the process has closed stdout/stderr, so
# it is safe and necessary to wait for the actual process completion.
self.status = self.process.wait()
self.process.stdout.close()
if self.process.stderr:
self.process.stderr.close()
self.log.debug("Command '%s' returned %d as exit code." % (self.cmd, self.status))
# logging the complete output is insane
# bitbake -e output is really big
# and makes the log file useless
if self.status:
lout = "\n".join(self.output.splitlines()[-20:])
self.log.debug("Last 20 lines:\n%s" % lout)
class Result(object):
pass
def runCmd(command, ignore_status=False, timeout=None, assert_error=True,
native_sysroot=None, limit_exc_output=0, output_log=None, **options):
result = Result()
if native_sysroot:
extra_paths = "%s/sbin:%s/usr/sbin:%s/usr/bin" % \
(native_sysroot, native_sysroot, native_sysroot)
extra_libpaths = "%s/lib:%s/usr/lib" % \
(native_sysroot, native_sysroot)
nenv = dict(options.get('env', os.environ))
nenv['PATH'] = extra_paths + ':' + nenv.get('PATH', '')
nenv['LD_LIBRARY_PATH'] = extra_libpaths + ':' + nenv.get('LD_LIBRARY_PATH', '')
options['env'] = nenv
cmd = Command(command, timeout=timeout, output_log=output_log, **options)
cmd.run()
result.command = command
result.status = cmd.status
result.output = cmd.output
result.error = cmd.error
result.pid = cmd.process.pid
if result.status and not ignore_status:
exc_output = result.output
if limit_exc_output > 0:
split = result.output.splitlines()
if len(split) > limit_exc_output:
exc_output = "\n... (last %d lines of output)\n" % limit_exc_output + \
'\n'.join(split[-limit_exc_output:])
if assert_error:
raise AssertionError("Command '%s' returned non-zero exit status %d:\n%s" % (command, result.status, exc_output))
else:
raise CommandError(result.status, command, exc_output)
return result
def bitbake(command, ignore_status=False, timeout=None, postconfig=None, output_log=None, **options):
if postconfig:
postconfig_file = os.path.join(os.environ.get('BUILDDIR'), 'oeqa-post.conf')
ftools.write_file(postconfig_file, postconfig)
extra_args = "-R %s" % postconfig_file
else:
extra_args = ""
if isinstance(command, str):
cmd = "bitbake " + extra_args + " " + command
else:
cmd = [ "bitbake" ] + [a for a in (command + extra_args.split(" ")) if a not in [""]]
try:
return runCmd(cmd, ignore_status, timeout, output_log=output_log, **options)
finally:
if postconfig:
os.remove(postconfig_file)
def get_bb_env(target=None, postconfig=None):
if target:
return bitbake("-e %s" % target, postconfig=postconfig).output
else:
return bitbake("-e", postconfig=postconfig).output
def get_bb_vars(variables=None, target=None, postconfig=None):
bbenv = get_bb_env(target, postconfig=postconfig)
if variables is not None:
variables = list(variables)
var_re = re.compile(r'^(export )?(?P<var>\w+(_.*)?)="(?P<value>.*)"$')
unset_re = re.compile(r'^unset (?P<var>\w+)$')
lastline = None
values = {}
for line in bbenv.splitlines():
match = var_re.match(line)
val = None
if match:
val = match.group('value')
else:
match = unset_re.match(line)
if match:
# Handle [unexport] variables
if lastline.startswith('
val = lastline.split('"')[1]
if val:
var = match.group('var')
if variables is None:
values[var] = val
else:
if var in variables:
values[var] = val
variables.remove(var)
# Stop after all required variables have been found
if not variables:
break
lastline = line
if variables:
# Fill in missing values
for var in variables:
values[var] = None
return values
def get_bb_var(var, target=None, postconfig=None):
return get_bb_vars([var], target, postconfig)[var]
def get_test_layer():
layers = get_bb_var("BBLAYERS").split()
testlayer = None
for l in layers:
if '~' in l:
l = os.path.expanduser(l)
if "/meta-selftest" in l and os.path.isdir(l):
testlayer = l
break
return testlayer
def create_temp_layer(templayerdir, templayername, priority=999, recipepathspec='recipes-*/*'):
os.makedirs(os.path.join(templayerdir, 'conf'))
with open(os.path.join(templayerdir, 'conf', 'layer.conf'), 'w') as f:
f.write('BBPATH .= ":${LAYERDIR}"\n')
f.write('BBFILES += "${LAYERDIR}/%s/*.bb \\' % recipepathspec)
f.write(' ${LAYERDIR}/%s/*.bbappend"\n' % recipepathspec)
f.write('BBFILE_COLLECTIONS += "%s"\n' % templayername)
f.write('BBFILE_PATTERN_%s = "^${LAYERDIR}/"\n' % templayername)
f.write('BBFILE_PRIORITY_%s = "%d"\n' % (templayername, priority))
f.write('BBFILE_PATTERN_IGNORE_EMPTY_%s = "1"\n' % templayername)
f.write('LAYERSERIES_COMPAT_%s = "${LAYERSERIES_COMPAT_core}"\n' % templayername)
@contextlib.contextmanager
def runqemu(pn, ssh=True, runqemuparams='', image_fstype=None, launch_cmd=None, qemuparams=None, overrides={}, discard_writes=True):
import bb.tinfoil
import bb.build
# Need a non-'BitBake' logger to capture the runner output
targetlogger = logging.getLogger('TargetRunner')
targetlogger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
targetlogger.addHandler(handler)
tinfoil = bb.tinfoil.Tinfoil()
tinfoil.prepare(config_only=False, quiet=True)
try:
tinfoil.logger.setLevel(logging.WARNING)
import oeqa.targetcontrol
recipedata = tinfoil.parse_recipe(pn)
recipedata.setVar("TEST_LOG_DIR", "${WORKDIR}/testimage")
recipedata.setVar("TEST_QEMUBOOT_TIMEOUT", "1000")
# Tell QemuTarget() whether need find rootfs/kernel or not
if launch_cmd:
recipedata.setVar("FIND_ROOTFS", '0')
else:
recipedata.setVar("FIND_ROOTFS", '1')
for key, value in overrides.items():
recipedata.setVar(key, value)
logdir = recipedata.getVar("TEST_LOG_DIR")
qemu = oeqa.targetcontrol.QemuTarget(recipedata, targetlogger, image_fstype)
finally:
# We need to shut down tinfoil early here in case we actually want
# to run tinfoil-using utilities with the running QEMU instance.
# Luckily QemuTarget doesn't need it after the constructor.
tinfoil.shutdown()
try:
qemu.deploy()
try:
qemu.start(params=qemuparams, ssh=ssh, runqemuparams=runqemuparams, launch_cmd=launch_cmd, discard_writes=discard_writes)
except Exception as e:
msg = str(e) + '\nFailed to start QEMU - see the logs in %s' % logdir
if os.path.exists(qemu.qemurunnerlog):
with open(qemu.qemurunnerlog, 'r') as f:
msg = msg + "Qemurunner log output from %s:\n%s" % (qemu.qemurunnerlog, f.read())
raise Exception(msg)
yield qemu
finally:
targetlogger.removeHandler(handler)
qemu.stop()
def updateEnv(env_file):
cmd = ". %s; env -0" % env_file
result = runCmd(cmd)
for line in result.output.split("\0"):
(key, _, value) = line.partition("=")
os.environ[key] = value
| true | true |
f7f8c17ecba74a8f00083f484e953c8077707774 | 3,605 | py | Python | test/torchaudio_unittest/functional/functional_impl.py | prarabdh9909/audio | 6bad3a66a7a1c7cc05755e9ee5931b7391d2b94c | [
"BSD-2-Clause"
] | 1 | 2021-03-16T08:09:20.000Z | 2021-03-16T08:09:20.000Z | test/torchaudio_unittest/functional/functional_impl.py | prarabdh9909/audio | 6bad3a66a7a1c7cc05755e9ee5931b7391d2b94c | [
"BSD-2-Clause"
] | null | null | null | test/torchaudio_unittest/functional/functional_impl.py | prarabdh9909/audio | 6bad3a66a7a1c7cc05755e9ee5931b7391d2b94c | [
"BSD-2-Clause"
] | null | null | null | """Test defintion common to CPU and CUDA"""
import torch
import torchaudio.functional as F
from parameterized import parameterized
from scipy import signal
from torchaudio_unittest import common_utils
class Lfilter(common_utils.TestBaseMixin):
def test_simple(self):
"""
Create a very basic signal,
Then make a simple 4th order delay
The output should be same as the input but shifted
"""
torch.random.manual_seed(42)
waveform = torch.rand(2, 44100 * 1, dtype=self.dtype, device=self.device)
b_coeffs = torch.tensor([0, 0, 0, 1], dtype=self.dtype, device=self.device)
a_coeffs = torch.tensor([1, 0, 0, 0], dtype=self.dtype, device=self.device)
output_waveform = F.lfilter(waveform, a_coeffs, b_coeffs)
self.assertEqual(output_waveform[:, 3:], waveform[:, 0:-3], atol=1e-5, rtol=1e-5)
def test_clamp(self):
input_signal = torch.ones(1, 44100 * 1, dtype=self.dtype, device=self.device)
b_coeffs = torch.tensor([1, 0], dtype=self.dtype, device=self.device)
a_coeffs = torch.tensor([1, -0.95], dtype=self.dtype, device=self.device)
output_signal = F.lfilter(input_signal, a_coeffs, b_coeffs, clamp=True)
assert output_signal.max() <= 1
output_signal = F.lfilter(input_signal, a_coeffs, b_coeffs, clamp=False)
assert output_signal.max() > 1
@parameterized.expand([
((44100,),),
((3, 44100),),
((2, 3, 44100),),
((1, 2, 3, 44100),)
])
def test_shape(self, shape):
torch.random.manual_seed(42)
waveform = torch.rand(*shape, dtype=self.dtype, device=self.device)
b_coeffs = torch.tensor([0, 0, 0, 1], dtype=self.dtype, device=self.device)
a_coeffs = torch.tensor([1, 0, 0, 0], dtype=self.dtype, device=self.device)
output_waveform = F.lfilter(waveform, a_coeffs, b_coeffs)
assert shape == waveform.size() == output_waveform.size()
def test_9th_order_filter_stability(self):
"""
Validate the precision of lfilter against reference scipy implementation when using high order filter.
The reference implementation use cascaded second-order filters so is more numerically accurate.
"""
# create an impulse signal
x = torch.zeros(1024, dtype=self.dtype, device=self.device)
x[0] = 1
# get target impulse response
sos = signal.butter(9, 850, 'hp', fs=22050, output='sos')
y = torch.from_numpy(signal.sosfilt(sos, x.cpu().numpy())).to(self.dtype).to(self.device)
# get lfilter coefficients
b, a = signal.butter(9, 850, 'hp', fs=22050, output='ba')
b, a = torch.from_numpy(b).to(self.dtype).to(self.device), torch.from_numpy(
a).to(self.dtype).to(self.device)
# predict impulse response
yhat = F.lfilter(x, a, b, False)
self.assertEqual(yhat, y, atol=1e-4, rtol=1e-5)
class Spectrogram(common_utils.TestBaseMixin):
@parameterized.expand([(0., ), (1., ), (2., ), (3., )])
def test_grad_at_zero(self, power):
"""The gradient of power spectrogram should not be nan but zero near x=0
https://github.com/pytorch/audio/issues/993
"""
x = torch.zeros(1, 22050, requires_grad=True)
spec = F.spectrogram(
x,
pad=0,
window=None,
n_fft=2048,
hop_length=None,
win_length=None,
power=power,
normalized=False,
)
spec.sum().backward()
assert not x.grad.isnan().sum()
| 39.184783 | 110 | 0.622469 | import torch
import torchaudio.functional as F
from parameterized import parameterized
from scipy import signal
from torchaudio_unittest import common_utils
class Lfilter(common_utils.TestBaseMixin):
def test_simple(self):
torch.random.manual_seed(42)
waveform = torch.rand(2, 44100 * 1, dtype=self.dtype, device=self.device)
b_coeffs = torch.tensor([0, 0, 0, 1], dtype=self.dtype, device=self.device)
a_coeffs = torch.tensor([1, 0, 0, 0], dtype=self.dtype, device=self.device)
output_waveform = F.lfilter(waveform, a_coeffs, b_coeffs)
self.assertEqual(output_waveform[:, 3:], waveform[:, 0:-3], atol=1e-5, rtol=1e-5)
def test_clamp(self):
input_signal = torch.ones(1, 44100 * 1, dtype=self.dtype, device=self.device)
b_coeffs = torch.tensor([1, 0], dtype=self.dtype, device=self.device)
a_coeffs = torch.tensor([1, -0.95], dtype=self.dtype, device=self.device)
output_signal = F.lfilter(input_signal, a_coeffs, b_coeffs, clamp=True)
assert output_signal.max() <= 1
output_signal = F.lfilter(input_signal, a_coeffs, b_coeffs, clamp=False)
assert output_signal.max() > 1
@parameterized.expand([
((44100,),),
((3, 44100),),
((2, 3, 44100),),
((1, 2, 3, 44100),)
])
def test_shape(self, shape):
torch.random.manual_seed(42)
waveform = torch.rand(*shape, dtype=self.dtype, device=self.device)
b_coeffs = torch.tensor([0, 0, 0, 1], dtype=self.dtype, device=self.device)
a_coeffs = torch.tensor([1, 0, 0, 0], dtype=self.dtype, device=self.device)
output_waveform = F.lfilter(waveform, a_coeffs, b_coeffs)
assert shape == waveform.size() == output_waveform.size()
def test_9th_order_filter_stability(self):
x = torch.zeros(1024, dtype=self.dtype, device=self.device)
x[0] = 1
sos = signal.butter(9, 850, 'hp', fs=22050, output='sos')
y = torch.from_numpy(signal.sosfilt(sos, x.cpu().numpy())).to(self.dtype).to(self.device)
b, a = signal.butter(9, 850, 'hp', fs=22050, output='ba')
b, a = torch.from_numpy(b).to(self.dtype).to(self.device), torch.from_numpy(
a).to(self.dtype).to(self.device)
yhat = F.lfilter(x, a, b, False)
self.assertEqual(yhat, y, atol=1e-4, rtol=1e-5)
class Spectrogram(common_utils.TestBaseMixin):
@parameterized.expand([(0., ), (1., ), (2., ), (3., )])
def test_grad_at_zero(self, power):
x = torch.zeros(1, 22050, requires_grad=True)
spec = F.spectrogram(
x,
pad=0,
window=None,
n_fft=2048,
hop_length=None,
win_length=None,
power=power,
normalized=False,
)
spec.sum().backward()
assert not x.grad.isnan().sum()
| true | true |
f7f8c1ac3508eddbbe6d086b02f19351777e5223 | 173 | py | Python | configure.py | OmkarMetri/Conference-Management-System | 4b18819738e393be0aa5fe144a8ede7ac566470c | [
"Apache-2.0"
] | null | null | null | configure.py | OmkarMetri/Conference-Management-System | 4b18819738e393be0aa5fe144a8ede7ac566470c | [
"Apache-2.0"
] | 1 | 2021-06-02T00:53:05.000Z | 2021-06-02T00:53:05.000Z | configure.py | OmkarMetri/Conference-Management-System | 4b18819738e393be0aa5fe144a8ede7ac566470c | [
"Apache-2.0"
] | null | null | null | import requests
print("Updating database (see the server logs)")
res = requests.post("http://localhost:5000/admin/update-datasets")
print(res.status_code)
print(res.json()) | 28.833333 | 66 | 0.768786 | import requests
print("Updating database (see the server logs)")
res = requests.post("http://localhost:5000/admin/update-datasets")
print(res.status_code)
print(res.json()) | true | true |
f7f8c1f4deba335a77cd584c7dc1e85f738b79eb | 2,492 | py | Python | tests/core/design/core_custom_vjp_test.py | berndbohnet/flax | 5aa7f335bb8819088c8b1aa89aa459c99eb00c1c | [
"Apache-2.0"
] | 1 | 2022-02-27T13:50:55.000Z | 2022-02-27T13:50:55.000Z | tests/core/design/core_custom_vjp_test.py | berndbohnet/flax | 5aa7f335bb8819088c8b1aa89aa459c99eb00c1c | [
"Apache-2.0"
] | null | null | null | tests/core/design/core_custom_vjp_test.py | berndbohnet/flax | 5aa7f335bb8819088c8b1aa89aa459c99eb00c1c | [
"Apache-2.0"
] | null | null | null | # Copyright 2022 The Flax Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Sequence, Callable
from functools import partial
from absl.testing import absltest
import numpy as np
from flax.core import Scope, Array, init, apply, unfreeze, lift, nn
import jax
from jax import random, numpy as jnp
def mlp_custom_grad(scope: Scope, x: Array,
sizes: Sequence[int] = (8, 1),
act_fn: Callable[[Array], Array] = nn.relu):
f = nn.dense
def fwd(scope, x, features):
y, vjp_fn = lift.vjp(partial(f, features=features), scope, x)
return y, vjp_fn
def bwd(features, res, y_t):
del features
vjp_fn = res
input_t, params_t = vjp_fn(y_t)
params_t = jax.tree_map(jnp.sign, params_t)
return input_t, params_t
dense_custom_grad = lift.custom_vjp(
f, forward_fn=fwd, backward_fn=bwd, nondiff_argnums=(2,))
# hidden layers
for size in sizes[:-1]:
x = scope.child(dense_custom_grad, prefix='hidden_')(x, size)
x = act_fn(x)
# output layer
return scope.child(dense_custom_grad, 'out')(x, sizes[-1])
class CustomVJPTest(absltest.TestCase):
def test_custom_vjp(self):
x = random.normal(random.PRNGKey(0), (1, 4))
y, variables = init(mlp_custom_grad)(random.PRNGKey(1), x)
param_shapes = unfreeze(
jax.tree_map(jnp.shape, variables['params']))
loss_fn = lambda p, x: jnp.mean(apply(mlp_custom_grad)(p, x) ** 2)
grad = jax.grad(loss_fn)(variables, x)
grad_shapes = unfreeze(
jax.tree_map(jnp.shape, grad['params']))
self.assertEqual(y.shape, (1, 1))
expected_param_shapes = {
'hidden_0': {'kernel': (4, 8), 'bias': (8,)},
'out': {'kernel': (8, 1), 'bias': (1,)},
}
self.assertEqual(param_shapes, expected_param_shapes)
self.assertEqual(grad_shapes, expected_param_shapes)
for g in jax.tree_leaves(grad):
self.assertTrue(np.all(g == np.sign(g)))
if __name__ == '__main__':
absltest.main()
| 30.390244 | 74 | 0.678571 |
from typing import Sequence, Callable
from functools import partial
from absl.testing import absltest
import numpy as np
from flax.core import Scope, Array, init, apply, unfreeze, lift, nn
import jax
from jax import random, numpy as jnp
def mlp_custom_grad(scope: Scope, x: Array,
sizes: Sequence[int] = (8, 1),
act_fn: Callable[[Array], Array] = nn.relu):
f = nn.dense
def fwd(scope, x, features):
y, vjp_fn = lift.vjp(partial(f, features=features), scope, x)
return y, vjp_fn
def bwd(features, res, y_t):
del features
vjp_fn = res
input_t, params_t = vjp_fn(y_t)
params_t = jax.tree_map(jnp.sign, params_t)
return input_t, params_t
dense_custom_grad = lift.custom_vjp(
f, forward_fn=fwd, backward_fn=bwd, nondiff_argnums=(2,))
for size in sizes[:-1]:
x = scope.child(dense_custom_grad, prefix='hidden_')(x, size)
x = act_fn(x)
return scope.child(dense_custom_grad, 'out')(x, sizes[-1])
class CustomVJPTest(absltest.TestCase):
def test_custom_vjp(self):
x = random.normal(random.PRNGKey(0), (1, 4))
y, variables = init(mlp_custom_grad)(random.PRNGKey(1), x)
param_shapes = unfreeze(
jax.tree_map(jnp.shape, variables['params']))
loss_fn = lambda p, x: jnp.mean(apply(mlp_custom_grad)(p, x) ** 2)
grad = jax.grad(loss_fn)(variables, x)
grad_shapes = unfreeze(
jax.tree_map(jnp.shape, grad['params']))
self.assertEqual(y.shape, (1, 1))
expected_param_shapes = {
'hidden_0': {'kernel': (4, 8), 'bias': (8,)},
'out': {'kernel': (8, 1), 'bias': (1,)},
}
self.assertEqual(param_shapes, expected_param_shapes)
self.assertEqual(grad_shapes, expected_param_shapes)
for g in jax.tree_leaves(grad):
self.assertTrue(np.all(g == np.sign(g)))
if __name__ == '__main__':
absltest.main()
| true | true |
f7f8c33a303f88218bb800b844d12a4b67476d7c | 8,585 | py | Python | util.py | diningphil/CGMM-ICML2018 | c6da2ac267edae0a0326818c6b4f4a6c141a053f | [
"BSD-3-Clause"
] | 1 | 2018-05-17T03:38:42.000Z | 2018-05-17T03:38:42.000Z | util.py | diningphil/CGMM-ICML2018 | c6da2ac267edae0a0326818c6b4f4a6c141a053f | [
"BSD-3-Clause"
] | null | null | null | util.py | diningphil/CGMM-ICML2018 | c6da2ac267edae0a0326818c6b4f4a6c141a053f | [
"BSD-3-Clause"
] | null | null | null | from typing import Optional, Tuple, List
import torch
import torch_geometric
def extend_lists(data_list: Optional[Tuple[Optional[List[torch.Tensor]]]],
new_data_list: Tuple[Optional[List[torch.Tensor]]]) -> Tuple[Optional[List[torch.Tensor]]]:
r"""
Extends the semantic of Python :func:`extend()` over lists to tuples
Used e.g., to concatenate results of mini-batches in incremental architectures such as :obj:`CGMM`
Args:
data_list: tuple of lists, or ``None`` if there is no list to extend.
new_data_list: object of the same form of :obj:`data_list` that has to be concatenated
Returns:
the tuple of extended lists
"""
if data_list is None:
return new_data_list
assert len(data_list) == len(new_data_list)
for i in range(len(data_list)):
if new_data_list[i] is not None:
data_list[i].extend(new_data_list[i])
return data_list
def to_tensor_lists(embeddings: Tuple[Optional[torch.Tensor]],
batch: torch_geometric.data.batch.Batch,
edge_index: torch.Tensor) -> Tuple[Optional[List[torch.Tensor]]]:
r"""
Reverts batched outputs back to a list of Tensors elements.
Can be useful to build incremental architectures such as :obj:`CGMM` that store intermediate results
before training the next layer.
Args:
embeddings (tuple): a tuple of embeddings :obj:`(vertex_output, edge_output, graph_output, vertex_extra_output, edge_extra_output, graph_extra_output)`.
Each embedding can be a :class:`torch.Tensor` or ``None``.
batch (:class:`torch_geometric.data.batch.Batch`): Batch information used to split the tensors.
edge_index (:class:`torch.Tensor`): a :obj:`2 x num_edges` tensor as defined in Pytorch Geometric.
Used to split edge Tensors graph-wise.
Returns:
a tuple with the same semantics as the argument ``embeddings``, but this time each element holds a list of
Tensors, one for each graph in the dataset.
"""
# Crucial: Detach the embeddings to free the computation graph!!
# TODO this code can surely be made more compact, but leave it as is until future refactoring or removal from PyDGN.
v_out, e_out, g_out, vo_out, eo_out, go_out = embeddings
v_out = v_out.detach() if v_out is not None else None
v_out_list = [] if v_out is not None else None
e_out = e_out.detach() if e_out is not None else None
e_out_list = [] if e_out is not None else None
g_out = g_out.detach() if g_out is not None else None
g_out_list = [] if g_out is not None else None
vo_out = vo_out.detach() if vo_out is not None else None
vo_out_list = [] if vo_out is not None else None
eo_out = eo_out.detach() if eo_out is not None else None
eo_out_list = [] if eo_out is not None else None
go_out = go_out.detach() if go_out is not None else None
go_out_list = [] if go_out is not None else None
_, node_counts = torch.unique_consecutive(batch, return_counts=True)
node_cumulative = torch.cumsum(node_counts, dim=0)
if e_out is not None or eo_out is not None:
edge_batch = batch[edge_index[0]]
_, edge_counts = torch.unique_consecutive(edge_batch, return_counts=True)
edge_cumulative = torch.cumsum(edge_counts, dim=0)
if v_out_list is not None:
v_out_list.append(v_out[:node_cumulative[0]])
if e_out_list is not None:
e_out_list.append(e_out[:edge_cumulative[0]])
if g_out_list is not None:
g_out_list.append(g_out[0].unsqueeze(0)) # recreate batch dimension by unsqueezing
if vo_out_list is not None:
vo_out_list.append(vo_out[:node_cumulative[0]])
if eo_out_list is not None:
eo_out_list.append(eo_out[:edge_cumulative[0]])
if go_out_list is not None:
go_out_list.append(go_out[0].unsqueeze(0)) # recreate batch dimension by unsqueezing
for i in range(1, len(node_cumulative)):
if v_out_list is not None:
v_out_list.append(v_out[node_cumulative[i - 1]:node_cumulative[i]])
if e_out_list is not None:
e_out_list.append(e_out[edge_cumulative[i - 1]:edge_cumulative[i]])
if g_out_list is not None:
g_out_list.append(g_out[i].unsqueeze(0)) # recreate batch dimension by unsqueezing
if vo_out_list is not None:
vo_out_list.append(vo_out[node_cumulative[i - 1]:node_cumulative[i]])
if eo_out_list is not None:
eo_out_list.append(eo_out[edge_cumulative[i - 1]:edge_cumulative[i]])
if go_out_list is not None:
go_out_list.append(go_out[i].unsqueeze(0)) # recreate batch dimension by unsqueezing
return v_out_list, e_out_list, g_out_list, vo_out_list, eo_out_list, go_out_list
def compute_unigram(posteriors: torch.Tensor, use_continuous_states: bool) -> torch.Tensor:
r"""
Computes the unigram representation of nodes as defined in https://www.jmlr.org/papers/volume21/19-470/19-470.pdf
Args:
posteriors (torch.Tensor): tensor of posterior distributions of nodes with shape `(#nodes,num_latent_states)`
use_continuous_states (bool): whether or not to use the most probable state (one-hot vector) or a "soft" version
Returns:
a tensor of unigrams with shape `(#nodes,num_latent_states)`
"""
num_latent_states = posteriors.shape[1]
if use_continuous_states:
node_embeddings_batch = posteriors
else:
node_embeddings_batch = make_one_hot(posteriors.argmax(dim=1), num_latent_states)
return node_embeddings_batch.double()
def compute_bigram(posteriors: torch.Tensor, edge_index: torch.Tensor, batch: torch.Tensor,
use_continuous_states: bool) -> torch.Tensor:
r"""
Computes the bigram representation of nodes as defined in https://www.jmlr.org/papers/volume21/19-470/19-470.pdf
Args:
posteriors (torch.Tensor): tensor of posterior distributions of nodes with shape `(#nodes,num_latent_states)`
edge_index (torch.Tensor): tensor of edge indices with shape `(2,#edges)` that adheres to PyG specifications
batch (torch.Tensor): vector that assigns each node to a graph id in the batch
use_continuous_states (bool): whether or not to use the most probable state (one-hot vector) or a "soft" version
Returns:
a tensor of bigrams with shape `(#nodes,num_latent_states*num_latent_states)`
"""
C = posteriors.shape[1]
device = posteriors.get_device()
device = 'cpu' if device == -1 else device
if use_continuous_states:
# Code provided by Daniele Atzeni to speed up the computation!
nodes_in_batch = len(batch)
sparse_adj_matrix = torch.sparse.FloatTensor(edge_index,
torch.ones(edge_index.shape[1]).to(device),
torch.Size([nodes_in_batch, nodes_in_batch]))
tmp1 = torch.sparse.mm(sparse_adj_matrix, posteriors.float()).repeat(1, C)
tmp2 = posteriors.reshape(-1, 1).repeat(1, C).reshape(-1, C * C)
node_bigram_batch = torch.mul(tmp1, tmp2)
else:
# Convert into one hot
posteriors_one_hot = make_one_hot(posteriors.argmax(dim=1), C).float()
# Code provided by Daniele Atzeni to speed up the computation!
nodes_in_batch = len(batch)
sparse_adj_matrix = torch.sparse.FloatTensor(edge_index,
torch.ones(edge_index.shape[1]).to(device),
torch.Size([nodes_in_batch, nodes_in_batch]))
tmp1 = torch.sparse.mm(sparse_adj_matrix, posteriors_one_hot).repeat(1, C)
tmp2 = posteriors_one_hot.reshape(-1, 1).repeat(1, C).reshape(-1, C * C)
node_bigram_batch = torch.mul(tmp1, tmp2)
return node_bigram_batch.double()
def make_one_hot(labels: torch.Tensor, num_unique_ids: torch.Tensor) -> torch.Tensor:
r"""
Converts a vector of ids into a one-hot matrix
Args:
labels (torch.Tensor): the vector of ids
num_unique_ids (torch.Tensor): number of unique ids
Returns:
a one-hot tensor with shape `(samples,num_unique_ids)`
"""
device = labels.get_device()
device = 'cpu' if device == -1 else device
one_hot = torch.zeros(labels.size(0), num_unique_ids).to(device)
one_hot[torch.arange(labels.size(0)).to(device), labels] = 1
return one_hot
| 42.5 | 160 | 0.671171 | from typing import Optional, Tuple, List
import torch
import torch_geometric
def extend_lists(data_list: Optional[Tuple[Optional[List[torch.Tensor]]]],
new_data_list: Tuple[Optional[List[torch.Tensor]]]) -> Tuple[Optional[List[torch.Tensor]]]:
if data_list is None:
return new_data_list
assert len(data_list) == len(new_data_list)
for i in range(len(data_list)):
if new_data_list[i] is not None:
data_list[i].extend(new_data_list[i])
return data_list
def to_tensor_lists(embeddings: Tuple[Optional[torch.Tensor]],
batch: torch_geometric.data.batch.Batch,
edge_index: torch.Tensor) -> Tuple[Optional[List[torch.Tensor]]]:
v_out, e_out, g_out, vo_out, eo_out, go_out = embeddings
v_out = v_out.detach() if v_out is not None else None
v_out_list = [] if v_out is not None else None
e_out = e_out.detach() if e_out is not None else None
e_out_list = [] if e_out is not None else None
g_out = g_out.detach() if g_out is not None else None
g_out_list = [] if g_out is not None else None
vo_out = vo_out.detach() if vo_out is not None else None
vo_out_list = [] if vo_out is not None else None
eo_out = eo_out.detach() if eo_out is not None else None
eo_out_list = [] if eo_out is not None else None
go_out = go_out.detach() if go_out is not None else None
go_out_list = [] if go_out is not None else None
_, node_counts = torch.unique_consecutive(batch, return_counts=True)
node_cumulative = torch.cumsum(node_counts, dim=0)
if e_out is not None or eo_out is not None:
edge_batch = batch[edge_index[0]]
_, edge_counts = torch.unique_consecutive(edge_batch, return_counts=True)
edge_cumulative = torch.cumsum(edge_counts, dim=0)
if v_out_list is not None:
v_out_list.append(v_out[:node_cumulative[0]])
if e_out_list is not None:
e_out_list.append(e_out[:edge_cumulative[0]])
if g_out_list is not None:
g_out_list.append(g_out[0].unsqueeze(0))
if vo_out_list is not None:
vo_out_list.append(vo_out[:node_cumulative[0]])
if eo_out_list is not None:
eo_out_list.append(eo_out[:edge_cumulative[0]])
if go_out_list is not None:
go_out_list.append(go_out[0].unsqueeze(0))
for i in range(1, len(node_cumulative)):
if v_out_list is not None:
v_out_list.append(v_out[node_cumulative[i - 1]:node_cumulative[i]])
if e_out_list is not None:
e_out_list.append(e_out[edge_cumulative[i - 1]:edge_cumulative[i]])
if g_out_list is not None:
g_out_list.append(g_out[i].unsqueeze(0))
if vo_out_list is not None:
vo_out_list.append(vo_out[node_cumulative[i - 1]:node_cumulative[i]])
if eo_out_list is not None:
eo_out_list.append(eo_out[edge_cumulative[i - 1]:edge_cumulative[i]])
if go_out_list is not None:
go_out_list.append(go_out[i].unsqueeze(0))
return v_out_list, e_out_list, g_out_list, vo_out_list, eo_out_list, go_out_list
def compute_unigram(posteriors: torch.Tensor, use_continuous_states: bool) -> torch.Tensor:
num_latent_states = posteriors.shape[1]
if use_continuous_states:
node_embeddings_batch = posteriors
else:
node_embeddings_batch = make_one_hot(posteriors.argmax(dim=1), num_latent_states)
return node_embeddings_batch.double()
def compute_bigram(posteriors: torch.Tensor, edge_index: torch.Tensor, batch: torch.Tensor,
use_continuous_states: bool) -> torch.Tensor:
C = posteriors.shape[1]
device = posteriors.get_device()
device = 'cpu' if device == -1 else device
if use_continuous_states:
nodes_in_batch = len(batch)
sparse_adj_matrix = torch.sparse.FloatTensor(edge_index,
torch.ones(edge_index.shape[1]).to(device),
torch.Size([nodes_in_batch, nodes_in_batch]))
tmp1 = torch.sparse.mm(sparse_adj_matrix, posteriors.float()).repeat(1, C)
tmp2 = posteriors.reshape(-1, 1).repeat(1, C).reshape(-1, C * C)
node_bigram_batch = torch.mul(tmp1, tmp2)
else:
posteriors_one_hot = make_one_hot(posteriors.argmax(dim=1), C).float()
nodes_in_batch = len(batch)
sparse_adj_matrix = torch.sparse.FloatTensor(edge_index,
torch.ones(edge_index.shape[1]).to(device),
torch.Size([nodes_in_batch, nodes_in_batch]))
tmp1 = torch.sparse.mm(sparse_adj_matrix, posteriors_one_hot).repeat(1, C)
tmp2 = posteriors_one_hot.reshape(-1, 1).repeat(1, C).reshape(-1, C * C)
node_bigram_batch = torch.mul(tmp1, tmp2)
return node_bigram_batch.double()
def make_one_hot(labels: torch.Tensor, num_unique_ids: torch.Tensor) -> torch.Tensor:
device = labels.get_device()
device = 'cpu' if device == -1 else device
one_hot = torch.zeros(labels.size(0), num_unique_ids).to(device)
one_hot[torch.arange(labels.size(0)).to(device), labels] = 1
return one_hot
| true | true |
f7f8c43de075b0dc8f9e8a0d763b73720fd094c5 | 4,285 | py | Python | implementation codes/quartic oscillator/setupC.py | Z-T-WANG/DeepReinforcementLearningControlOfQuantumCartpoles | 3b243f235b4945a4817b738d8dbc412937de9f28 | [
"MIT"
] | 6 | 2020-08-01T09:30:17.000Z | 2021-10-31T19:40:51.000Z | implementation codes/quartic oscillator/setupC.py | Z-T-WANG/DeepReinforcementLearningControlOfQuantumCartpoles | 3b243f235b4945a4817b738d8dbc412937de9f28 | [
"MIT"
] | null | null | null | implementation codes/quartic oscillator/setupC.py | Z-T-WANG/DeepReinforcementLearningControlOfQuantumCartpoles | 3b243f235b4945a4817b738d8dbc412937de9f28 | [
"MIT"
] | 1 | 2020-07-28T06:10:08.000Z | 2020-07-28T06:10:08.000Z | from distutils.core import setup, Extension
from math import pi
import numpy as np
import os, sys, shutil, glob
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--lambda', default= pi/25., type=float, metavar='\lambda',
help='the strength of the quartic anharmonic oscillator')
parser.add_argument('--x_max', default=8.5, type=float, metavar='x_{max}',
help='the distance from the center to the border of the simulation space')
parser.add_argument('--grid_size', default = 0.1, type=float, metavar='h',
help='the grid size of the discretized simulation space')
parser.add_argument('--mass', default = 1./pi, type=float, metavar='m',
help='the mass of the simulated particle')
parser.add_argument('--moment', default = 5, type=int,
help='the order of the distribution moments to compute in the compiled function "get_moments"')
args = parser.parse_args()
# Please rewrite the following arguments based on your OS and your prescription of compilation if necessary
# Please refer to https://software.intel.com/en-us/articles/intel-mkl-link-line-advisor . Usually Python uses GCC as the default compiler, and then GNU compiler should be selected. The arguments starting with "-I" mean to "include" those directories.
link_options = ['-Wl,--start-group', os.environ['MKLROOT']+'/lib/intel64/libmkl_intel_ilp64.a', os.environ['MKLROOT']+'/lib/intel64/libmkl_intel_thread.a', os.environ['MKLROOT']+'/lib/intel64/libmkl_core.a', '-Wl,--end-group', '-liomp5', '-lpthread', '-lm', '-ldl']
compiler_options = ['-DMKL_ILP64','-m64']
##############################################################################
# The following is the compilation program.
def compile(x_max, grid_size, mass, lambda_, moment):
assert lambda_>= 0., 'quartic oscillator strength \lambda should be positive'
assert mass> 0., 'the mass should be positive'
assert x_max> 0., 'the size of the simulation space (2 * x_max) should be positive'
assert grid_size> 0., 'the simulation grid size should be positive'
assert moment >= 1, 'the order of distribution moments should be larger than 1'
# It invokes the native "distutils.core" of Python by setting the commandline arguments stored in sys.argv to the desired one ("build")
# set the "build" command
original_args_exist = False
if len(sys.argv)>=2:
original_args=sys.argv[1:]
sys.argv = [sys.argv[0], "build"]
original_args_exist = True
else: sys.argv.append("build")
os.environ["MKL_NUM_THREADS"] = "1"
package_name = 'simulation'
module1 = Extension(package_name,language='c++',
define_macros = [('X_MAX', str(x_max)), ('GRID_SIZE', repr(grid_size)), ('MASS',repr(mass)), ('LAMBDA', repr(lambda_)), ('MOMENT', str(moment))], # pass the defining parameters
include_dirs = [np.get_include(), os.path.join(os.environ['MKLROOT'],'include')],
sources = ['simulation_quart.cpp'],
extra_compile_args = compiler_options+['-Ofast','-funroll-loops', '-march=native', '-flto','-fuse-linker-plugin','--param', 'ipcp-unit-growth=2000', '-std=c++14','-fno-stack-protector','-fmerge-all-constants'],
extra_link_args = link_options+['-Ofast','-fdelete-null-pointer-checks','-funroll-loops', '-march=native', '-fwhole-program','-flto','-fuse-linker-plugin','--param', 'ipcp-unit-growth=2000','-std=c++14','-fno-stack-protector','-fmerge-all-constants'])
setup (name = package_name,
version = '1.0',
description = 'do simulation steps',
author = 'Wang Zhikang',
ext_modules = [module1])
# copy the compiled C module to the root to import
compiled_files = glob.glob('build/**/*')
for compiled_file in compiled_files:
if 'temp' not in compiled_file:
shutil.move(compiled_file, os.path.basename(compiled_file), copy_function=shutil.copy2)
# restore the original commandline arguments
if original_args_exist: sys.argv = [sys.argv[0]]+original_args
else: sys.argv.pop(1)
compile(x_max=args.x_max, grid_size=args.grid_size, mass=args.mass, lambda_=args.__dict__['lambda'], moment=args.moment)
| 54.935897 | 271 | 0.664877 | from distutils.core import setup, Extension
from math import pi
import numpy as np
import os, sys, shutil, glob
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--lambda', default= pi/25., type=float, metavar='\lambda',
help='the strength of the quartic anharmonic oscillator')
parser.add_argument('--x_max', default=8.5, type=float, metavar='x_{max}',
help='the distance from the center to the border of the simulation space')
parser.add_argument('--grid_size', default = 0.1, type=float, metavar='h',
help='the grid size of the discretized simulation space')
parser.add_argument('--mass', default = 1./pi, type=float, metavar='m',
help='the mass of the simulated particle')
parser.add_argument('--moment', default = 5, type=int,
help='the order of the distribution moments to compute in the compiled function "get_moments"')
args = parser.parse_args()
link_options = ['-Wl,--start-group', os.environ['MKLROOT']+'/lib/intel64/libmkl_intel_ilp64.a', os.environ['MKLROOT']+'/lib/intel64/libmkl_intel_thread.a', os.environ['MKLROOT']+'/lib/intel64/libmkl_core.a', '-Wl,--end-group', '-liomp5', '-lpthread', '-lm', '-ldl']
compiler_options = ['-DMKL_ILP64','-m64']
| true | true |
f7f8c6a8ed3a87cb8591e84ffb27c4da0af65677 | 3,582 | py | Python | dockit/backends/djangodocument/indexers.py | zbyte64/django-dockit | 8d00a46cb0b6237de622fcb6816067078106a0c4 | [
"BSD-3-Clause"
] | 5 | 2015-02-25T17:01:48.000Z | 2021-06-03T07:46:47.000Z | dockit/backends/djangodocument/indexers.py | zbyte64/django-dockit | 8d00a46cb0b6237de622fcb6816067078106a0c4 | [
"BSD-3-Clause"
] | 1 | 2015-03-11T15:19:55.000Z | 2015-04-13T04:14:24.000Z | dockit/backends/djangodocument/indexers.py | zbyte64/django-dockit | 8d00a46cb0b6237de622fcb6816067078106a0c4 | [
"BSD-3-Clause"
] | null | null | null | from django.db.models import Model, Q
from dockit.backends.indexer import BaseIndexer
from dockit.schema import fields#, Document
import dockit.backends.djangodocument.models as indexes
from dockit.backends.djangodocument.backend import ModelIndexStorage
#TODO need a mechanism for back populating indexes, must be task based
class Indexer(object):
def __init__(self, doc_class, index_creator, dotpath, name):
self.doc_class = doc_class
self.index_creator = index_creator
self.dotpath = dotpath
self.name = name
def __call__(self, document):
if self.dotpath in ('pk', '_pk'):
return
try:
value = document.dot_notation(self.dotpath)
except (KeyError, IndexError):
return
if value is None:
return #TODO proper handling
if isinstance(value, (list, set)):
for val in value:
self.index_creator(document.pk, self.name, val)
else:
self.index_creator(document.pk, self.name, value)
class ExactIndexer(BaseIndexer):
INDEXES = [(fields.TextField, indexes.StringIndex),
(fields.CharField, indexes.StringIndex),
(fields.IntegerField, indexes.IntegerIndex),
(fields.FloatField, indexes.FloatIndex),
(fields.DecimalField, indexes.DecimalIndex),
(fields.BooleanField, indexes.BooleanIndex),
(fields.DateField, indexes.DateIndex),
(fields.DateTimeField, indexes.DateTimeIndex),
(fields.TimeField, indexes.TimeIndex),
(Model, indexes.StringIndex),
(fields.ReferenceField, indexes.StringIndex),
(fields.ModelReferenceField, indexes.StringIndex),]
def __init__(self, document, filter_operation):
self.document = document
self.filter_operation = filter_operation
self.dotpath = self.filter_operation.dotpath()
self.generate_index()
def generate_index(self):
collection = self.document._meta.collection
field = self.document._meta.dot_notation_to_field(self.dotpath)
subindex = self._lookup_index(field)
if subindex is None and hasattr(field, 'subfield'):
subindex = self._lookup_index(field.subfield)
if subindex is None:
subindex = indexes.StringIndex
#raise TypeError("Could not identify an apropriate index for: %s" % field)
self.subindex = subindex
func = Indexer(self.document, subindex.objects.db_index, self.dotpath, self.filter_operation.key)
filt = subindex.objects.filter_kwargs_for_operation
values = subindex.objects.values
clear = subindex.objects.clear_db_index
self.index_functions = {'map':func, 'filter':filt, 'values':values, 'clear':clear}
def _lookup_index(self, field):
for key, val in self.INDEXES:
if isinstance(field, key):
return val
def on_document_save(self, instance):
self.index_functions['map'](instance)
def on_document_delete(self, instance):
self.index_functions['clear'](instance.pk)
def filter(self):
return Q(**self.index_functions['filter'](self.filter_operation))
def values(self):
return self.index_functions['values'](self.filter_operation)
ModelIndexStorage.register_indexer(ExactIndexer, 'exact', 'iexact', 'startswith', 'endswith', 'istartswith', 'iendswith', 'year', 'month', 'day', 'lt', 'gt', 'lte', 'gte')
| 38.516129 | 171 | 0.650475 | from django.db.models import Model, Q
from dockit.backends.indexer import BaseIndexer
from dockit.schema import fields
import dockit.backends.djangodocument.models as indexes
from dockit.backends.djangodocument.backend import ModelIndexStorage
class Indexer(object):
def __init__(self, doc_class, index_creator, dotpath, name):
self.doc_class = doc_class
self.index_creator = index_creator
self.dotpath = dotpath
self.name = name
def __call__(self, document):
if self.dotpath in ('pk', '_pk'):
return
try:
value = document.dot_notation(self.dotpath)
except (KeyError, IndexError):
return
if value is None:
return
if isinstance(value, (list, set)):
for val in value:
self.index_creator(document.pk, self.name, val)
else:
self.index_creator(document.pk, self.name, value)
class ExactIndexer(BaseIndexer):
INDEXES = [(fields.TextField, indexes.StringIndex),
(fields.CharField, indexes.StringIndex),
(fields.IntegerField, indexes.IntegerIndex),
(fields.FloatField, indexes.FloatIndex),
(fields.DecimalField, indexes.DecimalIndex),
(fields.BooleanField, indexes.BooleanIndex),
(fields.DateField, indexes.DateIndex),
(fields.DateTimeField, indexes.DateTimeIndex),
(fields.TimeField, indexes.TimeIndex),
(Model, indexes.StringIndex),
(fields.ReferenceField, indexes.StringIndex),
(fields.ModelReferenceField, indexes.StringIndex),]
def __init__(self, document, filter_operation):
self.document = document
self.filter_operation = filter_operation
self.dotpath = self.filter_operation.dotpath()
self.generate_index()
def generate_index(self):
collection = self.document._meta.collection
field = self.document._meta.dot_notation_to_field(self.dotpath)
subindex = self._lookup_index(field)
if subindex is None and hasattr(field, 'subfield'):
subindex = self._lookup_index(field.subfield)
if subindex is None:
subindex = indexes.StringIndex
self.subindex = subindex
func = Indexer(self.document, subindex.objects.db_index, self.dotpath, self.filter_operation.key)
filt = subindex.objects.filter_kwargs_for_operation
values = subindex.objects.values
clear = subindex.objects.clear_db_index
self.index_functions = {'map':func, 'filter':filt, 'values':values, 'clear':clear}
def _lookup_index(self, field):
for key, val in self.INDEXES:
if isinstance(field, key):
return val
def on_document_save(self, instance):
self.index_functions['map'](instance)
def on_document_delete(self, instance):
self.index_functions['clear'](instance.pk)
def filter(self):
return Q(**self.index_functions['filter'](self.filter_operation))
def values(self):
return self.index_functions['values'](self.filter_operation)
ModelIndexStorage.register_indexer(ExactIndexer, 'exact', 'iexact', 'startswith', 'endswith', 'istartswith', 'iendswith', 'year', 'month', 'day', 'lt', 'gt', 'lte', 'gte')
| true | true |
f7f8c6e2a1a99bb0eb636992ece1ebc18068184a | 7,767 | py | Python | telemetry/telemetry/internal/results/story_run_unittest.py | arthesh/catapult | c5ff470c5f62406ee0eb47a4b59acf5fea5f84aa | [
"BSD-3-Clause"
] | null | null | null | telemetry/telemetry/internal/results/story_run_unittest.py | arthesh/catapult | c5ff470c5f62406ee0eb47a4b59acf5fea5f84aa | [
"BSD-3-Clause"
] | null | null | null | telemetry/telemetry/internal/results/story_run_unittest.py | arthesh/catapult | c5ff470c5f62406ee0eb47a4b59acf5fea5f84aa | [
"BSD-3-Clause"
] | null | null | null | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
import os
import unittest
import mock
from telemetry.internal.results import story_run
from telemetry.story import shared_state
from telemetry import story as story_module
from py_utils import tempfile_ext
def TestStory(name, **kwargs):
return story_module.Story(shared_state.SharedState, name=name, **kwargs)
class StoryRunTest(unittest.TestCase):
def setUp(self):
self.story = TestStory('foo')
def testStoryRunFailed(self):
run = story_run.StoryRun(self.story)
run.SetFailed('abc')
self.assertFalse(run.ok)
self.assertTrue(run.failed)
self.assertFalse(run.skipped)
self.assertEquals(run.failure_str, 'abc')
run = story_run.StoryRun(self.story)
run.SetFailed('something is wrong')
self.assertFalse(run.ok)
self.assertTrue(run.failed)
self.assertFalse(run.skipped)
self.assertEquals(run.failure_str, 'something is wrong')
def testStoryRunSkipped(self):
run = story_run.StoryRun(self.story)
run.SetFailed('oops')
run.Skip('test', expected=True)
self.assertFalse(run.ok)
self.assertFalse(run.failed)
self.assertTrue(run.skipped)
self.assertTrue(run.expected)
self.assertEquals(run.failure_str, 'oops')
run = story_run.StoryRun(self.story)
run.Skip('test', expected=False)
self.assertFalse(run.ok)
self.assertFalse(run.failed)
self.assertTrue(run.skipped)
self.assertFalse(run.expected)
self.assertEquals(run.failure_str, None)
def testStoryRunSucceeded(self):
run = story_run.StoryRun(self.story)
self.assertTrue(run.ok)
self.assertFalse(run.failed)
self.assertFalse(run.skipped)
self.assertEquals(run.failure_str, None)
run = story_run.StoryRun(self.story)
self.assertTrue(run.ok)
self.assertFalse(run.failed)
self.assertFalse(run.skipped)
self.assertEquals(run.failure_str, None)
@mock.patch.dict('os.environ', {'GTEST_SHARD_INDEX': '7'})
@mock.patch('telemetry.internal.results.story_run.time')
def testAsDict(self, time_module):
time_module.time.side_effect = [1234567890.987,
1234567900.987]
with tempfile_ext.NamedTemporaryDirectory() as tempdir:
run = story_run.StoryRun(
story=TestStory(name='http://example.com', tags=['tag1', 'tag2']),
test_prefix='benchmark',
index=2,
intermediate_dir=tempdir)
with run.CreateArtifact('logs.txt') as log_file:
log_file.write('hello\n')
run.SetTbmMetrics(['metric1', 'metric2'])
run.Finish()
entry = run.AsDict()
self.assertEqual(
entry,
{
'testResult': {
'testPath': 'benchmark/http%3A%2F%2Fexample.com',
'resultId': '2',
'status': 'PASS',
'expected': True,
'startTime': '2009-02-13T23:31:30.987000Z',
'runDuration': '10.00s',
'outputArtifacts': {
'logs.txt' : {
'filePath': mock.ANY,
'contentType': 'text/plain'
}
},
'tags': [
{'key': 'tbmv2', 'value': 'metric1'},
{'key': 'tbmv2', 'value': 'metric2'},
{'key': 'shard', 'value': '7'},
{'key': 'story_tag', 'value': 'tag1'},
{'key': 'story_tag', 'value': 'tag2'},
],
}
}
)
# Log file is in the {intermediate_dir}/ directory, and file name
# extension is preserved.
logs_file = entry['testResult']['outputArtifacts']['logs.txt']['filePath']
intermediate_dir = os.path.join(tempdir, '')
self.assertTrue(logs_file.startswith(intermediate_dir))
self.assertTrue(logs_file.endswith('.txt'))
def testAddMeasurements(self):
with tempfile_ext.NamedTemporaryDirectory() as tempdir:
run = story_run.StoryRun(self.story, intermediate_dir=tempdir)
run.AddMeasurement('run_time', 'ms', [1, 2, 3])
run.AddMeasurement('foo_bars', 'count', 4,
description='number of foo_bars found')
run.Finish()
artifact = run.GetArtifact(story_run.MEASUREMENTS_NAME)
with open(artifact.local_path) as f:
measurements = json.load(f)
self.assertEqual(measurements, {
'measurements': {
'run_time': {
'unit': 'ms',
'samples': [1, 2, 3],
},
'foo_bars' : {
'unit': 'count',
'samples': [4],
'description': 'number of foo_bars found'
}
}
})
def testAddMeasurementValidation(self):
run = story_run.StoryRun(self.story)
with self.assertRaises(TypeError):
run.AddMeasurement(name=None, unit='ms', samples=[1, 2, 3])
with self.assertRaises(TypeError):
run.AddMeasurement(name='run_time', unit=7, samples=[1, 2, 3])
with self.assertRaises(TypeError):
run.AddMeasurement(name='run_time', unit='ms', samples=[1, None, 3])
with self.assertRaises(TypeError):
run.AddMeasurement(name='run_time', unit='ms', samples=[1, 2, 3],
description=['not', 'a', 'string'])
def testAddMeasurementRaisesAfterFinish(self):
run = story_run.StoryRun(self.story)
run.AddMeasurement('run_time', 'ms', [1, 2, 3])
run.Finish()
with self.assertRaises(AssertionError):
run.AddMeasurement('foo_bars', 'count', 4)
def testAddMeasurementTwiceRaises(self):
run = story_run.StoryRun(self.story)
run.AddMeasurement('foo_bars', 'ms', [1])
with self.assertRaises(AssertionError):
run.AddMeasurement('foo_bars', 'ms', [2])
def testCreateArtifact(self):
with tempfile_ext.NamedTemporaryDirectory() as tempdir:
run = story_run.StoryRun(self.story, intermediate_dir=tempdir)
with run.CreateArtifact('logs.txt') as log_file:
log_file.write('hi\n')
artifact = run.GetArtifact('logs.txt')
with open(artifact.local_path) as f:
self.assertEqual(f.read(), 'hi\n')
self.assertEqual(artifact.content_type, 'text/plain')
def testCaptureArtifact(self):
with tempfile_ext.NamedTemporaryDirectory() as tempdir:
run = story_run.StoryRun(self.story, intermediate_dir=tempdir)
with run.CaptureArtifact('logs.txt') as log_file_name:
with open(log_file_name, 'w') as log_file:
log_file.write('hi\n')
artifact = run.GetArtifact('logs.txt')
with open(artifact.local_path) as f:
self.assertEqual(f.read(), 'hi\n')
self.assertEqual(artifact.content_type, 'text/plain')
def testIterArtifacts(self):
with tempfile_ext.NamedTemporaryDirectory() as tempdir:
run = story_run.StoryRun(self.story, intermediate_dir=tempdir)
with run.CreateArtifact('log/log1.foo'):
pass
with run.CreateArtifact('trace/trace1.json'):
pass
with run.CreateArtifact('trace/trace2.json'):
pass
all_artifacts = list(run.IterArtifacts())
self.assertEqual(3, len(all_artifacts))
logs = list(run.IterArtifacts('log'))
self.assertEqual(1, len(logs))
# Falls back to 'application/octet-stream' due to unknown extension.
self.assertEqual('application/octet-stream', logs[0].content_type)
traces = list(run.IterArtifacts('trace'))
self.assertEqual(2, len(traces))
self.assertTrue(all(t.content_type == 'application/json' for t in traces))
| 35.62844 | 80 | 0.624565 |
import json
import os
import unittest
import mock
from telemetry.internal.results import story_run
from telemetry.story import shared_state
from telemetry import story as story_module
from py_utils import tempfile_ext
def TestStory(name, **kwargs):
return story_module.Story(shared_state.SharedState, name=name, **kwargs)
class StoryRunTest(unittest.TestCase):
def setUp(self):
self.story = TestStory('foo')
def testStoryRunFailed(self):
run = story_run.StoryRun(self.story)
run.SetFailed('abc')
self.assertFalse(run.ok)
self.assertTrue(run.failed)
self.assertFalse(run.skipped)
self.assertEquals(run.failure_str, 'abc')
run = story_run.StoryRun(self.story)
run.SetFailed('something is wrong')
self.assertFalse(run.ok)
self.assertTrue(run.failed)
self.assertFalse(run.skipped)
self.assertEquals(run.failure_str, 'something is wrong')
def testStoryRunSkipped(self):
run = story_run.StoryRun(self.story)
run.SetFailed('oops')
run.Skip('test', expected=True)
self.assertFalse(run.ok)
self.assertFalse(run.failed)
self.assertTrue(run.skipped)
self.assertTrue(run.expected)
self.assertEquals(run.failure_str, 'oops')
run = story_run.StoryRun(self.story)
run.Skip('test', expected=False)
self.assertFalse(run.ok)
self.assertFalse(run.failed)
self.assertTrue(run.skipped)
self.assertFalse(run.expected)
self.assertEquals(run.failure_str, None)
def testStoryRunSucceeded(self):
run = story_run.StoryRun(self.story)
self.assertTrue(run.ok)
self.assertFalse(run.failed)
self.assertFalse(run.skipped)
self.assertEquals(run.failure_str, None)
run = story_run.StoryRun(self.story)
self.assertTrue(run.ok)
self.assertFalse(run.failed)
self.assertFalse(run.skipped)
self.assertEquals(run.failure_str, None)
@mock.patch.dict('os.environ', {'GTEST_SHARD_INDEX': '7'})
@mock.patch('telemetry.internal.results.story_run.time')
def testAsDict(self, time_module):
time_module.time.side_effect = [1234567890.987,
1234567900.987]
with tempfile_ext.NamedTemporaryDirectory() as tempdir:
run = story_run.StoryRun(
story=TestStory(name='http://example.com', tags=['tag1', 'tag2']),
test_prefix='benchmark',
index=2,
intermediate_dir=tempdir)
with run.CreateArtifact('logs.txt') as log_file:
log_file.write('hello\n')
run.SetTbmMetrics(['metric1', 'metric2'])
run.Finish()
entry = run.AsDict()
self.assertEqual(
entry,
{
'testResult': {
'testPath': 'benchmark/http%3A%2F%2Fexample.com',
'resultId': '2',
'status': 'PASS',
'expected': True,
'startTime': '2009-02-13T23:31:30.987000Z',
'runDuration': '10.00s',
'outputArtifacts': {
'logs.txt' : {
'filePath': mock.ANY,
'contentType': 'text/plain'
}
},
'tags': [
{'key': 'tbmv2', 'value': 'metric1'},
{'key': 'tbmv2', 'value': 'metric2'},
{'key': 'shard', 'value': '7'},
{'key': 'story_tag', 'value': 'tag1'},
{'key': 'story_tag', 'value': 'tag2'},
],
}
}
)
logs_file = entry['testResult']['outputArtifacts']['logs.txt']['filePath']
intermediate_dir = os.path.join(tempdir, '')
self.assertTrue(logs_file.startswith(intermediate_dir))
self.assertTrue(logs_file.endswith('.txt'))
def testAddMeasurements(self):
with tempfile_ext.NamedTemporaryDirectory() as tempdir:
run = story_run.StoryRun(self.story, intermediate_dir=tempdir)
run.AddMeasurement('run_time', 'ms', [1, 2, 3])
run.AddMeasurement('foo_bars', 'count', 4,
description='number of foo_bars found')
run.Finish()
artifact = run.GetArtifact(story_run.MEASUREMENTS_NAME)
with open(artifact.local_path) as f:
measurements = json.load(f)
self.assertEqual(measurements, {
'measurements': {
'run_time': {
'unit': 'ms',
'samples': [1, 2, 3],
},
'foo_bars' : {
'unit': 'count',
'samples': [4],
'description': 'number of foo_bars found'
}
}
})
def testAddMeasurementValidation(self):
run = story_run.StoryRun(self.story)
with self.assertRaises(TypeError):
run.AddMeasurement(name=None, unit='ms', samples=[1, 2, 3])
with self.assertRaises(TypeError):
run.AddMeasurement(name='run_time', unit=7, samples=[1, 2, 3])
with self.assertRaises(TypeError):
run.AddMeasurement(name='run_time', unit='ms', samples=[1, None, 3])
with self.assertRaises(TypeError):
run.AddMeasurement(name='run_time', unit='ms', samples=[1, 2, 3],
description=['not', 'a', 'string'])
def testAddMeasurementRaisesAfterFinish(self):
run = story_run.StoryRun(self.story)
run.AddMeasurement('run_time', 'ms', [1, 2, 3])
run.Finish()
with self.assertRaises(AssertionError):
run.AddMeasurement('foo_bars', 'count', 4)
def testAddMeasurementTwiceRaises(self):
run = story_run.StoryRun(self.story)
run.AddMeasurement('foo_bars', 'ms', [1])
with self.assertRaises(AssertionError):
run.AddMeasurement('foo_bars', 'ms', [2])
def testCreateArtifact(self):
with tempfile_ext.NamedTemporaryDirectory() as tempdir:
run = story_run.StoryRun(self.story, intermediate_dir=tempdir)
with run.CreateArtifact('logs.txt') as log_file:
log_file.write('hi\n')
artifact = run.GetArtifact('logs.txt')
with open(artifact.local_path) as f:
self.assertEqual(f.read(), 'hi\n')
self.assertEqual(artifact.content_type, 'text/plain')
def testCaptureArtifact(self):
with tempfile_ext.NamedTemporaryDirectory() as tempdir:
run = story_run.StoryRun(self.story, intermediate_dir=tempdir)
with run.CaptureArtifact('logs.txt') as log_file_name:
with open(log_file_name, 'w') as log_file:
log_file.write('hi\n')
artifact = run.GetArtifact('logs.txt')
with open(artifact.local_path) as f:
self.assertEqual(f.read(), 'hi\n')
self.assertEqual(artifact.content_type, 'text/plain')
def testIterArtifacts(self):
with tempfile_ext.NamedTemporaryDirectory() as tempdir:
run = story_run.StoryRun(self.story, intermediate_dir=tempdir)
with run.CreateArtifact('log/log1.foo'):
pass
with run.CreateArtifact('trace/trace1.json'):
pass
with run.CreateArtifact('trace/trace2.json'):
pass
all_artifacts = list(run.IterArtifacts())
self.assertEqual(3, len(all_artifacts))
logs = list(run.IterArtifacts('log'))
self.assertEqual(1, len(logs))
self.assertEqual('application/octet-stream', logs[0].content_type)
traces = list(run.IterArtifacts('trace'))
self.assertEqual(2, len(traces))
self.assertTrue(all(t.content_type == 'application/json' for t in traces))
| true | true |
f7f8c71defb7f76045db9f8b5be4541e61000970 | 11,352 | py | Python | nova/api/openstack/compute/views/servers.py | ZhanHan/nova | 4033e0166ca16ef380705cfdd928083be8bf4f68 | [
"Apache-2.0"
] | 1 | 2019-07-29T10:30:24.000Z | 2019-07-29T10:30:24.000Z | nova/api/openstack/compute/views/servers.py | ZhanHan/nova | 4033e0166ca16ef380705cfdd928083be8bf4f68 | [
"Apache-2.0"
] | null | null | null | nova/api/openstack/compute/views/servers.py | ZhanHan/nova | 4033e0166ca16ef380705cfdd928083be8bf4f68 | [
"Apache-2.0"
] | 1 | 2020-07-24T00:40:05.000Z | 2020-07-24T00:40:05.000Z | # Copyright 2010-2011 OpenStack Foundation
# Copyright 2011 Piston Cloud Computing, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import hashlib
from oslo_log import log as logging
from nova.api.openstack import api_version_request
from nova.api.openstack import common
from nova.api.openstack.compute.views import addresses as views_addresses
from nova.api.openstack.compute.views import flavors as views_flavors
from nova.api.openstack.compute.views import images as views_images
from nova.i18n import _LW
from nova.objects import base as obj_base
from nova import utils
LOG = logging.getLogger(__name__)
class ViewBuilder(common.ViewBuilder):
"""Model a server API response as a python dictionary."""
_collection_name = "servers"
_progress_statuses = (
"ACTIVE",
"BUILD",
"REBUILD",
"RESIZE",
"VERIFY_RESIZE",
"MIGRATING",
)
_fault_statuses = (
"ERROR", "DELETED"
)
# These are the lazy-loadable instance attributes required for showing
# details about an instance. Add to this list as new things need to be
# shown.
_show_expected_attrs = ['flavor', 'info_cache', 'metadata']
def __init__(self):
"""Initialize view builder."""
super(ViewBuilder, self).__init__()
self._address_builder = views_addresses.ViewBuilder()
self._image_builder = views_images.ViewBuilder()
self._flavor_builder = views_flavors.ViewBuilder()
def create(self, request, instance):
"""View that should be returned when an instance is created."""
return {
"server": {
"id": instance["uuid"],
"links": self._get_links(request,
instance["uuid"],
self._collection_name),
# NOTE(sdague): historically this was the
# os-disk-config extension, but now that extensions
# are gone, we merge these attributes here.
"OS-DCF:diskConfig": (
'AUTO' if instance.get('auto_disk_config') else 'MANUAL'),
},
}
def basic(self, request, instance):
"""Generic, non-detailed view of an instance."""
return {
"server": {
"id": instance["uuid"],
"name": instance["display_name"],
"links": self._get_links(request,
instance["uuid"],
self._collection_name),
},
}
def get_show_expected_attrs(self, expected_attrs=None):
"""Returns a list of lazy-loadable expected attributes used by show
This should be used when getting the instances from the database so
that the necessary attributes are pre-loaded before needing to build
the show response where lazy-loading can fail if an instance was
deleted.
:param list expected_attrs: The list of expected attributes that will
be requested in addition to what this view builder requires. This
method will merge the two lists and return what should be
ultimately used when getting an instance from the database.
:returns: merged and sorted list of expected attributes
"""
if expected_attrs is None:
expected_attrs = []
# NOTE(mriedem): We sort the list so we can have predictable test
# results.
return sorted(list(set(self._show_expected_attrs + expected_attrs)))
def show(self, request, instance, extend_address=True):
"""Detailed view of a single instance."""
ip_v4 = instance.get('access_ip_v4')
ip_v6 = instance.get('access_ip_v6')
server = {
"server": {
"id": instance["uuid"],
"name": instance["display_name"],
"status": self._get_vm_status(instance),
"tenant_id": instance.get("project_id") or "",
"user_id": instance.get("user_id") or "",
"metadata": self._get_metadata(instance),
"hostId": self._get_host_id(instance) or "",
"image": self._get_image(request, instance),
"flavor": self._get_flavor(request, instance),
"created": utils.isotime(instance["created_at"]),
"updated": utils.isotime(instance["updated_at"]),
"addresses": self._get_addresses(request, instance,
extend_address),
"accessIPv4": str(ip_v4) if ip_v4 is not None else '',
"accessIPv6": str(ip_v6) if ip_v6 is not None else '',
"links": self._get_links(request,
instance["uuid"],
self._collection_name),
# NOTE(sdague): historically this was the
# os-disk-config extension, but now that extensions
# are gone, we merge these attributes here.
"OS-DCF:diskConfig": (
'AUTO' if instance.get('auto_disk_config') else 'MANUAL'),
},
}
if server["server"]["status"] in self._fault_statuses:
_inst_fault = self._get_fault(request, instance)
if _inst_fault:
server['server']['fault'] = _inst_fault
if server["server"]["status"] in self._progress_statuses:
server["server"]["progress"] = instance.get("progress", 0)
if api_version_request.is_supported(request, min_version="2.9"):
server["server"]["locked"] = (True if instance["locked_by"]
else False)
if api_version_request.is_supported(request, min_version="2.19"):
server["server"]["description"] = instance.get(
"display_description")
if api_version_request.is_supported(request, min_version="2.26"):
server["server"]["tags"] = [t.tag for t in instance.tags]
return server
def index(self, request, instances):
"""Show a list of servers without many details."""
coll_name = self._collection_name
return self._list_view(self.basic, request, instances, coll_name)
def detail(self, request, instances):
"""Detailed view of a list of instance."""
coll_name = self._collection_name + '/detail'
return self._list_view(self.show, request, instances, coll_name)
def _list_view(self, func, request, servers, coll_name):
"""Provide a view for a list of servers.
:param func: Function used to format the server data
:param request: API request
:param servers: List of servers in dictionary format
:param coll_name: Name of collection, used to generate the next link
for a pagination query
:returns: Server data in dictionary format
"""
server_list = [func(request, server)["server"] for server in servers]
servers_links = self._get_collection_links(request,
servers,
coll_name)
servers_dict = dict(servers=server_list)
if servers_links:
servers_dict["servers_links"] = servers_links
return servers_dict
@staticmethod
def _get_metadata(instance):
# FIXME(danms): Transitional support for objects
metadata = instance.get('metadata')
if isinstance(instance, obj_base.NovaObject):
return metadata or {}
else:
return utils.instance_meta(instance)
@staticmethod
def _get_vm_status(instance):
# If the instance is deleted the vm and task states don't really matter
if instance.get("deleted"):
return "DELETED"
return common.status_from_state(instance.get("vm_state"),
instance.get("task_state"))
@staticmethod
def _get_host_id(instance):
host = instance.get("host")
project = str(instance.get("project_id"))
if host:
data = (project + host).encode('utf-8')
sha_hash = hashlib.sha224(data)
return sha_hash.hexdigest()
def _get_addresses(self, request, instance, extend_address=False):
context = request.environ["nova.context"]
networks = common.get_networks_for_instance(context, instance)
return self._address_builder.index(networks,
extend_address)["addresses"]
def _get_image(self, request, instance):
image_ref = instance["image_ref"]
if image_ref:
image_id = str(common.get_id_from_href(image_ref))
bookmark = self._image_builder._get_bookmark_link(request,
image_id,
"images")
return {
"id": image_id,
"links": [{
"rel": "bookmark",
"href": bookmark,
}],
}
else:
return ""
def _get_flavor(self, request, instance):
instance_type = instance.get_flavor()
if not instance_type:
LOG.warning(_LW("Instance has had its instance_type removed "
"from the DB"), instance=instance)
return {}
flavor_id = instance_type["flavorid"]
flavor_bookmark = self._flavor_builder._get_bookmark_link(request,
flavor_id,
"flavors")
return {
"id": str(flavor_id),
"links": [{
"rel": "bookmark",
"href": flavor_bookmark,
}],
}
def _get_fault(self, request, instance):
# This can result in a lazy load of the fault information
fault = instance.fault
if not fault:
return None
fault_dict = {
"code": fault["code"],
"created": utils.isotime(fault["created_at"]),
"message": fault["message"],
}
if fault.get('details', None):
is_admin = False
context = request.environ["nova.context"]
if context:
is_admin = getattr(context, 'is_admin', False)
if is_admin or fault['code'] != 500:
fault_dict['details'] = fault["details"]
return fault_dict
| 39.692308 | 79 | 0.568798 |
import hashlib
from oslo_log import log as logging
from nova.api.openstack import api_version_request
from nova.api.openstack import common
from nova.api.openstack.compute.views import addresses as views_addresses
from nova.api.openstack.compute.views import flavors as views_flavors
from nova.api.openstack.compute.views import images as views_images
from nova.i18n import _LW
from nova.objects import base as obj_base
from nova import utils
LOG = logging.getLogger(__name__)
class ViewBuilder(common.ViewBuilder):
_collection_name = "servers"
_progress_statuses = (
"ACTIVE",
"BUILD",
"REBUILD",
"RESIZE",
"VERIFY_RESIZE",
"MIGRATING",
)
_fault_statuses = (
"ERROR", "DELETED"
)
_show_expected_attrs = ['flavor', 'info_cache', 'metadata']
def __init__(self):
super(ViewBuilder, self).__init__()
self._address_builder = views_addresses.ViewBuilder()
self._image_builder = views_images.ViewBuilder()
self._flavor_builder = views_flavors.ViewBuilder()
def create(self, request, instance):
return {
"server": {
"id": instance["uuid"],
"links": self._get_links(request,
instance["uuid"],
self._collection_name),
"OS-DCF:diskConfig": (
'AUTO' if instance.get('auto_disk_config') else 'MANUAL'),
},
}
def basic(self, request, instance):
return {
"server": {
"id": instance["uuid"],
"name": instance["display_name"],
"links": self._get_links(request,
instance["uuid"],
self._collection_name),
},
}
def get_show_expected_attrs(self, expected_attrs=None):
if expected_attrs is None:
expected_attrs = []
return sorted(list(set(self._show_expected_attrs + expected_attrs)))
def show(self, request, instance, extend_address=True):
ip_v4 = instance.get('access_ip_v4')
ip_v6 = instance.get('access_ip_v6')
server = {
"server": {
"id": instance["uuid"],
"name": instance["display_name"],
"status": self._get_vm_status(instance),
"tenant_id": instance.get("project_id") or "",
"user_id": instance.get("user_id") or "",
"metadata": self._get_metadata(instance),
"hostId": self._get_host_id(instance) or "",
"image": self._get_image(request, instance),
"flavor": self._get_flavor(request, instance),
"created": utils.isotime(instance["created_at"]),
"updated": utils.isotime(instance["updated_at"]),
"addresses": self._get_addresses(request, instance,
extend_address),
"accessIPv4": str(ip_v4) if ip_v4 is not None else '',
"accessIPv6": str(ip_v6) if ip_v6 is not None else '',
"links": self._get_links(request,
instance["uuid"],
self._collection_name),
"OS-DCF:diskConfig": (
'AUTO' if instance.get('auto_disk_config') else 'MANUAL'),
},
}
if server["server"]["status"] in self._fault_statuses:
_inst_fault = self._get_fault(request, instance)
if _inst_fault:
server['server']['fault'] = _inst_fault
if server["server"]["status"] in self._progress_statuses:
server["server"]["progress"] = instance.get("progress", 0)
if api_version_request.is_supported(request, min_version="2.9"):
server["server"]["locked"] = (True if instance["locked_by"]
else False)
if api_version_request.is_supported(request, min_version="2.19"):
server["server"]["description"] = instance.get(
"display_description")
if api_version_request.is_supported(request, min_version="2.26"):
server["server"]["tags"] = [t.tag for t in instance.tags]
return server
def index(self, request, instances):
coll_name = self._collection_name
return self._list_view(self.basic, request, instances, coll_name)
def detail(self, request, instances):
coll_name = self._collection_name + '/detail'
return self._list_view(self.show, request, instances, coll_name)
def _list_view(self, func, request, servers, coll_name):
server_list = [func(request, server)["server"] for server in servers]
servers_links = self._get_collection_links(request,
servers,
coll_name)
servers_dict = dict(servers=server_list)
if servers_links:
servers_dict["servers_links"] = servers_links
return servers_dict
@staticmethod
def _get_metadata(instance):
metadata = instance.get('metadata')
if isinstance(instance, obj_base.NovaObject):
return metadata or {}
else:
return utils.instance_meta(instance)
@staticmethod
def _get_vm_status(instance):
if instance.get("deleted"):
return "DELETED"
return common.status_from_state(instance.get("vm_state"),
instance.get("task_state"))
@staticmethod
def _get_host_id(instance):
host = instance.get("host")
project = str(instance.get("project_id"))
if host:
data = (project + host).encode('utf-8')
sha_hash = hashlib.sha224(data)
return sha_hash.hexdigest()
def _get_addresses(self, request, instance, extend_address=False):
context = request.environ["nova.context"]
networks = common.get_networks_for_instance(context, instance)
return self._address_builder.index(networks,
extend_address)["addresses"]
def _get_image(self, request, instance):
image_ref = instance["image_ref"]
if image_ref:
image_id = str(common.get_id_from_href(image_ref))
bookmark = self._image_builder._get_bookmark_link(request,
image_id,
"images")
return {
"id": image_id,
"links": [{
"rel": "bookmark",
"href": bookmark,
}],
}
else:
return ""
def _get_flavor(self, request, instance):
instance_type = instance.get_flavor()
if not instance_type:
LOG.warning(_LW("Instance has had its instance_type removed "
"from the DB"), instance=instance)
return {}
flavor_id = instance_type["flavorid"]
flavor_bookmark = self._flavor_builder._get_bookmark_link(request,
flavor_id,
"flavors")
return {
"id": str(flavor_id),
"links": [{
"rel": "bookmark",
"href": flavor_bookmark,
}],
}
def _get_fault(self, request, instance):
# This can result in a lazy load of the fault information
fault = instance.fault
if not fault:
return None
fault_dict = {
"code": fault["code"],
"created": utils.isotime(fault["created_at"]),
"message": fault["message"],
}
if fault.get('details', None):
is_admin = False
context = request.environ["nova.context"]
if context:
is_admin = getattr(context, 'is_admin', False)
if is_admin or fault['code'] != 500:
fault_dict['details'] = fault["details"]
return fault_dict
| true | true |
f7f8c757aff166e3b87332ee4229303248901a0c | 24,471 | py | Python | salt/modules/win_pkg.py | nshalman/salt | e162ce8aca1dc3a6bf35a86c779c41469d0adfb8 | [
"Apache-2.0"
] | null | null | null | salt/modules/win_pkg.py | nshalman/salt | e162ce8aca1dc3a6bf35a86c779c41469d0adfb8 | [
"Apache-2.0"
] | null | null | null | salt/modules/win_pkg.py | nshalman/salt | e162ce8aca1dc3a6bf35a86c779c41469d0adfb8 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
'''
A module to manage software on Windows
:depends: - win32com
- win32con
- win32api
- pywintypes
'''
# Import third party libs
try:
import win32api
import win32con
HAS_DEPENDENCIES = True
except ImportError:
HAS_DEPENDENCIES = False
# Import python libs
import copy
import logging
try:
import msgpack
except ImportError:
import msgpack_pure as msgpack
import os
import locale
from distutils.version import LooseVersion # pylint: disable=E0611
import re
# Import salt libs
import salt.utils
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Set the virtual pkg module if the os is Windows
'''
if salt.utils.is_windows() and HAS_DEPENDENCIES:
return __virtualname__
return False
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
if len(names) == 0:
return ''
# Initialize the return dict with empty strings
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if salt.utils.is_true(kwargs.get('refresh', True)):
refresh_db()
installed_pkgs = list_pkgs(versions_as_list=True)
log.trace('List of installed packages: {0}'.format(installed_pkgs))
# iterate over all requested package names
for name in names:
latest_installed = '0'
latest_available = '0'
# get latest installed version of package
if name in installed_pkgs:
log.trace('Sorting out the latest available version of {0}'.format(name))
latest_installed = sorted(installed_pkgs[name], cmp=_reverse_cmp_pkg_versions).pop()
log.debug('Latest installed version of package {0} is {1}'.format(name, latest_installed))
# get latest available (from win_repo) version of package
pkg_info = _get_package_info(name)
log.trace('Raw win_repo pkg_info for {0} is {1}'.format(name, pkg_info))
latest_available = _get_latest_pkg_version(pkg_info)
if latest_available:
log.debug('Latest available version of package {0} is {1}'.format(name, latest_available))
# check, whether latest available version is newer than latest installed version
if salt.utils.compare_versions(ver1=str(latest_available),
oper='>',
ver2=str(latest_installed)):
log.debug('Upgrade of {0} from {1} to {2} is available'.format(name, latest_installed, latest_available))
ret[name] = latest_available
else:
log.debug('No newer version than {0} of {1} is available'.format(latest_installed, name))
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def upgrade_available(name):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def list_upgrades(refresh=True):
'''
List all available package upgrades on this system
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
if salt.utils.is_true(refresh):
refresh_db()
ret = {}
for name, data in get_repo_data().get('repo', {}).items():
if version(name):
latest = latest_version(name)
if latest:
ret[name] = latest
return ret
def list_available(*names):
'''
Return a list of available versions of the specified package.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_available <package name>
salt '*' pkg.list_available <package name01> <package name02>
'''
if not names:
return ''
if len(names) == 1:
pkginfo = _get_package_info(names[0])
if not pkginfo:
return ''
versions = pkginfo.keys()
else:
versions = {}
for name in names:
pkginfo = _get_package_info(name)
if not pkginfo:
continue
versions[name] = pkginfo.keys() if pkginfo else []
versions = sorted(versions, cmp=_reverse_cmp_pkg_versions)
return versions
def version(*names, **kwargs):
'''
Returns a version if the package is installed, else returns an empty string
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
'''
win_names = []
ret = {}
if len(names) == 1:
val = __salt__['pkg_resource.version'](*names, **kwargs)
if len(val):
return val
return ''
if len(names) > 1:
reverse_dict = {}
nums = __salt__['pkg_resource.version'](*names, **kwargs)
if len(nums):
for num, val in nums.iteritems():
if len(val) > 0:
try:
ret[reverse_dict[num]] = val
except KeyError:
ret[num] = val
return ret
return dict([(x, '') for x in names])
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
if 'pkg.list_pkgs' in __context__:
if versions_as_list:
return __context__['pkg.list_pkgs']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs'])
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {}
name_map = _get_name_map()
with salt.utils.winapi.Com():
for key, val in _get_reg_software().iteritems():
if key in name_map:
key = name_map[key]
__salt__['pkg_resource.add_pkg'](ret, key, val)
for key, val in _get_msi_software().iteritems():
if key in name_map:
key = name_map[key]
__salt__['pkg_resource.add_pkg'](ret, key, val)
__salt__['pkg_resource.sort_pkglist'](ret)
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _search_software(target):
'''
This searches the msi product databases for name matches
of the list of target products, it will return a dict with
values added to the list passed in
'''
search_results = {}
software = dict(
list(_get_reg_software().items()) +
list(_get_msi_software().items()))
for key, value in software.items():
if key is not None:
if target.lower() in key.lower():
search_results[key] = value
return search_results
def _get_msi_software():
'''
Uses powershell to search the msi product databases, returns a
dict keyed on the product name as the key and the version as the
value. If powershell is not available, returns `{}`
'''
win32_products = {}
# Don't use WMI to select from `Win32_product`, that has nasty
# side effects. Use the `WindowsInstaller.Installer` COM object's
# `ProductsEx`. Jumping through powershell because `ProductsEx` is
# a get property that takes 3 arguments, and `win32com` can't call
# that
#
# see https://github.com/saltstack/salt/issues/12550 for detail
# powershell script to fetch (name, version) from COM, and write
# without word-wrapping. Attempting to target minimal powershell
# versions
ps = '''
$msi = New-Object -ComObject WindowsInstaller.Installer;
$msi.GetType().InvokeMember('ProductsEx', 'GetProperty', $null, $msi, ('', 's-1-1-0', 7))
| select @{
name='name';
expression={$_.GetType().InvokeMember('InstallProperty', 'GetProperty', $null, $_, ('ProductName'))}
},
@{
name='version';
expression={$_.GetType().InvokeMember('InstallProperty', 'GetProperty', $null, $_, ('VersionString'))}
}
| Write-host
'''.replace('\n', ' ') # make this a one-liner
ret = __salt__['cmd.run_all'](ps, shell='powershell', python_shell=True)
# sometimes the powershell reflection fails on a single product,
# giving us a non-zero return code AND useful output. Ignore RC
# and just try to process stdout, which should empty if the cmd
# failed.
#
# each line of output looks like:
#
# `@{name=PRD_NAME; version=PRD_VER}`
pattern = r'@{name=(.+); version=(.+)}'
for m in re.finditer(pattern, ret['stdout']):
(prd_name, prd_ver) = m.groups()
win32_products[prd_name] = prd_ver
return win32_products
def _get_reg_software():
'''
This searches the uninstall keys in the registry to find
a match in the sub keys, it will return a dict with the
display name as the key and the version as the value
'''
reg_software = {}
#This is a list of default OS reg entries that don't seem to be installed
#software and no version information exists on any of these items
ignore_list = ['AddressBook',
'Connection Manager',
'DirectDrawEx',
'Fontcore',
'IE40',
'IE4Data',
'IE5BAKEX',
'IEData',
'MobileOptionPack',
'SchedulingAgent',
'WIC'
]
encoding = locale.getpreferredencoding()
#attempt to corral the wild west of the multiple ways to install
#software in windows
reg_entries = dict(list(_get_user_keys().items()) +
list(_get_machine_keys().items()))
for reg_hive, reg_keys in reg_entries.items():
for reg_key in reg_keys:
try:
reg_handle = win32api.RegOpenKeyEx(
reg_hive,
reg_key,
0,
win32con.KEY_READ)
except Exception:
pass
#Unsinstall key may not exist for all users
for name, num, blank, time in win32api.RegEnumKeyEx(reg_handle):
prd_uninst_key = "\\".join([reg_key, name])
#These reg values aren't guaranteed to exist
windows_installer = _get_reg_value(
reg_hive,
prd_uninst_key,
'WindowsInstaller')
if windows_installer != 'Not Found' and windows_installer:
continue
prd_name = _get_reg_value(
reg_hive,
prd_uninst_key,
"DisplayName")
try:
prd_name = prd_name.decode(encoding)
except Exception:
pass
prd_ver = _get_reg_value(
reg_hive,
prd_uninst_key,
"DisplayVersion")
if name not in ignore_list:
if prd_name != 'Not Found':
# some MS Office updates don't register a product name which means
# their information is useless
if prd_name != '':
reg_software[prd_name] = prd_ver
return reg_software
def _get_machine_keys():
'''
This will return the hive 'const' value and some registry keys where
installed software information has been known to exist for the
HKEY_LOCAL_MACHINE hive
'''
machine_hive_and_keys = {}
machine_keys = [
"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
"Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
]
machine_hive = win32con.HKEY_LOCAL_MACHINE
machine_hive_and_keys[machine_hive] = machine_keys
return machine_hive_and_keys
def _get_user_keys():
'''
This will return the hive 'const' value and some registry keys where
installed software information has been known to exist for the
HKEY_USERS hive
'''
user_hive_and_keys = {}
user_keys = []
users_hive = win32con.HKEY_USERS
#skip some built in and default users since software information in these
#keys is limited
skip_users = ['.DEFAULT',
'S-1-5-18',
'S-1-5-19',
'S-1-5-20']
sw_uninst_key = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
reg_handle = win32api.RegOpenKeyEx(
users_hive,
'',
0,
win32con.KEY_READ)
for name, num, blank, time in win32api.RegEnumKeyEx(reg_handle):
#this is some identical key of a sid that contains some software names
#but no detailed information about the software installed for that user
if '_Classes' in name:
break
if name not in skip_users:
usr_sw_uninst_key = "\\".join([name, sw_uninst_key])
user_keys.append(usr_sw_uninst_key)
user_hive_and_keys[users_hive] = user_keys
return user_hive_and_keys
def _get_reg_value(reg_hive, reg_key, value_name=''):
'''
Read one value from Windows registry.
If 'name' is empty map, reads default value.
'''
try:
key_handle = win32api.RegOpenKeyEx(
reg_hive, reg_key, 0, win32con.KEY_ALL_ACCESS)
value_data, value_type = win32api.RegQueryValueEx(key_handle,
value_name)
win32api.RegCloseKey(key_handle)
except Exception:
value_data = 'Not Found'
return value_data
def refresh_db(saltenv='base'):
'''
Just recheck the repository and return a dict::
{'<database name>': Bool}
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
__context__.pop('winrepo.data', None)
repocache = __opts__['win_repo_cachefile']
cached_repo = __salt__['cp.is_cached'](repocache, saltenv)
if not cached_repo:
# It's not cached. Cache it, mate.
cached_repo = __salt__['cp.cache_file'](repocache, saltenv)
return True
# Check if the master's cache file has changed
if __salt__['cp.hash_file'](repocache) != __salt__['cp.hash_file'](cached_repo, saltenv):
cached_repo = __salt__['cp.cache_file'](repocache, saltenv)
return True
def install(name=None, refresh=False, pkgs=None, saltenv='base', **kwargs):
'''
Install the passed package
Return a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
'''
if salt.utils.is_true(refresh):
refresh_db()
# Ignore pkg_type from parse_targets, Windows does not support the "sources"
# argument
pkg_params = __salt__['pkg_resource.parse_targets'](name,
pkgs,
**kwargs)[0]
if pkg_params is None or len(pkg_params) == 0:
return {}
old = list_pkgs()
if pkgs is None and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
pkg_params = {name:
{
'version': kwargs.get('version'),
'extra_install_flags': kwargs.get('extra_install_flags')}}
for pkg_name, options in pkg_params.iteritems():
pkginfo = _get_package_info(pkg_name)
if not pkginfo:
log.error('Unable to locate package {0}'.format(pkg_name))
continue
version_num = options and options.get('version') or _get_latest_pkg_version(pkginfo)
if version_num in [old.get(pkginfo[x]['full_name']) for x in pkginfo]:
# Desired version number already installed
continue
elif version_num not in pkginfo:
log.error('Version {0} not found for package '
'{1}'.format(version_num, pkg_name))
continue
installer = pkginfo[version_num].get('installer')
if not installer:
log.error('No installer configured for version {0} of package '
'{1}'.format(version_num, pkg_name))
if installer.startswith('salt:') \
or installer.startswith('http:') \
or installer.startswith('https:') \
or installer.startswith('ftp:'):
cached_pkg = __salt__['cp.is_cached'](installer, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
if __salt__['cp.hash_file'](installer, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
else:
cached_pkg = installer
cached_pkg = cached_pkg.replace('/', '\\')
msiexec = pkginfo[version_num].get('msiexec')
install_flags = '{0} {1}'.format(pkginfo[version_num]['install_flags'], options and options.get('extra_install_flags') or "")
cmd = []
if msiexec:
cmd.extend(['msiexec', '/i'])
cmd.append(cached_pkg)
cmd.extend(install_flags.split())
__salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.compare_dicts(old, new)
def upgrade(refresh=True):
'''
Run a full system upgrade
Return a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
log.warning('pkg.upgrade not implemented on Windows yet')
# Uncomment the below once pkg.upgrade has been implemented
#if salt.utils.is_true(refresh):
# refresh_db()
return {}
def remove(name=None, pkgs=None, version=None, extra_uninstall_flags=None, **kwargs):
'''
Remove packages.
name
The name of the package to be deleted.
version
The version of the package to be deleted. If this option is used in
combination with the ``pkgs`` option below, then this version will be
applied to all targeted packages.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
pkg_params = __salt__['pkg_resource.parse_targets'](name,
pkgs,
**kwargs)[0]
old = list_pkgs()
for target in pkg_params:
pkginfo = _get_package_info(target)
if not pkginfo:
log.error('Unable to locate package {0}'.format(name))
continue
if not version:
version = _get_latest_pkg_version(pkginfo)
uninstaller = pkginfo[version].get('uninstaller')
if not uninstaller:
uninstaller = pkginfo[version].get('installer')
if not uninstaller:
return 'Error: No installer or uninstaller configured for package {0}'.format(name)
if uninstaller.startswith('salt:'):
cached_pkg = \
__salt__['cp.is_cached'](uninstaller)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = \
__salt__['cp.cache_file'](uninstaller)
else:
cached_pkg = uninstaller
cached_pkg = cached_pkg.replace('/', '\\')
if not os.path.exists(os.path.expandvars(cached_pkg)) \
and '(x86)' in cached_pkg:
cached_pkg = cached_pkg.replace('(x86)', '')
expanded_cached_pkg = str(os.path.expandvars(cached_pkg))
uninstall_flags = str(pkginfo[version].get('uninstall_flags', ''))
cmd = []
if pkginfo[version].get('msiexec'):
cmd.extend(['msiexec', '/x'])
cmd.append(expanded_cached_pkg)
cmd.extend(uninstall_flags.split())
if extra_uninstall_flags:
cmd.extend(str(extra_uninstall_flags).split())
__salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.compare_dicts(old, new)
def purge(name=None, pkgs=None, version=None, **kwargs):
'''
Package purges are not supported, this function is identical to
``remove()``.
name
The name of the package to be deleted.
version
The version of the package to be deleted. If this option is used in
combination with the ``pkgs`` option below, then this version will be
applied to all targeted packages.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs, version=version, **kwargs)
def get_repo_data(saltenv='base'):
'''
Returns the cached winrepo data
CLI Example:
.. code-block:: bash
salt '*' pkg.get_repo_data
'''
#if 'winrepo.data' in __context__:
# return __context__['winrepo.data']
repocache = __opts__['win_repo_cachefile']
cached_repo = __salt__['cp.is_cached'](repocache, saltenv)
if not cached_repo:
__salt__['pkg.refresh_db']()
try:
with salt.utils.fopen(cached_repo, 'rb') as repofile:
try:
repodata = msgpack.loads(repofile.read()) or {}
#__context__['winrepo.data'] = repodata
return repodata
except Exception as exc:
log.exception(exc)
return {}
except IOError as exc:
log.error('Not able to read repo file')
log.exception(exc)
return {}
def _get_name_map():
'''
Return a reverse map of full pkg names to the names recognized by winrepo.
'''
return get_repo_data().get('name_map', {})
def _get_package_info(name):
'''
Return package info.
Returns empty map if package not available
TODO: Add option for version
'''
return get_repo_data().get('repo', {}).get(name, {})
def _reverse_cmp_pkg_versions(pkg1, pkg2):
'''
Compare software package versions
'''
if LooseVersion(pkg1) > LooseVersion(pkg2):
return 1
else:
return -1
def _get_latest_pkg_version(pkginfo):
if len(pkginfo) == 1:
return pkginfo.iterkeys().next()
return sorted(pkginfo, cmp=_reverse_cmp_pkg_versions).pop()
| 31.65718 | 133 | 0.594663 |
try:
import win32api
import win32con
HAS_DEPENDENCIES = True
except ImportError:
HAS_DEPENDENCIES = False
import copy
import logging
try:
import msgpack
except ImportError:
import msgpack_pure as msgpack
import os
import locale
from distutils.version import LooseVersion
import re
import salt.utils
log = logging.getLogger(__name__)
__virtualname__ = 'pkg'
def __virtual__():
if salt.utils.is_windows() and HAS_DEPENDENCIES:
return __virtualname__
return False
def latest_version(*names, **kwargs):
if len(names) == 0:
return ''
# Initialize the return dict with empty strings
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if salt.utils.is_true(kwargs.get('refresh', True)):
refresh_db()
installed_pkgs = list_pkgs(versions_as_list=True)
log.trace('List of installed packages: {0}'.format(installed_pkgs))
# iterate over all requested package names
for name in names:
latest_installed = '0'
latest_available = '0'
# get latest installed version of package
if name in installed_pkgs:
log.trace('Sorting out the latest available version of {0}'.format(name))
latest_installed = sorted(installed_pkgs[name], cmp=_reverse_cmp_pkg_versions).pop()
log.debug('Latest installed version of package {0} is {1}'.format(name, latest_installed))
# get latest available (from win_repo) version of package
pkg_info = _get_package_info(name)
log.trace('Raw win_repo pkg_info for {0} is {1}'.format(name, pkg_info))
latest_available = _get_latest_pkg_version(pkg_info)
if latest_available:
log.debug('Latest available version of package {0} is {1}'.format(name, latest_available))
# check, whether latest available version is newer than latest installed version
if salt.utils.compare_versions(ver1=str(latest_available),
oper='>',
ver2=str(latest_installed)):
log.debug('Upgrade of {0} from {1} to {2} is available'.format(name, latest_installed, latest_available))
ret[name] = latest_available
else:
log.debug('No newer version than {0} of {1} is available'.format(latest_installed, name))
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def upgrade_available(name):
return latest_version(name) != ''
def list_upgrades(refresh=True):
if salt.utils.is_true(refresh):
refresh_db()
ret = {}
for name, data in get_repo_data().get('repo', {}).items():
if version(name):
latest = latest_version(name)
if latest:
ret[name] = latest
return ret
def list_available(*names):
if not names:
return ''
if len(names) == 1:
pkginfo = _get_package_info(names[0])
if not pkginfo:
return ''
versions = pkginfo.keys()
else:
versions = {}
for name in names:
pkginfo = _get_package_info(name)
if not pkginfo:
continue
versions[name] = pkginfo.keys() if pkginfo else []
versions = sorted(versions, cmp=_reverse_cmp_pkg_versions)
return versions
def version(*names, **kwargs):
win_names = []
ret = {}
if len(names) == 1:
val = __salt__['pkg_resource.version'](*names, **kwargs)
if len(val):
return val
return ''
if len(names) > 1:
reverse_dict = {}
nums = __salt__['pkg_resource.version'](*names, **kwargs)
if len(nums):
for num, val in nums.iteritems():
if len(val) > 0:
try:
ret[reverse_dict[num]] = val
except KeyError:
ret[num] = val
return ret
return dict([(x, '') for x in names])
return ret
def list_pkgs(versions_as_list=False, **kwargs):
versions_as_list = salt.utils.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
if 'pkg.list_pkgs' in __context__:
if versions_as_list:
return __context__['pkg.list_pkgs']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs'])
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {}
name_map = _get_name_map()
with salt.utils.winapi.Com():
for key, val in _get_reg_software().iteritems():
if key in name_map:
key = name_map[key]
__salt__['pkg_resource.add_pkg'](ret, key, val)
for key, val in _get_msi_software().iteritems():
if key in name_map:
key = name_map[key]
__salt__['pkg_resource.add_pkg'](ret, key, val)
__salt__['pkg_resource.sort_pkglist'](ret)
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _search_software(target):
search_results = {}
software = dict(
list(_get_reg_software().items()) +
list(_get_msi_software().items()))
for key, value in software.items():
if key is not None:
if target.lower() in key.lower():
search_results[key] = value
return search_results
def _get_msi_software():
win32_products = {}
# Don't use WMI to select from `Win32_product`, that has nasty
# `ProductsEx`. Jumping through powershell because `ProductsEx` is
# a get property that takes 3 arguments, and `win32com` can't call
ps = '''
$msi = New-Object -ComObject WindowsInstaller.Installer;
$msi.GetType().InvokeMember('ProductsEx', 'GetProperty', $null, $msi, ('', 's-1-1-0', 7))
| select @{
name='name';
expression={$_.GetType().InvokeMember('InstallProperty', 'GetProperty', $null, $_, ('ProductName'))}
},
@{
name='version';
expression={$_.GetType().InvokeMember('InstallProperty', 'GetProperty', $null, $_, ('VersionString'))}
}
| Write-host
'''.replace('\n', ' ')
ret = __salt__['cmd.run_all'](ps, shell='powershell', python_shell=True)
pattern = r'@{name=(.+); version=(.+)}'
for m in re.finditer(pattern, ret['stdout']):
(prd_name, prd_ver) = m.groups()
win32_products[prd_name] = prd_ver
return win32_products
def _get_reg_software():
reg_software = {}
#software and no version information exists on any of these items
ignore_list = ['AddressBook',
'Connection Manager',
'DirectDrawEx',
'Fontcore',
'IE40',
'IE4Data',
'IE5BAKEX',
'IEData',
'MobileOptionPack',
'SchedulingAgent',
'WIC'
]
encoding = locale.getpreferredencoding()
#attempt to corral the wild west of the multiple ways to install
#software in windows
reg_entries = dict(list(_get_user_keys().items()) +
list(_get_machine_keys().items()))
for reg_hive, reg_keys in reg_entries.items():
for reg_key in reg_keys:
try:
reg_handle = win32api.RegOpenKeyEx(
reg_hive,
reg_key,
0,
win32con.KEY_READ)
except Exception:
pass
#Unsinstall key may not exist for all users
for name, num, blank, time in win32api.RegEnumKeyEx(reg_handle):
prd_uninst_key = "\\".join([reg_key, name])
#These reg values aren't guaranteed to exist
windows_installer = _get_reg_value(
reg_hive,
prd_uninst_key,
'WindowsInstaller')
if windows_installer != 'Not Found' and windows_installer:
continue
prd_name = _get_reg_value(
reg_hive,
prd_uninst_key,
"DisplayName")
try:
prd_name = prd_name.decode(encoding)
except Exception:
pass
prd_ver = _get_reg_value(
reg_hive,
prd_uninst_key,
"DisplayVersion")
if name not in ignore_list:
if prd_name != 'Not Found':
# their information is useless
if prd_name != '':
reg_software[prd_name] = prd_ver
return reg_software
def _get_machine_keys():
machine_hive_and_keys = {}
machine_keys = [
"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
"Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
]
machine_hive = win32con.HKEY_LOCAL_MACHINE
machine_hive_and_keys[machine_hive] = machine_keys
return machine_hive_and_keys
def _get_user_keys():
user_hive_and_keys = {}
user_keys = []
users_hive = win32con.HKEY_USERS
#skip some built in and default users since software information in these
#keys is limited
skip_users = ['.DEFAULT',
'S-1-5-18',
'S-1-5-19',
'S-1-5-20']
sw_uninst_key = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
reg_handle = win32api.RegOpenKeyEx(
users_hive,
'',
0,
win32con.KEY_READ)
for name, num, blank, time in win32api.RegEnumKeyEx(reg_handle):
#this is some identical key of a sid that contains some software names
#but no detailed information about the software installed for that user
if '_Classes' in name:
break
if name not in skip_users:
usr_sw_uninst_key = "\\".join([name, sw_uninst_key])
user_keys.append(usr_sw_uninst_key)
user_hive_and_keys[users_hive] = user_keys
return user_hive_and_keys
def _get_reg_value(reg_hive, reg_key, value_name=''):
try:
key_handle = win32api.RegOpenKeyEx(
reg_hive, reg_key, 0, win32con.KEY_ALL_ACCESS)
value_data, value_type = win32api.RegQueryValueEx(key_handle,
value_name)
win32api.RegCloseKey(key_handle)
except Exception:
value_data = 'Not Found'
return value_data
def refresh_db(saltenv='base'):
__context__.pop('winrepo.data', None)
repocache = __opts__['win_repo_cachefile']
cached_repo = __salt__['cp.is_cached'](repocache, saltenv)
if not cached_repo:
# It's not cached. Cache it, mate.
cached_repo = __salt__['cp.cache_file'](repocache, saltenv)
return True
if __salt__['cp.hash_file'](repocache) != __salt__['cp.hash_file'](cached_repo, saltenv):
cached_repo = __salt__['cp.cache_file'](repocache, saltenv)
return True
def install(name=None, refresh=False, pkgs=None, saltenv='base', **kwargs):
if salt.utils.is_true(refresh):
refresh_db()
# Ignore pkg_type from parse_targets, Windows does not support the "sources"
# argument
pkg_params = __salt__['pkg_resource.parse_targets'](name,
pkgs,
**kwargs)[0]
if pkg_params is None or len(pkg_params) == 0:
return {}
old = list_pkgs()
if pkgs is None and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
pkg_params = {name:
{
'version': kwargs.get('version'),
'extra_install_flags': kwargs.get('extra_install_flags')}}
for pkg_name, options in pkg_params.iteritems():
pkginfo = _get_package_info(pkg_name)
if not pkginfo:
log.error('Unable to locate package {0}'.format(pkg_name))
continue
version_num = options and options.get('version') or _get_latest_pkg_version(pkginfo)
if version_num in [old.get(pkginfo[x]['full_name']) for x in pkginfo]:
# Desired version number already installed
continue
elif version_num not in pkginfo:
log.error('Version {0} not found for package '
'{1}'.format(version_num, pkg_name))
continue
installer = pkginfo[version_num].get('installer')
if not installer:
log.error('No installer configured for version {0} of package '
'{1}'.format(version_num, pkg_name))
if installer.startswith('salt:') \
or installer.startswith('http:') \
or installer.startswith('https:') \
or installer.startswith('ftp:'):
cached_pkg = __salt__['cp.is_cached'](installer, saltenv)
if not cached_pkg:
# It's not cached. Cache it, mate.
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
if __salt__['cp.hash_file'](installer, saltenv) != \
__salt__['cp.hash_file'](cached_pkg):
cached_pkg = __salt__['cp.cache_file'](installer, saltenv)
else:
cached_pkg = installer
cached_pkg = cached_pkg.replace('/', '\\')
msiexec = pkginfo[version_num].get('msiexec')
install_flags = '{0} {1}'.format(pkginfo[version_num]['install_flags'], options and options.get('extra_install_flags') or "")
cmd = []
if msiexec:
cmd.extend(['msiexec', '/i'])
cmd.append(cached_pkg)
cmd.extend(install_flags.split())
__salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.compare_dicts(old, new)
def upgrade(refresh=True):
log.warning('pkg.upgrade not implemented on Windows yet')
return {}
def remove(name=None, pkgs=None, version=None, extra_uninstall_flags=None, **kwargs):
pkg_params = __salt__['pkg_resource.parse_targets'](name,
pkgs,
**kwargs)[0]
old = list_pkgs()
for target in pkg_params:
pkginfo = _get_package_info(target)
if not pkginfo:
log.error('Unable to locate package {0}'.format(name))
continue
if not version:
version = _get_latest_pkg_version(pkginfo)
uninstaller = pkginfo[version].get('uninstaller')
if not uninstaller:
uninstaller = pkginfo[version].get('installer')
if not uninstaller:
return 'Error: No installer or uninstaller configured for package {0}'.format(name)
if uninstaller.startswith('salt:'):
cached_pkg = \
__salt__['cp.is_cached'](uninstaller)
if not cached_pkg:
cached_pkg = \
__salt__['cp.cache_file'](uninstaller)
else:
cached_pkg = uninstaller
cached_pkg = cached_pkg.replace('/', '\\')
if not os.path.exists(os.path.expandvars(cached_pkg)) \
and '(x86)' in cached_pkg:
cached_pkg = cached_pkg.replace('(x86)', '')
expanded_cached_pkg = str(os.path.expandvars(cached_pkg))
uninstall_flags = str(pkginfo[version].get('uninstall_flags', ''))
cmd = []
if pkginfo[version].get('msiexec'):
cmd.extend(['msiexec', '/x'])
cmd.append(expanded_cached_pkg)
cmd.extend(uninstall_flags.split())
if extra_uninstall_flags:
cmd.extend(str(extra_uninstall_flags).split())
__salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.compare_dicts(old, new)
def purge(name=None, pkgs=None, version=None, **kwargs):
return remove(name=name, pkgs=pkgs, version=version, **kwargs)
def get_repo_data(saltenv='base'):
#if 'winrepo.data' in __context__:
# return __context__['winrepo.data']
repocache = __opts__['win_repo_cachefile']
cached_repo = __salt__['cp.is_cached'](repocache, saltenv)
if not cached_repo:
__salt__['pkg.refresh_db']()
try:
with salt.utils.fopen(cached_repo, 'rb') as repofile:
try:
repodata = msgpack.loads(repofile.read()) or {}
#__context__['winrepo.data'] = repodata
return repodata
except Exception as exc:
log.exception(exc)
return {}
except IOError as exc:
log.error('Not able to read repo file')
log.exception(exc)
return {}
def _get_name_map():
return get_repo_data().get('name_map', {})
def _get_package_info(name):
return get_repo_data().get('repo', {}).get(name, {})
def _reverse_cmp_pkg_versions(pkg1, pkg2):
if LooseVersion(pkg1) > LooseVersion(pkg2):
return 1
else:
return -1
def _get_latest_pkg_version(pkginfo):
if len(pkginfo) == 1:
return pkginfo.iterkeys().next()
return sorted(pkginfo, cmp=_reverse_cmp_pkg_versions).pop()
| true | true |
f7f8c8167f224dafef796ec6031f269b479e58dc | 4,675 | py | Python | allennlp/training/metrics/attachment_scores.py | urigoren/allennlp | 236e1fd01ca30409cd736625901292609009f5c4 | [
"Apache-2.0"
] | 4 | 2019-05-30T01:03:31.000Z | 2021-12-18T08:24:51.000Z | allennlp/training/metrics/attachment_scores.py | urigoren/allennlp | 236e1fd01ca30409cd736625901292609009f5c4 | [
"Apache-2.0"
] | 123 | 2020-04-26T02:41:30.000Z | 2021-08-02T21:18:00.000Z | allennlp/training/metrics/attachment_scores.py | urigoren/allennlp | 236e1fd01ca30409cd736625901292609009f5c4 | [
"Apache-2.0"
] | 5 | 2019-07-16T06:43:50.000Z | 2021-12-18T08:25:12.000Z | from typing import Optional, List
from overrides import overrides
import torch
from allennlp.training.metrics.metric import Metric
@Metric.register("attachment_scores")
class AttachmentScores(Metric):
"""
Computes labeled and unlabeled attachment scores for a
dependency parse, as well as sentence level exact match
for both labeled and unlabeled trees. Note that the input
to this metric is the sampled predictions, not the distribution
itself.
# Parameters
ignore_classes : `List[int]`, optional (default = None)
A list of label ids to ignore when computing metrics.
"""
def __init__(self, ignore_classes: List[int] = None) -> None:
self._labeled_correct = 0.0
self._unlabeled_correct = 0.0
self._exact_labeled_correct = 0.0
self._exact_unlabeled_correct = 0.0
self._total_words = 0.0
self._total_sentences = 0.0
self._ignore_classes: List[int] = ignore_classes or []
def __call__( # type: ignore
self,
predicted_indices: torch.Tensor,
predicted_labels: torch.Tensor,
gold_indices: torch.Tensor,
gold_labels: torch.Tensor,
mask: Optional[torch.BoolTensor] = None,
):
"""
# Parameters
predicted_indices : `torch.Tensor`, required.
A tensor of head index predictions of shape (batch_size, timesteps).
predicted_labels : `torch.Tensor`, required.
A tensor of arc label predictions of shape (batch_size, timesteps).
gold_indices : `torch.Tensor`, required.
A tensor of the same shape as `predicted_indices`.
gold_labels : `torch.Tensor`, required.
A tensor of the same shape as `predicted_labels`.
mask : `torch.BoolTensor`, optional (default = None).
A tensor of the same shape as `predicted_indices`.
"""
detached = self.detach_tensors(
predicted_indices, predicted_labels, gold_indices, gold_labels, mask
)
predicted_indices, predicted_labels, gold_indices, gold_labels, mask = detached
if mask is None:
mask = torch.ones_like(predicted_indices).bool()
predicted_indices = predicted_indices.long()
predicted_labels = predicted_labels.long()
gold_indices = gold_indices.long()
gold_labels = gold_labels.long()
# Multiply by a mask denoting locations of
# gold labels which we should ignore.
for label in self._ignore_classes:
label_mask = gold_labels.eq(label)
mask = mask & ~label_mask
correct_indices = predicted_indices.eq(gold_indices).long() * mask
unlabeled_exact_match = (correct_indices + ~mask).prod(dim=-1)
correct_labels = predicted_labels.eq(gold_labels).long() * mask
correct_labels_and_indices = correct_indices * correct_labels
labeled_exact_match = (correct_labels_and_indices + ~mask).prod(dim=-1)
self._unlabeled_correct += correct_indices.sum()
self._exact_unlabeled_correct += unlabeled_exact_match.sum()
self._labeled_correct += correct_labels_and_indices.sum()
self._exact_labeled_correct += labeled_exact_match.sum()
self._total_sentences += correct_indices.size(0)
self._total_words += correct_indices.numel() - (~mask).sum()
def get_metric(self, reset: bool = False):
"""
# Returns
The accumulated metrics as a dictionary.
"""
unlabeled_attachment_score = 0.0
labeled_attachment_score = 0.0
unlabeled_exact_match = 0.0
labeled_exact_match = 0.0
if self._total_words > 0.0:
unlabeled_attachment_score = float(self._unlabeled_correct) / float(self._total_words)
labeled_attachment_score = float(self._labeled_correct) / float(self._total_words)
if self._total_sentences > 0:
unlabeled_exact_match = float(self._exact_unlabeled_correct) / float(
self._total_sentences
)
labeled_exact_match = float(self._exact_labeled_correct) / float(self._total_sentences)
if reset:
self.reset()
return {
"UAS": unlabeled_attachment_score,
"LAS": labeled_attachment_score,
"UEM": unlabeled_exact_match,
"LEM": labeled_exact_match,
}
@overrides
def reset(self):
self._labeled_correct = 0.0
self._unlabeled_correct = 0.0
self._exact_labeled_correct = 0.0
self._exact_unlabeled_correct = 0.0
self._total_words = 0.0
self._total_sentences = 0.0
| 38.00813 | 99 | 0.655401 | from typing import Optional, List
from overrides import overrides
import torch
from allennlp.training.metrics.metric import Metric
@Metric.register("attachment_scores")
class AttachmentScores(Metric):
def __init__(self, ignore_classes: List[int] = None) -> None:
self._labeled_correct = 0.0
self._unlabeled_correct = 0.0
self._exact_labeled_correct = 0.0
self._exact_unlabeled_correct = 0.0
self._total_words = 0.0
self._total_sentences = 0.0
self._ignore_classes: List[int] = ignore_classes or []
def __call__(
self,
predicted_indices: torch.Tensor,
predicted_labels: torch.Tensor,
gold_indices: torch.Tensor,
gold_labels: torch.Tensor,
mask: Optional[torch.BoolTensor] = None,
):
detached = self.detach_tensors(
predicted_indices, predicted_labels, gold_indices, gold_labels, mask
)
predicted_indices, predicted_labels, gold_indices, gold_labels, mask = detached
if mask is None:
mask = torch.ones_like(predicted_indices).bool()
predicted_indices = predicted_indices.long()
predicted_labels = predicted_labels.long()
gold_indices = gold_indices.long()
gold_labels = gold_labels.long()
for label in self._ignore_classes:
label_mask = gold_labels.eq(label)
mask = mask & ~label_mask
correct_indices = predicted_indices.eq(gold_indices).long() * mask
unlabeled_exact_match = (correct_indices + ~mask).prod(dim=-1)
correct_labels = predicted_labels.eq(gold_labels).long() * mask
correct_labels_and_indices = correct_indices * correct_labels
labeled_exact_match = (correct_labels_and_indices + ~mask).prod(dim=-1)
self._unlabeled_correct += correct_indices.sum()
self._exact_unlabeled_correct += unlabeled_exact_match.sum()
self._labeled_correct += correct_labels_and_indices.sum()
self._exact_labeled_correct += labeled_exact_match.sum()
self._total_sentences += correct_indices.size(0)
self._total_words += correct_indices.numel() - (~mask).sum()
def get_metric(self, reset: bool = False):
unlabeled_attachment_score = 0.0
labeled_attachment_score = 0.0
unlabeled_exact_match = 0.0
labeled_exact_match = 0.0
if self._total_words > 0.0:
unlabeled_attachment_score = float(self._unlabeled_correct) / float(self._total_words)
labeled_attachment_score = float(self._labeled_correct) / float(self._total_words)
if self._total_sentences > 0:
unlabeled_exact_match = float(self._exact_unlabeled_correct) / float(
self._total_sentences
)
labeled_exact_match = float(self._exact_labeled_correct) / float(self._total_sentences)
if reset:
self.reset()
return {
"UAS": unlabeled_attachment_score,
"LAS": labeled_attachment_score,
"UEM": unlabeled_exact_match,
"LEM": labeled_exact_match,
}
@overrides
def reset(self):
self._labeled_correct = 0.0
self._unlabeled_correct = 0.0
self._exact_labeled_correct = 0.0
self._exact_unlabeled_correct = 0.0
self._total_words = 0.0
self._total_sentences = 0.0
| true | true |
f7f8c8bc7b4658d5b5e6903f6a97cb114888b621 | 1,027 | py | Python | aerics/client.py | Aermoss/Aerics | 21d25a02b339e79c46a6e28163b4b00ea027d348 | [
"MIT"
] | 1 | 2022-01-25T17:36:54.000Z | 2022-01-25T17:36:54.000Z | aerics/client.py | Aermoss/Aerics | 21d25a02b339e79c46a6e28163b4b00ea027d348 | [
"MIT"
] | null | null | null | aerics/client.py | Aermoss/Aerics | 21d25a02b339e79c46a6e28163b4b00ea027d348 | [
"MIT"
] | null | null | null | import socket
import pickle
class Client:
def __init__(self, ip, port, recv_size = 1024, pickle = True):
self.ip = ip
self.port = port
self.recv_size = recv_size
self.pickle = pickle
self.destroyed = False
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect(self):
if not self.destroyed:
self.client.connect((self.ip, self.port))
def destroy(self):
if not self.destroyed:
self.destroyed = True
self.client.shutdown(socket.SHUT_RDWR)
self.client.close()
def send(self, data):
if not self.destroyed:
if self.pickle:
data = pickle.dumps(data)
self.client.send(data)
def recv(self):
if not self.destroyed:
data = self.client.recv(self.recv_size)
if self.pickle:
data = pickle.loads(data)
return data | 26.333333 | 72 | 0.53554 | import socket
import pickle
class Client:
def __init__(self, ip, port, recv_size = 1024, pickle = True):
self.ip = ip
self.port = port
self.recv_size = recv_size
self.pickle = pickle
self.destroyed = False
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect(self):
if not self.destroyed:
self.client.connect((self.ip, self.port))
def destroy(self):
if not self.destroyed:
self.destroyed = True
self.client.shutdown(socket.SHUT_RDWR)
self.client.close()
def send(self, data):
if not self.destroyed:
if self.pickle:
data = pickle.dumps(data)
self.client.send(data)
def recv(self):
if not self.destroyed:
data = self.client.recv(self.recv_size)
if self.pickle:
data = pickle.loads(data)
return data | true | true |
f7f8c9c426f612adeb828f335ad7255e04da9393 | 10,523 | py | Python | adaptnlp/training.py | emycooper/adaptnlp | 2e39f81a7faa4c7cd1d2a3764790cf7bb7ad7469 | [
"Apache-2.0"
] | 5 | 2020-03-30T12:50:56.000Z | 2022-01-20T22:45:29.000Z | adaptnlp/training.py | emycooper/adaptnlp | 2e39f81a7faa4c7cd1d2a3764790cf7bb7ad7469 | [
"Apache-2.0"
] | 9 | 2020-11-13T18:41:44.000Z | 2022-02-10T01:58:28.000Z | adaptnlp/training.py | emycooper/adaptnlp | 2e39f81a7faa4c7cd1d2a3764790cf7bb7ad7469 | [
"Apache-2.0"
] | 1 | 2020-03-30T17:29:05.000Z | 2020-03-30T17:29:05.000Z | from typing import Union, Dict
from pathlib import Path
import json
import csv
import numpy as np
from adaptnlp import EasyDocumentEmbeddings
from flair.datasets import CSVClassificationCorpus
from flair.data import Corpus
from flair.embeddings import DocumentRNNEmbeddings
from flair.models import TextClassifier
from flair.trainers import ModelTrainer
from flair.visual.training_curves import Plotter
class SequenceClassifierTrainer:
"""Sequence Classifier Trainer
Usage:
```python
>>> sc_trainer = SequenceClassifierTrainer(corpus="/Path/to/data/dir")
```
**Parameters:**
* **corpus** - A flair corpus data model or `Path`/string to a directory with train.csv/test.csv/dev.csv
* **encoder** - A `EasyDocumentEmbeddings` object if training with a flair prediction head or `Path`/string if training with Transformer's prediction models
* **column_name_map** - Required if corpus is not a `Corpus` object, it's a dictionary specifying the indices of the text and label columns of the csv i.e. {1:"text",2:"label"}
* **corpus_in_memory** - Boolean for whether to store corpus embeddings in memory
* **predictive_head** - For now either "flair" or "transformers" for the prediction head
* ****kwargs** - Keyword arguments for Flair's `TextClassifier` model class
"""
def __init__(
self,
corpus: Union[Corpus, Path, str],
encoder: Union[EasyDocumentEmbeddings, Path, str],
column_name_map: None,
corpus_in_memory: bool = True,
predictive_head: str = "flair",
**kwargs,
):
if isinstance(corpus, Corpus):
self.corpus = corpus
else:
if isinstance(corpus, str):
corpus = Path(corpus)
if not column_name_map:
raise ValueError(
"If not instantiating with `Corpus` object, must pass in `column_name_map` argument to specify text/label indices"
)
self.corpus = CSVClassificationCorpus(
corpus,
column_name_map,
skip_header=True,
delimiter=",",
in_memory=corpus_in_memory,
)
# Verify predictive head is within available heads
self.available_predictive_head = ["flair", "transformers"]
if predictive_head not in self.available_predictive_head:
raise ValueError(
f"predictive_head param must be one of the following: {self.available_predictive_head}"
)
self.predictive_head = predictive_head
# Verify correct corresponding encoder is used with predictive head (This can be structured with better design in the future)
if isinstance(encoder, EasyDocumentEmbeddings):
if predictive_head == "transformers":
raise ValueError(
"If using `transformers` predictive head, pass in the path to the transformer's model"
)
else:
self.encoder = encoder
else:
if isinstance(encoder, str):
encoder = Path(encoder)
self.encoder = encoder
# Create the label dictionary on init (store to keep from constantly generating label_dict) should we use dev/test set instead assuming all labels are provided?
self.label_dict = self.corpus.make_label_dictionary()
# Save trainer kwargs dict for reinitializations
self.trainer_kwargs = kwargs
# Load trainer with initial setup
self._initial_setup(self.label_dict, **kwargs)
def _initial_setup(self, label_dict: Dict, **kwargs):
if self.predictive_head == "flair":
# Get Document embeddings from `embeddings`
document_embeddings: DocumentRNNEmbeddings = self.encoder.rnn_embeddings
# Create the text classifier
classifier = TextClassifier(
document_embeddings, label_dictionary=label_dict, **kwargs,
)
# Initialize the text classifier trainer
self.trainer = ModelTrainer(classifier, self.corpus)
# TODO: In internal transformers package, create ****ForSequenceClassification adaptations
elif self.predictive_head == "transformers":
with open(self.encoder / "config.json") as config_f:
configs = json.load(config_f)
model_name = configs["architectures"][-1]
if model_name == "BertForMaskedLM":
pass
def train(
self,
output_dir: Union[Path, str],
learning_rate: float = 0.07,
mini_batch_size: int = 32,
anneal_factor: float = 0.5,
patience: int = 5,
max_epochs: int = 150,
plot_weights: bool = False,
**kwargs,
) -> None:
"""
Train the Sequence Classifier
* **output_dir** - The output directory where the model predictions and checkpoints will be written.
* **learning_rate** - The initial learning rate
* **mini_batch_size** - Batch size for the dataloader
* **anneal_factor** - The factor by which the learning rate is annealed
* **patience** - Patience is the number of epochs with no improvement the Trainer waits until annealing the learning rate
* **max_epochs** - Maximum number of epochs to train. Terminates training if this number is surpassed.
* **plot_weights** - Bool to plot weights or not
* **kwargs** - Keyword arguments for the rest of Flair's `Trainer.train()` hyperparameters
"""
if isinstance(output_dir, str):
output_dir = Path(output_dir)
# Start the training
self.trainer.train(
output_dir,
learning_rate=learning_rate,
mini_batch_size=mini_batch_size,
anneal_factor=anneal_factor,
patience=patience,
max_epochs=max_epochs,
**kwargs,
)
# Plot weight traces
if plot_weights:
plotter = Plotter()
plotter.plot_weights(output_dir / "weights.txt")
def find_learning_rate(
self,
output_dir: Union[Path, str],
file_name: str = "learning_rate.tsv",
start_learning_rate: float = 1e-8,
end_learning_rate: float = 10,
iterations: int = 100,
mini_batch_size: int = 32,
stop_early: bool = True,
smoothing_factor: float = 0.7,
plot_learning_rate: bool = True,
**kwargs,
) -> float:
"""
Uses Leslie's cyclical learning rate finding method to generate and save the loss x learning rate plot
This method returns a suggested learning rate using the static method `LMFineTuner.suggest_learning_rate()`
which is implicitly run in this method.
* **output_dir** - Path to dir for learning rate file to be saved
* **file_name** - Name of learning rate .tsv file
* **start_learning_rate** - Initial learning rate to start cyclical learning rate finder method
* **end_learning_rate** - End learning rate to stop exponential increase of the learning rate
* **iterations** - Number of optimizer iterations for the ExpAnnealLR scheduler
* **mini_batch_size** - Batch size for dataloader
* **stop_early** - Bool for stopping early once loss diverges
* **smoothing_factor** - Smoothing factor on moving average of losses
* **adam_epsilon** - Epsilon for Adam optimizer.
* **weight_decay** - Weight decay if we apply some.
* **kwargs** - Additional keyword arguments for the Adam optimizer
**return** - Learning rate as a float
"""
# 7. find learning rate
learning_rate_tsv = self.trainer.find_learning_rate(
base_path=output_dir,
file_name=file_name,
start_learning_rate=start_learning_rate,
end_learning_rate=end_learning_rate,
iterations=iterations,
mini_batch_size=mini_batch_size,
stop_early=stop_early,
smoothing_factor=smoothing_factor,
)
# Reinitialize optimizer and parameters by reinitializing trainer
self._initial_setup(self.label_dict, **self.trainer_kwargs)
if plot_learning_rate:
plotter = Plotter()
plotter.plot_learning_rate(learning_rate_tsv)
# Use the automated learning rate finder
with open(learning_rate_tsv) as lr_f:
lr_tsv = list(csv.reader(lr_f, delimiter="\t"))
losses = np.array([float(row[-1]) for row in lr_tsv[1:]])
lrs = np.array([float(row[-2]) for row in lr_tsv[1:]])
lr_to_use = self.suggested_learning_rate(losses, lrs, **kwargs)
print(f"Recommended Learning Rate {lr_to_use}")
return lr_to_use
@staticmethod
def suggested_learning_rate(
losses: np.array,
lrs: np.array,
lr_diff: int = 15,
loss_threshold: float = 0.2,
adjust_value: float = 1,
) -> float:
# This seems redundant unless we can make this configured for each trainer/finetuner
"""
Attempts to find the optimal learning rate using a interval slide rule approach with the cyclical learning rate method
* **losses** - Numpy array of losses
* **lrs** - Numpy array of exponentially increasing learning rates (must match dim of `losses`)
* **lr_diff** - Learning rate Interval of slide ruler
* **loss_threshold** - Threshold of loss difference on interval where the sliding stops
* **adjust_value** - Coefficient for adjustment
**return** - the optimal learning rate as a float
"""
# Get loss values and their corresponding gradients, and get lr values
assert lr_diff < len(losses)
loss_grad = np.gradient(losses)
# Search for index in gradients where loss is lowest before the loss spike
# Initialize right and left idx using the lr_diff as a spacing unit
# Set the local min lr as -1 to signify if threshold is too low
r_idx = -1
l_idx = r_idx - lr_diff
local_min_lr = lrs[l_idx]
while (l_idx >= -len(losses)) and (
abs(loss_grad[r_idx] - loss_grad[l_idx]) > loss_threshold
):
local_min_lr = lrs[l_idx]
r_idx -= 1
l_idx -= 1
lr_to_use = local_min_lr * adjust_value
return lr_to_use
| 41.105469 | 180 | 0.634895 | from typing import Union, Dict
from pathlib import Path
import json
import csv
import numpy as np
from adaptnlp import EasyDocumentEmbeddings
from flair.datasets import CSVClassificationCorpus
from flair.data import Corpus
from flair.embeddings import DocumentRNNEmbeddings
from flair.models import TextClassifier
from flair.trainers import ModelTrainer
from flair.visual.training_curves import Plotter
class SequenceClassifierTrainer:
def __init__(
self,
corpus: Union[Corpus, Path, str],
encoder: Union[EasyDocumentEmbeddings, Path, str],
column_name_map: None,
corpus_in_memory: bool = True,
predictive_head: str = "flair",
**kwargs,
):
if isinstance(corpus, Corpus):
self.corpus = corpus
else:
if isinstance(corpus, str):
corpus = Path(corpus)
if not column_name_map:
raise ValueError(
"If not instantiating with `Corpus` object, must pass in `column_name_map` argument to specify text/label indices"
)
self.corpus = CSVClassificationCorpus(
corpus,
column_name_map,
skip_header=True,
delimiter=",",
in_memory=corpus_in_memory,
)
self.available_predictive_head = ["flair", "transformers"]
if predictive_head not in self.available_predictive_head:
raise ValueError(
f"predictive_head param must be one of the following: {self.available_predictive_head}"
)
self.predictive_head = predictive_head
if isinstance(encoder, EasyDocumentEmbeddings):
if predictive_head == "transformers":
raise ValueError(
"If using `transformers` predictive head, pass in the path to the transformer's model"
)
else:
self.encoder = encoder
else:
if isinstance(encoder, str):
encoder = Path(encoder)
self.encoder = encoder
# Create the label dictionary on init (store to keep from constantly generating label_dict) should we use dev/test set instead assuming all labels are provided?
self.label_dict = self.corpus.make_label_dictionary()
# Save trainer kwargs dict for reinitializations
self.trainer_kwargs = kwargs
# Load trainer with initial setup
self._initial_setup(self.label_dict, **kwargs)
def _initial_setup(self, label_dict: Dict, **kwargs):
if self.predictive_head == "flair":
# Get Document embeddings from `embeddings`
document_embeddings: DocumentRNNEmbeddings = self.encoder.rnn_embeddings
# Create the text classifier
classifier = TextClassifier(
document_embeddings, label_dictionary=label_dict, **kwargs,
)
# Initialize the text classifier trainer
self.trainer = ModelTrainer(classifier, self.corpus)
# TODO: In internal transformers package, create ****ForSequenceClassification adaptations
elif self.predictive_head == "transformers":
with open(self.encoder / "config.json") as config_f:
configs = json.load(config_f)
model_name = configs["architectures"][-1]
if model_name == "BertForMaskedLM":
pass
def train(
self,
output_dir: Union[Path, str],
learning_rate: float = 0.07,
mini_batch_size: int = 32,
anneal_factor: float = 0.5,
patience: int = 5,
max_epochs: int = 150,
plot_weights: bool = False,
**kwargs,
) -> None:
if isinstance(output_dir, str):
output_dir = Path(output_dir)
# Start the training
self.trainer.train(
output_dir,
learning_rate=learning_rate,
mini_batch_size=mini_batch_size,
anneal_factor=anneal_factor,
patience=patience,
max_epochs=max_epochs,
**kwargs,
)
# Plot weight traces
if plot_weights:
plotter = Plotter()
plotter.plot_weights(output_dir / "weights.txt")
def find_learning_rate(
self,
output_dir: Union[Path, str],
file_name: str = "learning_rate.tsv",
start_learning_rate: float = 1e-8,
end_learning_rate: float = 10,
iterations: int = 100,
mini_batch_size: int = 32,
stop_early: bool = True,
smoothing_factor: float = 0.7,
plot_learning_rate: bool = True,
**kwargs,
) -> float:
# 7. find learning rate
learning_rate_tsv = self.trainer.find_learning_rate(
base_path=output_dir,
file_name=file_name,
start_learning_rate=start_learning_rate,
end_learning_rate=end_learning_rate,
iterations=iterations,
mini_batch_size=mini_batch_size,
stop_early=stop_early,
smoothing_factor=smoothing_factor,
)
# Reinitialize optimizer and parameters by reinitializing trainer
self._initial_setup(self.label_dict, **self.trainer_kwargs)
if plot_learning_rate:
plotter = Plotter()
plotter.plot_learning_rate(learning_rate_tsv)
# Use the automated learning rate finder
with open(learning_rate_tsv) as lr_f:
lr_tsv = list(csv.reader(lr_f, delimiter="\t"))
losses = np.array([float(row[-1]) for row in lr_tsv[1:]])
lrs = np.array([float(row[-2]) for row in lr_tsv[1:]])
lr_to_use = self.suggested_learning_rate(losses, lrs, **kwargs)
print(f"Recommended Learning Rate {lr_to_use}")
return lr_to_use
@staticmethod
def suggested_learning_rate(
losses: np.array,
lrs: np.array,
lr_diff: int = 15,
loss_threshold: float = 0.2,
adjust_value: float = 1,
) -> float:
# This seems redundant unless we can make this configured for each trainer/finetuner
# Get loss values and their corresponding gradients, and get lr values
assert lr_diff < len(losses)
loss_grad = np.gradient(losses)
# Search for index in gradients where loss is lowest before the loss spike
# Initialize right and left idx using the lr_diff as a spacing unit
# Set the local min lr as -1 to signify if threshold is too low
r_idx = -1
l_idx = r_idx - lr_diff
local_min_lr = lrs[l_idx]
while (l_idx >= -len(losses)) and (
abs(loss_grad[r_idx] - loss_grad[l_idx]) > loss_threshold
):
local_min_lr = lrs[l_idx]
r_idx -= 1
l_idx -= 1
lr_to_use = local_min_lr * adjust_value
return lr_to_use
| true | true |
f7f8cac09a038db6e7f34f18098c7e1ac92de8c0 | 606 | py | Python | Leetcode/199. Binary Tree Right Side View/solution1.py | asanoviskhak/Outtalent | c500e8ad498f76d57eb87a9776a04af7bdda913d | [
"MIT"
] | 51 | 2020-07-12T21:27:47.000Z | 2022-02-11T19:25:36.000Z | Leetcode/199. Binary Tree Right Side View/solution1.py | CrazySquirrel/Outtalent | 8a10b23335d8e9f080e5c39715b38bcc2916ff00 | [
"MIT"
] | null | null | null | Leetcode/199. Binary Tree Right Side View/solution1.py | CrazySquirrel/Outtalent | 8a10b23335d8e9f080e5c39715b38bcc2916ff00 | [
"MIT"
] | 32 | 2020-07-27T13:54:24.000Z | 2021-12-25T18:12:50.000Z | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
if not root: return []
nodes = [root]
result = []
while nodes:
result.append(nodes[-1].val)
tmp = []
for node in nodes:
if node.left: tmp.append(node.left)
if node.right: tmp.append(node.right)
nodes = tmp
return result
| 30.3 | 57 | 0.526403 |
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
if not root: return []
nodes = [root]
result = []
while nodes:
result.append(nodes[-1].val)
tmp = []
for node in nodes:
if node.left: tmp.append(node.left)
if node.right: tmp.append(node.right)
nodes = tmp
return result
| true | true |
f7f8cad20a22af8e02e4775d31e89bfaceb2d952 | 4,604 | py | Python | src/patent_client/uspto/assignment/schema.py | dmathijs/patent_client | 0466d34ef7af8556a11a2cff865d0f89ef7bd542 | [
"Apache-2.0"
] | 15 | 2018-10-23T01:15:29.000Z | 2022-02-01T19:53:44.000Z | src/patent_client/uspto/assignment/schema.py | grimmer0125/patent_client | 8943ca970d174ecf8aad10669a95ceddd75f5e13 | [
"Apache-2.0"
] | 33 | 2018-10-26T03:48:51.000Z | 2022-01-17T09:16:07.000Z | src/patent_client/uspto/assignment/schema.py | grimmer0125/patent_client | 8943ca970d174ecf8aad10669a95ceddd75f5e13 | [
"Apache-2.0"
] | 7 | 2019-02-14T20:25:20.000Z | 2021-05-24T07:49:34.000Z | from marshmallow import Schema, fields, EXCLUDE, pre_load, post_load, ValidationError
from .model import Assignment, Property, Assignee, Assignor
from patent_client.util.schema import ListField
# Utility Functions
def separate_dicts_by_prefix(prefix, data):
keys = [k for k in data.keys() if k.startswith(prefix) and not k.endswith('size')]
if not any(isinstance(data[k], (tuple, list)) for k in keys):
filtered_data = [{k[len(prefix)+1:]: v for k, v in data.items() if k in keys},]
return filtered_data
filtered_data = {k: v for k, v in data.items() if k in keys and isinstance(v, (tuple, list))}
count = len(next(iter(filtered_data.values())))
list_of_dicts = [
{k[len(prefix)+1:]:v[i] for k, v in filtered_data.items()}
for i in range(count)
]
return list_of_dicts
def separate_dicts(keys, data):
if not any(isinstance(data[k], (tuple, list)) for k in keys):
filtered_data = [{k: v for k, v in data.items() if k in keys},]
return filtered_data
filtered_data = {k: v for k, v in data.items() if k in keys and isinstance(v, (tuple, list))}
count = len(next(iter(filtered_data.values())))
list_of_dicts = [
{k:v[i] for k, v in filtered_data.items()}
for i in range(count)
]
return list_of_dicts
def combine_strings(prefix, data):
filtered_data = {k:v for k, v in data.items() if k.startswith(prefix)}
return "\n".join(filtered_data[k] for k in sorted(filtered_data.keys()))
# Custom Fields
class YesNoField(fields.Field):
"""Converts to and from boolean values represented
as a yes or no
"""
def _deserialize(self, value, *args, **kwargs) -> bool:
if value not in ('Y', 'N'): raise ValidationError('YesNo must be a Y or N')
return value == 'Y'
# Schemas
class BaseSchema(Schema):
@post_load
def make_object(self, data, **kwargs):
return self.__model__(**data)
pass
class PropertySchema(BaseSchema):
__model__ = Property
invention_title = fields.Str(allow_none=True)
inventors = fields.Str(allow_none=True)
# Numbers
appl_id = fields.Str(allow_none=True, data_key='appl_num')
pct_num = fields.Str(allow_none=True)
intl_reg_num = fields.Str(allow_none=True)
publ_num = fields.Str(allow_none=True)
pat_num = fields.Str(allow_none=True)
# Dates
filing_date = fields.Date(allow_none=True)
intl_publ_date = fields.Date(allow_none=True)
issue_date = fields.Date(allow_none=True)
publ_date = fields.Date(allow_none=True)
class AssignorSchema(BaseSchema):
__model__ = Assignor
name = fields.Str()
ex_date = fields.Raw()
date_ack = fields.Raw()
class Meta:
unknown = EXCLUDE
class AssigneeSchema(BaseSchema):
__model__ = Assignee
name = fields.Str()
address = fields.Str()
city = fields.Str(allow_none=True)
state = fields.Str(allow_none=True)
country_name = fields.Str(allow_none=True)
postcode = fields.Str(allow_none=True)
@pre_load
def pre_load(self, input_data, **kwargs):
input_data['address'] = combine_strings('corr_address', input_data)
return input_data
class Meta:
unknown = EXCLUDE
class AssignmentSchema(BaseSchema):
__model__ = Assignment
assignment_record_has_images = YesNoField()
page_count = fields.Int()
transaction_date = fields.Raw(allow_none=True)
last_update_date = fields.Raw(required=True)
recorded_date = fields.Raw(required=True)
assignment_record_has_images = fields.Boolean(required=True)
properties = ListField(fields.Nested(PropertySchema))
assignors = ListField(fields.Nested(AssignorSchema))
assignees = ListField(fields.Nested(AssigneeSchema))
@pre_load
def pre_load(self, input_data, **kwargs):
input_data['assignors'] = separate_dicts_by_prefix('pat_assignor', input_data)
input_data['assignees'] = separate_dicts_by_prefix('pat_assignee', input_data)
property_fields = [f.data_key or f.name for f in PropertySchema().fields.values()]
input_data['properties'] = separate_dicts(property_fields, input_data)
input_data['corr_address'] = combine_strings('corr_address', input_data)
input_data['conveyance_text'] = input_data['conveyance_text'].replace('(SEE DOCUMENT FOR DETAILS).', '').strip()
return input_data
class Meta:
unknown = EXCLUDE
additional = ('id', 'conveyance_text', 'date_produced', 'assignment_record_has_images', 'corr_name', 'corr_address', 'assignor', 'assignee') | 37.430894 | 148 | 0.682884 | from marshmallow import Schema, fields, EXCLUDE, pre_load, post_load, ValidationError
from .model import Assignment, Property, Assignee, Assignor
from patent_client.util.schema import ListField
def separate_dicts_by_prefix(prefix, data):
keys = [k for k in data.keys() if k.startswith(prefix) and not k.endswith('size')]
if not any(isinstance(data[k], (tuple, list)) for k in keys):
filtered_data = [{k[len(prefix)+1:]: v for k, v in data.items() if k in keys},]
return filtered_data
filtered_data = {k: v for k, v in data.items() if k in keys and isinstance(v, (tuple, list))}
count = len(next(iter(filtered_data.values())))
list_of_dicts = [
{k[len(prefix)+1:]:v[i] for k, v in filtered_data.items()}
for i in range(count)
]
return list_of_dicts
def separate_dicts(keys, data):
if not any(isinstance(data[k], (tuple, list)) for k in keys):
filtered_data = [{k: v for k, v in data.items() if k in keys},]
return filtered_data
filtered_data = {k: v for k, v in data.items() if k in keys and isinstance(v, (tuple, list))}
count = len(next(iter(filtered_data.values())))
list_of_dicts = [
{k:v[i] for k, v in filtered_data.items()}
for i in range(count)
]
return list_of_dicts
def combine_strings(prefix, data):
filtered_data = {k:v for k, v in data.items() if k.startswith(prefix)}
return "\n".join(filtered_data[k] for k in sorted(filtered_data.keys()))
class YesNoField(fields.Field):
def _deserialize(self, value, *args, **kwargs) -> bool:
if value not in ('Y', 'N'): raise ValidationError('YesNo must be a Y or N')
return value == 'Y'
class BaseSchema(Schema):
@post_load
def make_object(self, data, **kwargs):
return self.__model__(**data)
pass
class PropertySchema(BaseSchema):
__model__ = Property
invention_title = fields.Str(allow_none=True)
inventors = fields.Str(allow_none=True)
appl_id = fields.Str(allow_none=True, data_key='appl_num')
pct_num = fields.Str(allow_none=True)
intl_reg_num = fields.Str(allow_none=True)
publ_num = fields.Str(allow_none=True)
pat_num = fields.Str(allow_none=True)
filing_date = fields.Date(allow_none=True)
intl_publ_date = fields.Date(allow_none=True)
issue_date = fields.Date(allow_none=True)
publ_date = fields.Date(allow_none=True)
class AssignorSchema(BaseSchema):
__model__ = Assignor
name = fields.Str()
ex_date = fields.Raw()
date_ack = fields.Raw()
class Meta:
unknown = EXCLUDE
class AssigneeSchema(BaseSchema):
__model__ = Assignee
name = fields.Str()
address = fields.Str()
city = fields.Str(allow_none=True)
state = fields.Str(allow_none=True)
country_name = fields.Str(allow_none=True)
postcode = fields.Str(allow_none=True)
@pre_load
def pre_load(self, input_data, **kwargs):
input_data['address'] = combine_strings('corr_address', input_data)
return input_data
class Meta:
unknown = EXCLUDE
class AssignmentSchema(BaseSchema):
__model__ = Assignment
assignment_record_has_images = YesNoField()
page_count = fields.Int()
transaction_date = fields.Raw(allow_none=True)
last_update_date = fields.Raw(required=True)
recorded_date = fields.Raw(required=True)
assignment_record_has_images = fields.Boolean(required=True)
properties = ListField(fields.Nested(PropertySchema))
assignors = ListField(fields.Nested(AssignorSchema))
assignees = ListField(fields.Nested(AssigneeSchema))
@pre_load
def pre_load(self, input_data, **kwargs):
input_data['assignors'] = separate_dicts_by_prefix('pat_assignor', input_data)
input_data['assignees'] = separate_dicts_by_prefix('pat_assignee', input_data)
property_fields = [f.data_key or f.name for f in PropertySchema().fields.values()]
input_data['properties'] = separate_dicts(property_fields, input_data)
input_data['corr_address'] = combine_strings('corr_address', input_data)
input_data['conveyance_text'] = input_data['conveyance_text'].replace('(SEE DOCUMENT FOR DETAILS).', '').strip()
return input_data
class Meta:
unknown = EXCLUDE
additional = ('id', 'conveyance_text', 'date_produced', 'assignment_record_has_images', 'corr_name', 'corr_address', 'assignor', 'assignee') | true | true |
f7f8cb6f0179b6b063f09c96301f1c9980221784 | 1,113 | py | Python | python/src/aoc/year2020/day6.py | ocirne/adventofcode | ea9b5f1b48a04284521e85c96b420ed54adf55f0 | [
"Unlicense"
] | 1 | 2021-02-16T21:30:04.000Z | 2021-02-16T21:30:04.000Z | python/src/aoc/year2020/day6.py | ocirne/adventofcode | ea9b5f1b48a04284521e85c96b420ed54adf55f0 | [
"Unlicense"
] | null | null | null | python/src/aoc/year2020/day6.py | ocirne/adventofcode | ea9b5f1b48a04284521e85c96b420ed54adf55f0 | [
"Unlicense"
] | null | null | null | from collections import defaultdict
from aoc.util import load_example, load_input
def part1(lines):
"""
>>> part1(load_example(__file__, '6'))
11
"""
answers = []
a = {}
for line in lines:
if not line.strip():
answers.append(len(a.keys()))
a = {}
else:
for k in line.strip():
a[k] = True
answers.append(len(a.keys()))
return sum(answers)
def part2(lines):
"""
>>> part2(load_example(__file__, '6'))
6
"""
answers = []
a = defaultdict(lambda: 0)
count_people = 0
for line in lines:
if not line.strip():
answers.append(len([1 for v in a.values() if v == count_people]))
a = defaultdict(lambda: 0)
count_people = 0
else:
for k in line.strip():
a[k] += 1
count_people += 1
answers.append(len([1 for v in a.values() if v == count_people]))
return sum(answers)
if __name__ == "__main__":
data = load_input(__file__, 2020, "6")
print(part1(data))
print(part2(data))
| 23.1875 | 77 | 0.525606 | from collections import defaultdict
from aoc.util import load_example, load_input
def part1(lines):
answers = []
a = {}
for line in lines:
if not line.strip():
answers.append(len(a.keys()))
a = {}
else:
for k in line.strip():
a[k] = True
answers.append(len(a.keys()))
return sum(answers)
def part2(lines):
answers = []
a = defaultdict(lambda: 0)
count_people = 0
for line in lines:
if not line.strip():
answers.append(len([1 for v in a.values() if v == count_people]))
a = defaultdict(lambda: 0)
count_people = 0
else:
for k in line.strip():
a[k] += 1
count_people += 1
answers.append(len([1 for v in a.values() if v == count_people]))
return sum(answers)
if __name__ == "__main__":
data = load_input(__file__, 2020, "6")
print(part1(data))
print(part2(data))
| true | true |
f7f8cb7a4e947608fdf78399dd696a1413e60f46 | 1,555 | py | Python | tests/p2p_test_peers.py | EOTSIO/EOT | d48e22c392a8a74abe8b5761a5fee50d3f75e956 | [
"MIT"
] | null | null | null | tests/p2p_test_peers.py | EOTSIO/EOT | d48e22c392a8a74abe8b5761a5fee50d3f75e956 | [
"MIT"
] | null | null | null | tests/p2p_test_peers.py | EOTSIO/EOT | d48e22c392a8a74abe8b5761a5fee50d3f75e956 | [
"MIT"
] | null | null | null | import subprocess
class P2PTestPeers:
#for testing with localhost
sshname = "testnet" # ssh name for executing remote commands
hosts = ["localhost"] # host list
ports = [8888] # eotiod listening port of each host
devs = ["lo0"] # network device of each host
#for testing with testnet2
#sshname = "testnet" # ssh name for executing remote commands
#hosts = ["10.160.11.101", "10.160.12.102", "10.160.13.103", "10.160.11.104", "10.160.12.105", "10.160.13.106", "10.160.11.107", "10.160.12.108", "10.160.13.109", "10.160.11.110", "10.160.12.111", "10.160.13.112", "10.160.11.113", "10.160.12.114", "10.160.13.115", "10.160.11.116", "10.160.12.117", "10.160.13.118", "10.160.11.119", "10.160.12.120", "10.160.13.121", "10.160.11.122"] # host list
#ports = [8888, 8888,8888,8888,8888,8888,8888,8888,8888,8888,8888,8888,8888,8888,8888,8888,8888,8888,8888,8888,8888, 8888] # eotiod listening port of each host
#devs = ["ens3", "ens3", "ens3", "ens3", "ens3", "ens3", "ens3", "ens3", "ens3", "ens3", "ens3", "ens3", "ens3", "ens3", "ens3", "ens3", "ens3", "ens3", "ens3", "ens3", "ens3", "ens3"] # network device of each host
@staticmethod
def exec(remoteCmd, toprint=True):
for i in range(len(P2PTestPeers.hosts)):
remoteCmd2 = remoteCmd.replace("{dev}", P2PTestPeers.devs[i])
cmd = "ssh " + P2PTestPeers.sshname + "@" + P2PTestPeers.hosts[i] + ' ' + remoteCmd2
if toprint is True:
print("execute:" + cmd)
subprocess.call(cmd, shell=True) | 64.791667 | 399 | 0.615434 | import subprocess
class P2PTestPeers:
sshname = "testnet"
hosts = ["localhost"]
ports = [8888]
devs = ["lo0"]
sts)):
remoteCmd2 = remoteCmd.replace("{dev}", P2PTestPeers.devs[i])
cmd = "ssh " + P2PTestPeers.sshname + "@" + P2PTestPeers.hosts[i] + ' ' + remoteCmd2
if toprint is True:
print("execute:" + cmd)
subprocess.call(cmd, shell=True) | true | true |
f7f8cb8010bdf2d35bf0b3602e2ae3fdd8f3ae58 | 158 | py | Python | runner.py | alunegov/ids_screens | 2699556651195c1f9e50c36ae119825cadf63370 | [
"MIT"
] | null | null | null | runner.py | alunegov/ids_screens | 2699556651195c1f9e50c36ae119825cadf63370 | [
"MIT"
] | null | null | null | runner.py | alunegov/ids_screens | 2699556651195c1f9e50c36ae119825cadf63370 | [
"MIT"
] | null | null | null | """Convenience wrapper for running ids_screens directly from source tree."""
from ids_screens.ids_screens import main
if __name__ == '__main__':
main()
| 22.571429 | 76 | 0.753165 |
from ids_screens.ids_screens import main
if __name__ == '__main__':
main()
| true | true |
f7f8cb8b29bcf2601a14807eec74793482aae454 | 479 | py | Python | classProject.py | Ayon134/code_for_Kids | d90698bb38efe5e26c31f02bd129bfdadea158e2 | [
"MIT"
] | null | null | null | classProject.py | Ayon134/code_for_Kids | d90698bb38efe5e26c31f02bd129bfdadea158e2 | [
"MIT"
] | null | null | null | classProject.py | Ayon134/code_for_Kids | d90698bb38efe5e26c31f02bd129bfdadea158e2 | [
"MIT"
] | 2 | 2021-01-08T03:52:46.000Z | 2021-04-01T19:16:12.000Z | import smtplib, ssl
port = 465
smtpServer = 'smtp.gmail.com'
sender = 'omarhasan115@gmail.com'
receiver = 'zabeer.omar07@gmail.com'
password = input('enter your password here')
message = """\
Subject: Python Consultation Hour
Please Do Active on 7.00 PM Tomorrow, Thank you"""
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtpServer, port, context=context) as server:
server.login(sender, password)
server.sendmail(sender, receiver, message) | 25.210526 | 67 | 0.736952 | import smtplib, ssl
port = 465
smtpServer = 'smtp.gmail.com'
sender = 'omarhasan115@gmail.com'
receiver = 'zabeer.omar07@gmail.com'
password = input('enter your password here')
message = """\
Subject: Python Consultation Hour
Please Do Active on 7.00 PM Tomorrow, Thank you"""
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtpServer, port, context=context) as server:
server.login(sender, password)
server.sendmail(sender, receiver, message) | true | true |
f7f8cc629f3ef283b80fc6fef301a8d90d6fa82c | 20,552 | py | Python | mmdet/core/evaluation/class_names.py | ideokas/Skripsi | d5f683d6257d1db79fd00597ad1a6733c0772cfb | [
"Apache-2.0"
] | null | null | null | mmdet/core/evaluation/class_names.py | ideokas/Skripsi | d5f683d6257d1db79fd00597ad1a6733c0772cfb | [
"Apache-2.0"
] | null | null | null | mmdet/core/evaluation/class_names.py | ideokas/Skripsi | d5f683d6257d1db79fd00597ad1a6733c0772cfb | [
"Apache-2.0"
] | null | null | null | # Copyright (c) OpenMMLab. All rights reserved.
import mmcv
def wider_face_classes():
return ['face']
def voc_classes():
return [
'crazing', 'inclusion', 'patches', 'pitted_surface', 'rolled-in_scale',
'scratches
]
def imagenet_det_classes():
return [
'accordion', 'airplane', 'ant', 'antelope', 'apple', 'armadillo',
'artichoke', 'axe', 'baby_bed', 'backpack', 'bagel', 'balance_beam',
'banana', 'band_aid', 'banjo', 'baseball', 'basketball', 'bathing_cap',
'beaker', 'bear', 'bee', 'bell_pepper', 'bench', 'bicycle', 'binder',
'bird', 'bookshelf', 'bow_tie', 'bow', 'bowl', 'brassiere', 'burrito',
'bus', 'butterfly', 'camel', 'can_opener', 'car', 'cart', 'cattle',
'cello', 'centipede', 'chain_saw', 'chair', 'chime', 'cocktail_shaker',
'coffee_maker', 'computer_keyboard', 'computer_mouse', 'corkscrew',
'cream', 'croquet_ball', 'crutch', 'cucumber', 'cup_or_mug', 'diaper',
'digital_clock', 'dishwasher', 'dog', 'domestic_cat', 'dragonfly',
'drum', 'dumbbell', 'electric_fan', 'elephant', 'face_powder', 'fig',
'filing_cabinet', 'flower_pot', 'flute', 'fox', 'french_horn', 'frog',
'frying_pan', 'giant_panda', 'goldfish', 'golf_ball', 'golfcart',
'guacamole', 'guitar', 'hair_dryer', 'hair_spray', 'hamburger',
'hammer', 'hamster', 'harmonica', 'harp', 'hat_with_a_wide_brim',
'head_cabbage', 'helmet', 'hippopotamus', 'horizontal_bar', 'horse',
'hotdog', 'iPod', 'isopod', 'jellyfish', 'koala_bear', 'ladle',
'ladybug', 'lamp', 'laptop', 'lemon', 'lion', 'lipstick', 'lizard',
'lobster', 'maillot', 'maraca', 'microphone', 'microwave', 'milk_can',
'miniskirt', 'monkey', 'motorcycle', 'mushroom', 'nail', 'neck_brace',
'oboe', 'orange', 'otter', 'pencil_box', 'pencil_sharpener', 'perfume',
'person', 'piano', 'pineapple', 'ping-pong_ball', 'pitcher', 'pizza',
'plastic_bag', 'plate_rack', 'pomegranate', 'popsicle', 'porcupine',
'power_drill', 'pretzel', 'printer', 'puck', 'punching_bag', 'purse',
'rabbit', 'racket', 'ray', 'red_panda', 'refrigerator',
'remote_control', 'rubber_eraser', 'rugby_ball', 'ruler',
'salt_or_pepper_shaker', 'saxophone', 'scorpion', 'screwdriver',
'seal', 'sheep', 'ski', 'skunk', 'snail', 'snake', 'snowmobile',
'snowplow', 'soap_dispenser', 'soccer_ball', 'sofa', 'spatula',
'squirrel', 'starfish', 'stethoscope', 'stove', 'strainer',
'strawberry', 'stretcher', 'sunglasses', 'swimming_trunks', 'swine',
'syringe', 'table', 'tape_player', 'tennis_ball', 'tick', 'tie',
'tiger', 'toaster', 'traffic_light', 'train', 'trombone', 'trumpet',
'turtle', 'tv_or_monitor', 'unicycle', 'vacuum', 'violin',
'volleyball', 'waffle_iron', 'washer', 'water_bottle', 'watercraft',
'whale', 'wine_bottle', 'zebra'
]
def imagenet_vid_classes():
return [
'airplane', 'antelope', 'bear', 'bicycle', 'bird', 'bus', 'car',
'cattle', 'dog', 'domestic_cat', 'elephant', 'fox', 'giant_panda',
'hamster', 'horse', 'lion', 'lizard', 'monkey', 'motorcycle', 'rabbit',
'red_panda', 'sheep', 'snake', 'squirrel', 'tiger', 'train', 'turtle',
'watercraft', 'whale', 'zebra'
]
def coco_classes():
return [
'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train',
'truck', 'boat', 'traffic_light', 'fire_hydrant', 'stop_sign',
'parking_meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep',
'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella',
'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard',
'sports_ball', 'kite', 'baseball_bat', 'baseball_glove', 'skateboard',
'surfboard', 'tennis_racket', 'bottle', 'wine_glass', 'cup', 'fork',
'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange',
'broccoli', 'carrot', 'hot_dog', 'pizza', 'donut', 'cake', 'chair',
'couch', 'potted_plant', 'bed', 'dining_table', 'toilet', 'tv',
'laptop', 'mouse', 'remote', 'keyboard', 'cell_phone', 'microwave',
'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase',
'scissors', 'teddy_bear', 'hair_drier', 'toothbrush'
]
def cityscapes_classes():
return [
'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle',
'bicycle'
]
def oid_challenge_classes():
return [
'Footwear', 'Jeans', 'House', 'Tree', 'Woman', 'Man', 'Land vehicle',
'Person', 'Wheel', 'Bus', 'Human face', 'Bird', 'Dress', 'Girl',
'Vehicle', 'Building', 'Cat', 'Car', 'Belt', 'Elephant', 'Dessert',
'Butterfly', 'Train', 'Guitar', 'Poster', 'Book', 'Boy', 'Bee',
'Flower', 'Window', 'Hat', 'Human head', 'Dog', 'Human arm', 'Drink',
'Human mouth', 'Human hair', 'Human nose', 'Human hand', 'Table',
'Marine invertebrates', 'Fish', 'Sculpture', 'Rose', 'Street light',
'Glasses', 'Fountain', 'Skyscraper', 'Swimwear', 'Brassiere', 'Drum',
'Duck', 'Countertop', 'Furniture', 'Ball', 'Human leg', 'Boat',
'Balloon', 'Bicycle helmet', 'Goggles', 'Door', 'Human eye', 'Shirt',
'Toy', 'Teddy bear', 'Pasta', 'Tomato', 'Human ear',
'Vehicle registration plate', 'Microphone', 'Musical keyboard',
'Tower', 'Houseplant', 'Flowerpot', 'Fruit', 'Vegetable',
'Musical instrument', 'Suit', 'Motorcycle', 'Bagel', 'French fries',
'Hamburger', 'Chair', 'Salt and pepper shakers', 'Snail', 'Airplane',
'Horse', 'Laptop', 'Computer keyboard', 'Football helmet', 'Cocktail',
'Juice', 'Tie', 'Computer monitor', 'Human beard', 'Bottle',
'Saxophone', 'Lemon', 'Mouse', 'Sock', 'Cowboy hat', 'Sun hat',
'Football', 'Porch', 'Sunglasses', 'Lobster', 'Crab', 'Picture frame',
'Van', 'Crocodile', 'Surfboard', 'Shorts', 'Helicopter', 'Helmet',
'Sports uniform', 'Taxi', 'Swan', 'Goose', 'Coat', 'Jacket', 'Handbag',
'Flag', 'Skateboard', 'Television', 'Tire', 'Spoon', 'Palm tree',
'Stairs', 'Salad', 'Castle', 'Oven', 'Microwave oven', 'Wine',
'Ceiling fan', 'Mechanical fan', 'Cattle', 'Truck', 'Box', 'Ambulance',
'Desk', 'Wine glass', 'Reptile', 'Tank', 'Traffic light', 'Billboard',
'Tent', 'Insect', 'Spider', 'Treadmill', 'Cupboard', 'Shelf',
'Seat belt', 'Human foot', 'Bicycle', 'Bicycle wheel', 'Couch',
'Bookcase', 'Fedora', 'Backpack', 'Bench', 'Oyster',
'Moths and butterflies', 'Lavender', 'Waffle', 'Fork', 'Animal',
'Accordion', 'Mobile phone', 'Plate', 'Coffee cup', 'Saucer',
'Platter', 'Dagger', 'Knife', 'Bull', 'Tortoise', 'Sea turtle', 'Deer',
'Weapon', 'Apple', 'Ski', 'Taco', 'Traffic sign', 'Beer', 'Necklace',
'Sunflower', 'Piano', 'Organ', 'Harpsichord', 'Bed', 'Cabinetry',
'Nightstand', 'Curtain', 'Chest of drawers', 'Drawer', 'Parrot',
'Sandal', 'High heels', 'Tableware', 'Cart', 'Mushroom', 'Kite',
'Missile', 'Seafood', 'Camera', 'Paper towel', 'Toilet paper',
'Sombrero', 'Radish', 'Lighthouse', 'Segway', 'Pig', 'Watercraft',
'Golf cart', 'studio couch', 'Dolphin', 'Whale', 'Earrings', 'Otter',
'Sea lion', 'Whiteboard', 'Monkey', 'Gondola', 'Zebra',
'Baseball glove', 'Scarf', 'Adhesive tape', 'Trousers', 'Scoreboard',
'Lily', 'Carnivore', 'Power plugs and sockets', 'Office building',
'Sandwich', 'Swimming pool', 'Headphones', 'Tin can', 'Crown', 'Doll',
'Cake', 'Frog', 'Beetle', 'Ant', 'Gas stove', 'Canoe', 'Falcon',
'Blue jay', 'Egg', 'Fire hydrant', 'Raccoon', 'Muffin', 'Wall clock',
'Coffee', 'Mug', 'Tea', 'Bear', 'Waste container', 'Home appliance',
'Candle', 'Lion', 'Mirror', 'Starfish', 'Marine mammal', 'Wheelchair',
'Umbrella', 'Alpaca', 'Violin', 'Cello', 'Brown bear', 'Canary', 'Bat',
'Ruler', 'Plastic bag', 'Penguin', 'Watermelon', 'Harbor seal', 'Pen',
'Pumpkin', 'Harp', 'Kitchen appliance', 'Roller skates', 'Bust',
'Coffee table', 'Tennis ball', 'Tennis racket', 'Ladder', 'Boot',
'Bowl', 'Stop sign', 'Volleyball', 'Eagle', 'Paddle', 'Chicken',
'Skull', 'Lamp', 'Beehive', 'Maple', 'Sink', 'Goldfish', 'Tripod',
'Coconut', 'Bidet', 'Tap', 'Bathroom cabinet', 'Toilet',
'Filing cabinet', 'Pretzel', 'Table tennis racket', 'Bronze sculpture',
'Rocket', 'Mouse', 'Hamster', 'Lizard', 'Lifejacket', 'Goat',
'Washing machine', 'Trumpet', 'Horn', 'Trombone', 'Sheep',
'Tablet computer', 'Pillow', 'Kitchen & dining room table',
'Parachute', 'Raven', 'Glove', 'Loveseat', 'Christmas tree',
'Shellfish', 'Rifle', 'Shotgun', 'Sushi', 'Sparrow', 'Bread',
'Toaster', 'Watch', 'Asparagus', 'Artichoke', 'Suitcase', 'Antelope',
'Broccoli', 'Ice cream', 'Racket', 'Banana', 'Cookie', 'Cucumber',
'Dragonfly', 'Lynx', 'Caterpillar', 'Light bulb', 'Office supplies',
'Miniskirt', 'Skirt', 'Fireplace', 'Potato', 'Light switch',
'Croissant', 'Cabbage', 'Ladybug', 'Handgun', 'Luggage and bags',
'Window blind', 'Snowboard', 'Baseball bat', 'Digital clock',
'Serving tray', 'Infant bed', 'Sofa bed', 'Guacamole', 'Fox', 'Pizza',
'Snowplow', 'Jet ski', 'Refrigerator', 'Lantern', 'Convenience store',
'Sword', 'Rugby ball', 'Owl', 'Ostrich', 'Pancake', 'Strawberry',
'Carrot', 'Tart', 'Dice', 'Turkey', 'Rabbit', 'Invertebrate', 'Vase',
'Stool', 'Swim cap', 'Shower', 'Clock', 'Jellyfish', 'Aircraft',
'Chopsticks', 'Orange', 'Snake', 'Sewing machine', 'Kangaroo', 'Mixer',
'Food processor', 'Shrimp', 'Towel', 'Porcupine', 'Jaguar', 'Cannon',
'Limousine', 'Mule', 'Squirrel', 'Kitchen knife', 'Tiara', 'Tiger',
'Bow and arrow', 'Candy', 'Rhinoceros', 'Shark', 'Cricket ball',
'Doughnut', 'Plumbing fixture', 'Camel', 'Polar bear', 'Coin',
'Printer', 'Blender', 'Giraffe', 'Billiard table', 'Kettle',
'Dinosaur', 'Pineapple', 'Zucchini', 'Jug', 'Barge', 'Teapot',
'Golf ball', 'Binoculars', 'Scissors', 'Hot dog', 'Door handle',
'Seahorse', 'Bathtub', 'Leopard', 'Centipede', 'Grapefruit', 'Snowman',
'Cheetah', 'Alarm clock', 'Grape', 'Wrench', 'Wok', 'Bell pepper',
'Cake stand', 'Barrel', 'Woodpecker', 'Flute', 'Corded phone',
'Willow', 'Punching bag', 'Pomegranate', 'Telephone', 'Pear',
'Common fig', 'Bench', 'Wood-burning stove', 'Burrito', 'Nail',
'Turtle', 'Submarine sandwich', 'Drinking straw', 'Peach', 'Popcorn',
'Frying pan', 'Picnic basket', 'Honeycomb', 'Envelope', 'Mango',
'Cutting board', 'Pitcher', 'Stationary bicycle', 'Dumbbell',
'Personal care', 'Dog bed', 'Snowmobile', 'Oboe', 'Briefcase',
'Squash', 'Tick', 'Slow cooker', 'Coffeemaker', 'Measuring cup',
'Crutch', 'Stretcher', 'Screwdriver', 'Flashlight', 'Spatula',
'Pressure cooker', 'Ring binder', 'Beaker', 'Torch', 'Winter melon'
]
def oid_v6_classes():
return [
'Tortoise', 'Container', 'Magpie', 'Sea turtle', 'Football',
'Ambulance', 'Ladder', 'Toothbrush', 'Syringe', 'Sink', 'Toy',
'Organ (Musical Instrument)', 'Cassette deck', 'Apple', 'Human eye',
'Cosmetics', 'Paddle', 'Snowman', 'Beer', 'Chopsticks', 'Human beard',
'Bird', 'Parking meter', 'Traffic light', 'Croissant', 'Cucumber',
'Radish', 'Towel', 'Doll', 'Skull', 'Washing machine', 'Glove', 'Tick',
'Belt', 'Sunglasses', 'Banjo', 'Cart', 'Ball', 'Backpack', 'Bicycle',
'Home appliance', 'Centipede', 'Boat', 'Surfboard', 'Boot',
'Headphones', 'Hot dog', 'Shorts', 'Fast food', 'Bus', 'Boy',
'Screwdriver', 'Bicycle wheel', 'Barge', 'Laptop', 'Miniskirt',
'Drill (Tool)', 'Dress', 'Bear', 'Waffle', 'Pancake', 'Brown bear',
'Woodpecker', 'Blue jay', 'Pretzel', 'Bagel', 'Tower', 'Teapot',
'Person', 'Bow and arrow', 'Swimwear', 'Beehive', 'Brassiere', 'Bee',
'Bat (Animal)', 'Starfish', 'Popcorn', 'Burrito', 'Chainsaw',
'Balloon', 'Wrench', 'Tent', 'Vehicle registration plate', 'Lantern',
'Toaster', 'Flashlight', 'Billboard', 'Tiara', 'Limousine', 'Necklace',
'Carnivore', 'Scissors', 'Stairs', 'Computer keyboard', 'Printer',
'Traffic sign', 'Chair', 'Shirt', 'Poster', 'Cheese', 'Sock',
'Fire hydrant', 'Land vehicle', 'Earrings', 'Tie', 'Watercraft',
'Cabinetry', 'Suitcase', 'Muffin', 'Bidet', 'Snack', 'Snowmobile',
'Clock', 'Medical equipment', 'Cattle', 'Cello', 'Jet ski', 'Camel',
'Coat', 'Suit', 'Desk', 'Cat', 'Bronze sculpture', 'Juice', 'Gondola',
'Beetle', 'Cannon', 'Computer mouse', 'Cookie', 'Office building',
'Fountain', 'Coin', 'Calculator', 'Cocktail', 'Computer monitor',
'Box', 'Stapler', 'Christmas tree', 'Cowboy hat', 'Hiking equipment',
'Studio couch', 'Drum', 'Dessert', 'Wine rack', 'Drink', 'Zucchini',
'Ladle', 'Human mouth', 'Dairy Product', 'Dice', 'Oven', 'Dinosaur',
'Ratchet (Device)', 'Couch', 'Cricket ball', 'Winter melon', 'Spatula',
'Whiteboard', 'Pencil sharpener', 'Door', 'Hat', 'Shower', 'Eraser',
'Fedora', 'Guacamole', 'Dagger', 'Scarf', 'Dolphin', 'Sombrero',
'Tin can', 'Mug', 'Tap', 'Harbor seal', 'Stretcher', 'Can opener',
'Goggles', 'Human body', 'Roller skates', 'Coffee cup',
'Cutting board', 'Blender', 'Plumbing fixture', 'Stop sign',
'Office supplies', 'Volleyball (Ball)', 'Vase', 'Slow cooker',
'Wardrobe', 'Coffee', 'Whisk', 'Paper towel', 'Personal care', 'Food',
'Sun hat', 'Tree house', 'Flying disc', 'Skirt', 'Gas stove',
'Salt and pepper shakers', 'Mechanical fan', 'Face powder', 'Fax',
'Fruit', 'French fries', 'Nightstand', 'Barrel', 'Kite', 'Tart',
'Treadmill', 'Fox', 'Flag', 'French horn', 'Window blind',
'Human foot', 'Golf cart', 'Jacket', 'Egg (Food)', 'Street light',
'Guitar', 'Pillow', 'Human leg', 'Isopod', 'Grape', 'Human ear',
'Power plugs and sockets', 'Panda', 'Giraffe', 'Woman', 'Door handle',
'Rhinoceros', 'Bathtub', 'Goldfish', 'Houseplant', 'Goat',
'Baseball bat', 'Baseball glove', 'Mixing bowl',
'Marine invertebrates', 'Kitchen utensil', 'Light switch', 'House',
'Horse', 'Stationary bicycle', 'Hammer', 'Ceiling fan', 'Sofa bed',
'Adhesive tape', 'Harp', 'Sandal', 'Bicycle helmet', 'Saucer',
'Harpsichord', 'Human hair', 'Heater', 'Harmonica', 'Hamster',
'Curtain', 'Bed', 'Kettle', 'Fireplace', 'Scale', 'Drinking straw',
'Insect', 'Hair dryer', 'Kitchenware', 'Indoor rower', 'Invertebrate',
'Food processor', 'Bookcase', 'Refrigerator', 'Wood-burning stove',
'Punching bag', 'Common fig', 'Cocktail shaker', 'Jaguar (Animal)',
'Golf ball', 'Fashion accessory', 'Alarm clock', 'Filing cabinet',
'Artichoke', 'Table', 'Tableware', 'Kangaroo', 'Koala', 'Knife',
'Bottle', 'Bottle opener', 'Lynx', 'Lavender (Plant)', 'Lighthouse',
'Dumbbell', 'Human head', 'Bowl', 'Humidifier', 'Porch', 'Lizard',
'Billiard table', 'Mammal', 'Mouse', 'Motorcycle',
'Musical instrument', 'Swim cap', 'Frying pan', 'Snowplow',
'Bathroom cabinet', 'Missile', 'Bust', 'Man', 'Waffle iron', 'Milk',
'Ring binder', 'Plate', 'Mobile phone', 'Baked goods', 'Mushroom',
'Crutch', 'Pitcher (Container)', 'Mirror', 'Personal flotation device',
'Table tennis racket', 'Pencil case', 'Musical keyboard', 'Scoreboard',
'Briefcase', 'Kitchen knife', 'Nail (Construction)', 'Tennis ball',
'Plastic bag', 'Oboe', 'Chest of drawers', 'Ostrich', 'Piano', 'Girl',
'Plant', 'Potato', 'Hair spray', 'Sports equipment', 'Pasta',
'Penguin', 'Pumpkin', 'Pear', 'Infant bed', 'Polar bear', 'Mixer',
'Cupboard', 'Jacuzzi', 'Pizza', 'Digital clock', 'Pig', 'Reptile',
'Rifle', 'Lipstick', 'Skateboard', 'Raven', 'High heels', 'Red panda',
'Rose', 'Rabbit', 'Sculpture', 'Saxophone', 'Shotgun', 'Seafood',
'Submarine sandwich', 'Snowboard', 'Sword', 'Picture frame', 'Sushi',
'Loveseat', 'Ski', 'Squirrel', 'Tripod', 'Stethoscope', 'Submarine',
'Scorpion', 'Segway', 'Training bench', 'Snake', 'Coffee table',
'Skyscraper', 'Sheep', 'Television', 'Trombone', 'Tea', 'Tank', 'Taco',
'Telephone', 'Torch', 'Tiger', 'Strawberry', 'Trumpet', 'Tree',
'Tomato', 'Train', 'Tool', 'Picnic basket', 'Cooking spray',
'Trousers', 'Bowling equipment', 'Football helmet', 'Truck',
'Measuring cup', 'Coffeemaker', 'Violin', 'Vehicle', 'Handbag',
'Paper cutter', 'Wine', 'Weapon', 'Wheel', 'Worm', 'Wok', 'Whale',
'Zebra', 'Auto part', 'Jug', 'Pizza cutter', 'Cream', 'Monkey', 'Lion',
'Bread', 'Platter', 'Chicken', 'Eagle', 'Helicopter', 'Owl', 'Duck',
'Turtle', 'Hippopotamus', 'Crocodile', 'Toilet', 'Toilet paper',
'Squid', 'Clothing', 'Footwear', 'Lemon', 'Spider', 'Deer', 'Frog',
'Banana', 'Rocket', 'Wine glass', 'Countertop', 'Tablet computer',
'Waste container', 'Swimming pool', 'Dog', 'Book', 'Elephant', 'Shark',
'Candle', 'Leopard', 'Axe', 'Hand dryer', 'Soap dispenser',
'Porcupine', 'Flower', 'Canary', 'Cheetah', 'Palm tree', 'Hamburger',
'Maple', 'Building', 'Fish', 'Lobster', 'Garden Asparagus',
'Furniture', 'Hedgehog', 'Airplane', 'Spoon', 'Otter', 'Bull',
'Oyster', 'Horizontal bar', 'Convenience store', 'Bomb', 'Bench',
'Ice cream', 'Caterpillar', 'Butterfly', 'Parachute', 'Orange',
'Antelope', 'Beaker', 'Moths and butterflies', 'Window', 'Closet',
'Castle', 'Jellyfish', 'Goose', 'Mule', 'Swan', 'Peach', 'Coconut',
'Seat belt', 'Raccoon', 'Chisel', 'Fork', 'Lamp', 'Camera',
'Squash (Plant)', 'Racket', 'Human face', 'Human arm', 'Vegetable',
'Diaper', 'Unicycle', 'Falcon', 'Chime', 'Snail', 'Shellfish',
'Cabbage', 'Carrot', 'Mango', 'Jeans', 'Flowerpot', 'Pineapple',
'Drawer', 'Stool', 'Envelope', 'Cake', 'Dragonfly', 'Common sunflower',
'Microwave oven', 'Honeycomb', 'Marine mammal', 'Sea lion', 'Ladybug',
'Shelf', 'Watch', 'Candy', 'Salad', 'Parrot', 'Handgun', 'Sparrow',
'Van', 'Grinder', 'Spice rack', 'Light bulb', 'Corded phone',
'Sports uniform', 'Tennis racket', 'Wall clock', 'Serving tray',
'Kitchen & dining room table', 'Dog bed', 'Cake stand',
'Cat furniture', 'Bathroom accessory', 'Facial tissue holder',
'Pressure cooker', 'Kitchen appliance', 'Tire', 'Ruler',
'Luggage and bags', 'Microphone', 'Broccoli', 'Umbrella', 'Pastry',
'Grapefruit', 'Band-aid', 'Animal', 'Bell pepper', 'Turkey', 'Lily',
'Pomegranate', 'Doughnut', 'Glasses', 'Human nose', 'Pen', 'Ant',
'Car', 'Aircraft', 'Human hand', 'Skunk', 'Teddy bear', 'Watermelon',
'Cantaloupe', 'Dishwasher', 'Flute', 'Balance beam', 'Sandwich',
'Shrimp', 'Sewing machine', 'Binoculars', 'Rays and skates', 'Ipod',
'Accordion', 'Willow', 'Crab', 'Crown', 'Seahorse', 'Perfume',
'Alpaca', 'Taxi', 'Canoe', 'Remote control', 'Wheelchair',
'Rugby ball', 'Armadillo', 'Maracas', 'Helmet'
]
dataset_aliases = {
'voc': ['voc', 'pascal_voc', 'voc07', 'voc12'],
'imagenet_det': ['det', 'imagenet_det', 'ilsvrc_det'],
'imagenet_vid': ['vid', 'imagenet_vid', 'ilsvrc_vid'],
'coco': ['coco', 'mscoco', 'ms_coco'],
'wider_face': ['WIDERFaceDataset', 'wider_face', 'WIDERFace'],
'cityscapes': ['cityscapes'],
'oid_challenge': ['oid_challenge', 'openimages_challenge'],
'oid_v6': ['oid_v6', 'openimages_v6']
}
def get_classes(dataset):
"""Get class names of a dataset."""
alias2name = {}
for name, aliases in dataset_aliases.items():
for alias in aliases:
alias2name[alias] = name
if mmcv.is_str(dataset):
if dataset in alias2name:
labels = eval(alias2name[dataset] + '_classes()')
else:
raise ValueError(f'Unrecognized dataset: {dataset}')
else:
raise TypeError(f'dataset must a str, but got {type(dataset)}')
return labels
| 61.903614 | 79 | 0.57717 |
import mmcv
def wider_face_classes():
return ['face']
def voc_classes():
return [
'crazing', 'inclusion', 'patches', 'pitted_surface', 'rolled-in_scale',
'scratches
]
def imagenet_det_classes():
return [
'accordion', 'airplane', 'ant', 'antelope', 'apple', 'armadillo',
'artichoke', 'axe', 'baby_bed', 'backpack', 'bagel', 'balance_beam',
'banana', 'band_aid', 'banjo', 'baseball', 'basketball', 'bathing_cap',
'beaker', 'bear', 'bee', 'bell_pepper', 'bench', 'bicycle', 'binder',
'bird', 'bookshelf', 'bow_tie', 'bow', 'bowl', 'brassiere', 'burrito',
'bus', 'butterfly', 'camel', 'can_opener', 'car', 'cart', 'cattle',
'cello', 'centipede', 'chain_saw', 'chair', 'chime', 'cocktail_shaker',
'coffee_maker', 'computer_keyboard', 'computer_mouse', 'corkscrew',
'cream', 'croquet_ball', 'crutch', 'cucumber', 'cup_or_mug', 'diaper',
'digital_clock', 'dishwasher', 'dog', 'domestic_cat', 'dragonfly',
'drum', 'dumbbell', 'electric_fan', 'elephant', 'face_powder', 'fig',
'filing_cabinet', 'flower_pot', 'flute', 'fox', 'french_horn', 'frog',
'frying_pan', 'giant_panda', 'goldfish', 'golf_ball', 'golfcart',
'guacamole', 'guitar', 'hair_dryer', 'hair_spray', 'hamburger',
'hammer', 'hamster', 'harmonica', 'harp', 'hat_with_a_wide_brim',
'head_cabbage', 'helmet', 'hippopotamus', 'horizontal_bar', 'horse',
'hotdog', 'iPod', 'isopod', 'jellyfish', 'koala_bear', 'ladle',
'ladybug', 'lamp', 'laptop', 'lemon', 'lion', 'lipstick', 'lizard',
'lobster', 'maillot', 'maraca', 'microphone', 'microwave', 'milk_can',
'miniskirt', 'monkey', 'motorcycle', 'mushroom', 'nail', 'neck_brace',
'oboe', 'orange', 'otter', 'pencil_box', 'pencil_sharpener', 'perfume',
'person', 'piano', 'pineapple', 'ping-pong_ball', 'pitcher', 'pizza',
'plastic_bag', 'plate_rack', 'pomegranate', 'popsicle', 'porcupine',
'power_drill', 'pretzel', 'printer', 'puck', 'punching_bag', 'purse',
'rabbit', 'racket', 'ray', 'red_panda', 'refrigerator',
'remote_control', 'rubber_eraser', 'rugby_ball', 'ruler',
'salt_or_pepper_shaker', 'saxophone', 'scorpion', 'screwdriver',
'seal', 'sheep', 'ski', 'skunk', 'snail', 'snake', 'snowmobile',
'snowplow', 'soap_dispenser', 'soccer_ball', 'sofa', 'spatula',
'squirrel', 'starfish', 'stethoscope', 'stove', 'strainer',
'strawberry', 'stretcher', 'sunglasses', 'swimming_trunks', 'swine',
'syringe', 'table', 'tape_player', 'tennis_ball', 'tick', 'tie',
'tiger', 'toaster', 'traffic_light', 'train', 'trombone', 'trumpet',
'turtle', 'tv_or_monitor', 'unicycle', 'vacuum', 'violin',
'volleyball', 'waffle_iron', 'washer', 'water_bottle', 'watercraft',
'whale', 'wine_bottle', 'zebra'
]
def imagenet_vid_classes():
return [
'airplane', 'antelope', 'bear', 'bicycle', 'bird', 'bus', 'car',
'cattle', 'dog', 'domestic_cat', 'elephant', 'fox', 'giant_panda',
'hamster', 'horse', 'lion', 'lizard', 'monkey', 'motorcycle', 'rabbit',
'red_panda', 'sheep', 'snake', 'squirrel', 'tiger', 'train', 'turtle',
'watercraft', 'whale', 'zebra'
]
def coco_classes():
return [
'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train',
'truck', 'boat', 'traffic_light', 'fire_hydrant', 'stop_sign',
'parking_meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep',
'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella',
'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard',
'sports_ball', 'kite', 'baseball_bat', 'baseball_glove', 'skateboard',
'surfboard', 'tennis_racket', 'bottle', 'wine_glass', 'cup', 'fork',
'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange',
'broccoli', 'carrot', 'hot_dog', 'pizza', 'donut', 'cake', 'chair',
'couch', 'potted_plant', 'bed', 'dining_table', 'toilet', 'tv',
'laptop', 'mouse', 'remote', 'keyboard', 'cell_phone', 'microwave',
'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase',
'scissors', 'teddy_bear', 'hair_drier', 'toothbrush'
]
def cityscapes_classes():
return [
'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle',
'bicycle'
]
def oid_challenge_classes():
return [
'Footwear', 'Jeans', 'House', 'Tree', 'Woman', 'Man', 'Land vehicle',
'Person', 'Wheel', 'Bus', 'Human face', 'Bird', 'Dress', 'Girl',
'Vehicle', 'Building', 'Cat', 'Car', 'Belt', 'Elephant', 'Dessert',
'Butterfly', 'Train', 'Guitar', 'Poster', 'Book', 'Boy', 'Bee',
'Flower', 'Window', 'Hat', 'Human head', 'Dog', 'Human arm', 'Drink',
'Human mouth', 'Human hair', 'Human nose', 'Human hand', 'Table',
'Marine invertebrates', 'Fish', 'Sculpture', 'Rose', 'Street light',
'Glasses', 'Fountain', 'Skyscraper', 'Swimwear', 'Brassiere', 'Drum',
'Duck', 'Countertop', 'Furniture', 'Ball', 'Human leg', 'Boat',
'Balloon', 'Bicycle helmet', 'Goggles', 'Door', 'Human eye', 'Shirt',
'Toy', 'Teddy bear', 'Pasta', 'Tomato', 'Human ear',
'Vehicle registration plate', 'Microphone', 'Musical keyboard',
'Tower', 'Houseplant', 'Flowerpot', 'Fruit', 'Vegetable',
'Musical instrument', 'Suit', 'Motorcycle', 'Bagel', 'French fries',
'Hamburger', 'Chair', 'Salt and pepper shakers', 'Snail', 'Airplane',
'Horse', 'Laptop', 'Computer keyboard', 'Football helmet', 'Cocktail',
'Juice', 'Tie', 'Computer monitor', 'Human beard', 'Bottle',
'Saxophone', 'Lemon', 'Mouse', 'Sock', 'Cowboy hat', 'Sun hat',
'Football', 'Porch', 'Sunglasses', 'Lobster', 'Crab', 'Picture frame',
'Van', 'Crocodile', 'Surfboard', 'Shorts', 'Helicopter', 'Helmet',
'Sports uniform', 'Taxi', 'Swan', 'Goose', 'Coat', 'Jacket', 'Handbag',
'Flag', 'Skateboard', 'Television', 'Tire', 'Spoon', 'Palm tree',
'Stairs', 'Salad', 'Castle', 'Oven', 'Microwave oven', 'Wine',
'Ceiling fan', 'Mechanical fan', 'Cattle', 'Truck', 'Box', 'Ambulance',
'Desk', 'Wine glass', 'Reptile', 'Tank', 'Traffic light', 'Billboard',
'Tent', 'Insect', 'Spider', 'Treadmill', 'Cupboard', 'Shelf',
'Seat belt', 'Human foot', 'Bicycle', 'Bicycle wheel', 'Couch',
'Bookcase', 'Fedora', 'Backpack', 'Bench', 'Oyster',
'Moths and butterflies', 'Lavender', 'Waffle', 'Fork', 'Animal',
'Accordion', 'Mobile phone', 'Plate', 'Coffee cup', 'Saucer',
'Platter', 'Dagger', 'Knife', 'Bull', 'Tortoise', 'Sea turtle', 'Deer',
'Weapon', 'Apple', 'Ski', 'Taco', 'Traffic sign', 'Beer', 'Necklace',
'Sunflower', 'Piano', 'Organ', 'Harpsichord', 'Bed', 'Cabinetry',
'Nightstand', 'Curtain', 'Chest of drawers', 'Drawer', 'Parrot',
'Sandal', 'High heels', 'Tableware', 'Cart', 'Mushroom', 'Kite',
'Missile', 'Seafood', 'Camera', 'Paper towel', 'Toilet paper',
'Sombrero', 'Radish', 'Lighthouse', 'Segway', 'Pig', 'Watercraft',
'Golf cart', 'studio couch', 'Dolphin', 'Whale', 'Earrings', 'Otter',
'Sea lion', 'Whiteboard', 'Monkey', 'Gondola', 'Zebra',
'Baseball glove', 'Scarf', 'Adhesive tape', 'Trousers', 'Scoreboard',
'Lily', 'Carnivore', 'Power plugs and sockets', 'Office building',
'Sandwich', 'Swimming pool', 'Headphones', 'Tin can', 'Crown', 'Doll',
'Cake', 'Frog', 'Beetle', 'Ant', 'Gas stove', 'Canoe', 'Falcon',
'Blue jay', 'Egg', 'Fire hydrant', 'Raccoon', 'Muffin', 'Wall clock',
'Coffee', 'Mug', 'Tea', 'Bear', 'Waste container', 'Home appliance',
'Candle', 'Lion', 'Mirror', 'Starfish', 'Marine mammal', 'Wheelchair',
'Umbrella', 'Alpaca', 'Violin', 'Cello', 'Brown bear', 'Canary', 'Bat',
'Ruler', 'Plastic bag', 'Penguin', 'Watermelon', 'Harbor seal', 'Pen',
'Pumpkin', 'Harp', 'Kitchen appliance', 'Roller skates', 'Bust',
'Coffee table', 'Tennis ball', 'Tennis racket', 'Ladder', 'Boot',
'Bowl', 'Stop sign', 'Volleyball', 'Eagle', 'Paddle', 'Chicken',
'Skull', 'Lamp', 'Beehive', 'Maple', 'Sink', 'Goldfish', 'Tripod',
'Coconut', 'Bidet', 'Tap', 'Bathroom cabinet', 'Toilet',
'Filing cabinet', 'Pretzel', 'Table tennis racket', 'Bronze sculpture',
'Rocket', 'Mouse', 'Hamster', 'Lizard', 'Lifejacket', 'Goat',
'Washing machine', 'Trumpet', 'Horn', 'Trombone', 'Sheep',
'Tablet computer', 'Pillow', 'Kitchen & dining room table',
'Parachute', 'Raven', 'Glove', 'Loveseat', 'Christmas tree',
'Shellfish', 'Rifle', 'Shotgun', 'Sushi', 'Sparrow', 'Bread',
'Toaster', 'Watch', 'Asparagus', 'Artichoke', 'Suitcase', 'Antelope',
'Broccoli', 'Ice cream', 'Racket', 'Banana', 'Cookie', 'Cucumber',
'Dragonfly', 'Lynx', 'Caterpillar', 'Light bulb', 'Office supplies',
'Miniskirt', 'Skirt', 'Fireplace', 'Potato', 'Light switch',
'Croissant', 'Cabbage', 'Ladybug', 'Handgun', 'Luggage and bags',
'Window blind', 'Snowboard', 'Baseball bat', 'Digital clock',
'Serving tray', 'Infant bed', 'Sofa bed', 'Guacamole', 'Fox', 'Pizza',
'Snowplow', 'Jet ski', 'Refrigerator', 'Lantern', 'Convenience store',
'Sword', 'Rugby ball', 'Owl', 'Ostrich', 'Pancake', 'Strawberry',
'Carrot', 'Tart', 'Dice', 'Turkey', 'Rabbit', 'Invertebrate', 'Vase',
'Stool', 'Swim cap', 'Shower', 'Clock', 'Jellyfish', 'Aircraft',
'Chopsticks', 'Orange', 'Snake', 'Sewing machine', 'Kangaroo', 'Mixer',
'Food processor', 'Shrimp', 'Towel', 'Porcupine', 'Jaguar', 'Cannon',
'Limousine', 'Mule', 'Squirrel', 'Kitchen knife', 'Tiara', 'Tiger',
'Bow and arrow', 'Candy', 'Rhinoceros', 'Shark', 'Cricket ball',
'Doughnut', 'Plumbing fixture', 'Camel', 'Polar bear', 'Coin',
'Printer', 'Blender', 'Giraffe', 'Billiard table', 'Kettle',
'Dinosaur', 'Pineapple', 'Zucchini', 'Jug', 'Barge', 'Teapot',
'Golf ball', 'Binoculars', 'Scissors', 'Hot dog', 'Door handle',
'Seahorse', 'Bathtub', 'Leopard', 'Centipede', 'Grapefruit', 'Snowman',
'Cheetah', 'Alarm clock', 'Grape', 'Wrench', 'Wok', 'Bell pepper',
'Cake stand', 'Barrel', 'Woodpecker', 'Flute', 'Corded phone',
'Willow', 'Punching bag', 'Pomegranate', 'Telephone', 'Pear',
'Common fig', 'Bench', 'Wood-burning stove', 'Burrito', 'Nail',
'Turtle', 'Submarine sandwich', 'Drinking straw', 'Peach', 'Popcorn',
'Frying pan', 'Picnic basket', 'Honeycomb', 'Envelope', 'Mango',
'Cutting board', 'Pitcher', 'Stationary bicycle', 'Dumbbell',
'Personal care', 'Dog bed', 'Snowmobile', 'Oboe', 'Briefcase',
'Squash', 'Tick', 'Slow cooker', 'Coffeemaker', 'Measuring cup',
'Crutch', 'Stretcher', 'Screwdriver', 'Flashlight', 'Spatula',
'Pressure cooker', 'Ring binder', 'Beaker', 'Torch', 'Winter melon'
]
def oid_v6_classes():
return [
'Tortoise', 'Container', 'Magpie', 'Sea turtle', 'Football',
'Ambulance', 'Ladder', 'Toothbrush', 'Syringe', 'Sink', 'Toy',
'Organ (Musical Instrument)', 'Cassette deck', 'Apple', 'Human eye',
'Cosmetics', 'Paddle', 'Snowman', 'Beer', 'Chopsticks', 'Human beard',
'Bird', 'Parking meter', 'Traffic light', 'Croissant', 'Cucumber',
'Radish', 'Towel', 'Doll', 'Skull', 'Washing machine', 'Glove', 'Tick',
'Belt', 'Sunglasses', 'Banjo', 'Cart', 'Ball', 'Backpack', 'Bicycle',
'Home appliance', 'Centipede', 'Boat', 'Surfboard', 'Boot',
'Headphones', 'Hot dog', 'Shorts', 'Fast food', 'Bus', 'Boy',
'Screwdriver', 'Bicycle wheel', 'Barge', 'Laptop', 'Miniskirt',
'Drill (Tool)', 'Dress', 'Bear', 'Waffle', 'Pancake', 'Brown bear',
'Woodpecker', 'Blue jay', 'Pretzel', 'Bagel', 'Tower', 'Teapot',
'Person', 'Bow and arrow', 'Swimwear', 'Beehive', 'Brassiere', 'Bee',
'Bat (Animal)', 'Starfish', 'Popcorn', 'Burrito', 'Chainsaw',
'Balloon', 'Wrench', 'Tent', 'Vehicle registration plate', 'Lantern',
'Toaster', 'Flashlight', 'Billboard', 'Tiara', 'Limousine', 'Necklace',
'Carnivore', 'Scissors', 'Stairs', 'Computer keyboard', 'Printer',
'Traffic sign', 'Chair', 'Shirt', 'Poster', 'Cheese', 'Sock',
'Fire hydrant', 'Land vehicle', 'Earrings', 'Tie', 'Watercraft',
'Cabinetry', 'Suitcase', 'Muffin', 'Bidet', 'Snack', 'Snowmobile',
'Clock', 'Medical equipment', 'Cattle', 'Cello', 'Jet ski', 'Camel',
'Coat', 'Suit', 'Desk', 'Cat', 'Bronze sculpture', 'Juice', 'Gondola',
'Beetle', 'Cannon', 'Computer mouse', 'Cookie', 'Office building',
'Fountain', 'Coin', 'Calculator', 'Cocktail', 'Computer monitor',
'Box', 'Stapler', 'Christmas tree', 'Cowboy hat', 'Hiking equipment',
'Studio couch', 'Drum', 'Dessert', 'Wine rack', 'Drink', 'Zucchini',
'Ladle', 'Human mouth', 'Dairy Product', 'Dice', 'Oven', 'Dinosaur',
'Ratchet (Device)', 'Couch', 'Cricket ball', 'Winter melon', 'Spatula',
'Whiteboard', 'Pencil sharpener', 'Door', 'Hat', 'Shower', 'Eraser',
'Fedora', 'Guacamole', 'Dagger', 'Scarf', 'Dolphin', 'Sombrero',
'Tin can', 'Mug', 'Tap', 'Harbor seal', 'Stretcher', 'Can opener',
'Goggles', 'Human body', 'Roller skates', 'Coffee cup',
'Cutting board', 'Blender', 'Plumbing fixture', 'Stop sign',
'Office supplies', 'Volleyball (Ball)', 'Vase', 'Slow cooker',
'Wardrobe', 'Coffee', 'Whisk', 'Paper towel', 'Personal care', 'Food',
'Sun hat', 'Tree house', 'Flying disc', 'Skirt', 'Gas stove',
'Salt and pepper shakers', 'Mechanical fan', 'Face powder', 'Fax',
'Fruit', 'French fries', 'Nightstand', 'Barrel', 'Kite', 'Tart',
'Treadmill', 'Fox', 'Flag', 'French horn', 'Window blind',
'Human foot', 'Golf cart', 'Jacket', 'Egg (Food)', 'Street light',
'Guitar', 'Pillow', 'Human leg', 'Isopod', 'Grape', 'Human ear',
'Power plugs and sockets', 'Panda', 'Giraffe', 'Woman', 'Door handle',
'Rhinoceros', 'Bathtub', 'Goldfish', 'Houseplant', 'Goat',
'Baseball bat', 'Baseball glove', 'Mixing bowl',
'Marine invertebrates', 'Kitchen utensil', 'Light switch', 'House',
'Horse', 'Stationary bicycle', 'Hammer', 'Ceiling fan', 'Sofa bed',
'Adhesive tape', 'Harp', 'Sandal', 'Bicycle helmet', 'Saucer',
'Harpsichord', 'Human hair', 'Heater', 'Harmonica', 'Hamster',
'Curtain', 'Bed', 'Kettle', 'Fireplace', 'Scale', 'Drinking straw',
'Insect', 'Hair dryer', 'Kitchenware', 'Indoor rower', 'Invertebrate',
'Food processor', 'Bookcase', 'Refrigerator', 'Wood-burning stove',
'Punching bag', 'Common fig', 'Cocktail shaker', 'Jaguar (Animal)',
'Golf ball', 'Fashion accessory', 'Alarm clock', 'Filing cabinet',
'Artichoke', 'Table', 'Tableware', 'Kangaroo', 'Koala', 'Knife',
'Bottle', 'Bottle opener', 'Lynx', 'Lavender (Plant)', 'Lighthouse',
'Dumbbell', 'Human head', 'Bowl', 'Humidifier', 'Porch', 'Lizard',
'Billiard table', 'Mammal', 'Mouse', 'Motorcycle',
'Musical instrument', 'Swim cap', 'Frying pan', 'Snowplow',
'Bathroom cabinet', 'Missile', 'Bust', 'Man', 'Waffle iron', 'Milk',
'Ring binder', 'Plate', 'Mobile phone', 'Baked goods', 'Mushroom',
'Crutch', 'Pitcher (Container)', 'Mirror', 'Personal flotation device',
'Table tennis racket', 'Pencil case', 'Musical keyboard', 'Scoreboard',
'Briefcase', 'Kitchen knife', 'Nail (Construction)', 'Tennis ball',
'Plastic bag', 'Oboe', 'Chest of drawers', 'Ostrich', 'Piano', 'Girl',
'Plant', 'Potato', 'Hair spray', 'Sports equipment', 'Pasta',
'Penguin', 'Pumpkin', 'Pear', 'Infant bed', 'Polar bear', 'Mixer',
'Cupboard', 'Jacuzzi', 'Pizza', 'Digital clock', 'Pig', 'Reptile',
'Rifle', 'Lipstick', 'Skateboard', 'Raven', 'High heels', 'Red panda',
'Rose', 'Rabbit', 'Sculpture', 'Saxophone', 'Shotgun', 'Seafood',
'Submarine sandwich', 'Snowboard', 'Sword', 'Picture frame', 'Sushi',
'Loveseat', 'Ski', 'Squirrel', 'Tripod', 'Stethoscope', 'Submarine',
'Scorpion', 'Segway', 'Training bench', 'Snake', 'Coffee table',
'Skyscraper', 'Sheep', 'Television', 'Trombone', 'Tea', 'Tank', 'Taco',
'Telephone', 'Torch', 'Tiger', 'Strawberry', 'Trumpet', 'Tree',
'Tomato', 'Train', 'Tool', 'Picnic basket', 'Cooking spray',
'Trousers', 'Bowling equipment', 'Football helmet', 'Truck',
'Measuring cup', 'Coffeemaker', 'Violin', 'Vehicle', 'Handbag',
'Paper cutter', 'Wine', 'Weapon', 'Wheel', 'Worm', 'Wok', 'Whale',
'Zebra', 'Auto part', 'Jug', 'Pizza cutter', 'Cream', 'Monkey', 'Lion',
'Bread', 'Platter', 'Chicken', 'Eagle', 'Helicopter', 'Owl', 'Duck',
'Turtle', 'Hippopotamus', 'Crocodile', 'Toilet', 'Toilet paper',
'Squid', 'Clothing', 'Footwear', 'Lemon', 'Spider', 'Deer', 'Frog',
'Banana', 'Rocket', 'Wine glass', 'Countertop', 'Tablet computer',
'Waste container', 'Swimming pool', 'Dog', 'Book', 'Elephant', 'Shark',
'Candle', 'Leopard', 'Axe', 'Hand dryer', 'Soap dispenser',
'Porcupine', 'Flower', 'Canary', 'Cheetah', 'Palm tree', 'Hamburger',
'Maple', 'Building', 'Fish', 'Lobster', 'Garden Asparagus',
'Furniture', 'Hedgehog', 'Airplane', 'Spoon', 'Otter', 'Bull',
'Oyster', 'Horizontal bar', 'Convenience store', 'Bomb', 'Bench',
'Ice cream', 'Caterpillar', 'Butterfly', 'Parachute', 'Orange',
'Antelope', 'Beaker', 'Moths and butterflies', 'Window', 'Closet',
'Castle', 'Jellyfish', 'Goose', 'Mule', 'Swan', 'Peach', 'Coconut',
'Seat belt', 'Raccoon', 'Chisel', 'Fork', 'Lamp', 'Camera',
'Squash (Plant)', 'Racket', 'Human face', 'Human arm', 'Vegetable',
'Diaper', 'Unicycle', 'Falcon', 'Chime', 'Snail', 'Shellfish',
'Cabbage', 'Carrot', 'Mango', 'Jeans', 'Flowerpot', 'Pineapple',
'Drawer', 'Stool', 'Envelope', 'Cake', 'Dragonfly', 'Common sunflower',
'Microwave oven', 'Honeycomb', 'Marine mammal', 'Sea lion', 'Ladybug',
'Shelf', 'Watch', 'Candy', 'Salad', 'Parrot', 'Handgun', 'Sparrow',
'Van', 'Grinder', 'Spice rack', 'Light bulb', 'Corded phone',
'Sports uniform', 'Tennis racket', 'Wall clock', 'Serving tray',
'Kitchen & dining room table', 'Dog bed', 'Cake stand',
'Cat furniture', 'Bathroom accessory', 'Facial tissue holder',
'Pressure cooker', 'Kitchen appliance', 'Tire', 'Ruler',
'Luggage and bags', 'Microphone', 'Broccoli', 'Umbrella', 'Pastry',
'Grapefruit', 'Band-aid', 'Animal', 'Bell pepper', 'Turkey', 'Lily',
'Pomegranate', 'Doughnut', 'Glasses', 'Human nose', 'Pen', 'Ant',
'Car', 'Aircraft', 'Human hand', 'Skunk', 'Teddy bear', 'Watermelon',
'Cantaloupe', 'Dishwasher', 'Flute', 'Balance beam', 'Sandwich',
'Shrimp', 'Sewing machine', 'Binoculars', 'Rays and skates', 'Ipod',
'Accordion', 'Willow', 'Crab', 'Crown', 'Seahorse', 'Perfume',
'Alpaca', 'Taxi', 'Canoe', 'Remote control', 'Wheelchair',
'Rugby ball', 'Armadillo', 'Maracas', 'Helmet'
]
dataset_aliases = {
'voc': ['voc', 'pascal_voc', 'voc07', 'voc12'],
'imagenet_det': ['det', 'imagenet_det', 'ilsvrc_det'],
'imagenet_vid': ['vid', 'imagenet_vid', 'ilsvrc_vid'],
'coco': ['coco', 'mscoco', 'ms_coco'],
'wider_face': ['WIDERFaceDataset', 'wider_face', 'WIDERFace'],
'cityscapes': ['cityscapes'],
'oid_challenge': ['oid_challenge', 'openimages_challenge'],
'oid_v6': ['oid_v6', 'openimages_v6']
}
def get_classes(dataset):
"""Get class names of a dataset."""
alias2name = {}
for name, aliases in dataset_aliases.items():
for alias in aliases:
alias2name[alias] = name
if mmcv.is_str(dataset):
if dataset in alias2name:
labels = eval(alias2name[dataset] + '_classes()')
else:
raise ValueError(f'Unrecognized dataset: {dataset}')
else:
raise TypeError(f'dataset must a str, but got {type(dataset)}')
return labels
| false | true |
f7f8cc84d8b50b3977a9162b1ea1e2e57c34e908 | 3,801 | py | Python | test/multiapi/Expected/AcceptanceTests/MultiapiDataPlane/multiapidataplane/v2/aio/_multiapi_service_client.py | qwordy/autorest.python | 6b12df51c2a39a1285546b5a771b69f5896e794f | [
"MIT"
] | null | null | null | test/multiapi/Expected/AcceptanceTests/MultiapiDataPlane/multiapidataplane/v2/aio/_multiapi_service_client.py | qwordy/autorest.python | 6b12df51c2a39a1285546b5a771b69f5896e794f | [
"MIT"
] | null | null | null | test/multiapi/Expected/AcceptanceTests/MultiapiDataPlane/multiapidataplane/v2/aio/_multiapi_service_client.py | qwordy/autorest.python | 6b12df51c2a39a1285546b5a771b69f5896e794f | [
"MIT"
] | null | null | null | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, Optional, TYPE_CHECKING
from azure.core import AsyncPipelineClient
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from msrest import Deserializer, Serializer
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
from ._configuration import MultiapiServiceClientConfiguration
from .operations import MultiapiServiceClientOperationsMixin
from .operations import OperationGroupOneOperations
from .operations import OperationGroupTwoOperations
from .. import models
class MultiapiServiceClient(MultiapiServiceClientOperationsMixin):
"""Service client for multiapi client testing.
:ivar operation_group_one: OperationGroupOneOperations operations
:vartype operation_group_one: multiapidataplane.v2.aio.operations.OperationGroupOneOperations
:ivar operation_group_two: OperationGroupTwoOperations operations
:vartype operation_group_two: multiapidataplane.v2.aio.operations.OperationGroupTwoOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials_async.AsyncTokenCredential
:param str base_url: Service URL
"""
def __init__(
self,
credential: "AsyncTokenCredential",
base_url: Optional[str] = None,
**kwargs: Any
) -> None:
if not base_url:
base_url = 'http://localhost:3000'
self._config = MultiapiServiceClientConfiguration(credential, **kwargs)
self._client = AsyncPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._serialize.client_side_validation = False
self._deserialize = Deserializer(client_models)
self.operation_group_one = OperationGroupOneOperations(
self._client, self._config, self._serialize, self._deserialize)
self.operation_group_two = OperationGroupTwoOperations(
self._client, self._config, self._serialize, self._deserialize)
async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse:
"""Runs the network request through the client's chained policies.
:param http_request: The network request you want to make. Required.
:type http_request: ~azure.core.pipeline.transport.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to True.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.pipeline.transport.AsyncHttpResponse
"""
http_request.url = self._client.format_url(http_request.url)
stream = kwargs.pop("stream", True)
pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs)
return pipeline_response.http_response
async def close(self) -> None:
await self._client.close()
async def __aenter__(self) -> "MultiapiServiceClient":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
| 46.353659 | 99 | 0.717969 |
from typing import Any, Optional, TYPE_CHECKING
from azure.core import AsyncPipelineClient
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from msrest import Deserializer, Serializer
if TYPE_CHECKING:
from azure.core.credentials_async import AsyncTokenCredential
from ._configuration import MultiapiServiceClientConfiguration
from .operations import MultiapiServiceClientOperationsMixin
from .operations import OperationGroupOneOperations
from .operations import OperationGroupTwoOperations
from .. import models
class MultiapiServiceClient(MultiapiServiceClientOperationsMixin):
def __init__(
self,
credential: "AsyncTokenCredential",
base_url: Optional[str] = None,
**kwargs: Any
) -> None:
if not base_url:
base_url = 'http://localhost:3000'
self._config = MultiapiServiceClientConfiguration(credential, **kwargs)
self._client = AsyncPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._serialize.client_side_validation = False
self._deserialize = Deserializer(client_models)
self.operation_group_one = OperationGroupOneOperations(
self._client, self._config, self._serialize, self._deserialize)
self.operation_group_two = OperationGroupTwoOperations(
self._client, self._config, self._serialize, self._deserialize)
async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse:
http_request.url = self._client.format_url(http_request.url)
stream = kwargs.pop("stream", True)
pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs)
return pipeline_response.http_response
async def close(self) -> None:
await self._client.close()
async def __aenter__(self) -> "MultiapiServiceClient":
await self._client.__aenter__()
return self
async def __aexit__(self, *exc_details) -> None:
await self._client.__aexit__(*exc_details)
| true | true |
f7f8ccb5292deb36f25ccbf362f42f1c7940e74b | 2,928 | py | Python | examples/run_dien.py | AlexanLee/DeepCTR | 1ff32c6b0105e3341ddf34e7074e596032bff158 | [
"Apache-2.0"
] | null | null | null | examples/run_dien.py | AlexanLee/DeepCTR | 1ff32c6b0105e3341ddf34e7074e596032bff158 | [
"Apache-2.0"
] | null | null | null | examples/run_dien.py | AlexanLee/DeepCTR | 1ff32c6b0105e3341ddf34e7074e596032bff158 | [
"Apache-2.0"
] | null | null | null | import numpy as np
import tensorflow as tf
from deepctr.models import DIEN
from deepctr.inputs import SparseFeat, DenseFeat, VarLenSparseFeat, get_feature_names
def get_xy_fd(use_neg=False, hash_flag=False):
feature_columns = [SparseFeat('user', 3, embedding_dim=10, use_hash=hash_flag),
SparseFeat('gender', 2, embedding_dim=4, use_hash=hash_flag),
SparseFeat('item', 3 + 1, embedding_dim=8, use_hash=hash_flag),
SparseFeat('item_gender', 2 + 1, embedding_dim=4, use_hash=hash_flag),
DenseFeat('score', 1)]
feature_columns += [
VarLenSparseFeat('hist_item', maxlen=4, vocabulary_size=3 + 1, embedding_dim=8, embedding_name='item',
length_name="seq_length"),
VarLenSparseFeat('hist_item_gender', maxlen=4, vocabulary_size=3 + 1, embedding_dim=4,
embedding_name='item_gender', length_name="seq_length")]
behavior_feature_list = ["item", "item_gender"]
uid = np.array([0, 1, 2])
ugender = np.array([0, 1, 0])
iid = np.array([1, 2, 3]) # 0 is mask value
igender = np.array([1, 2, 1]) # 0 is mask value
score = np.array([0.1, 0.2, 0.3])
hist_iid = np.array([[1, 2, 3, 0], [1, 2, 3, 0], [1, 2, 0, 0]])
hist_igender = np.array([[1, 1, 2, 0], [2, 1, 1, 0], [2, 1, 0, 0]])
behavior_length = np.array([3, 3, 2])
feature_dict = {'user': uid, 'gender': ugender, 'item': iid, 'item_gender': igender,
'hist_item': hist_iid, 'hist_item_gender': hist_igender,
'score': score, "seq_length": behavior_length}
if use_neg:
feature_dict['neg_hist_item'] = np.array([[1, 2, 3, 0], [1, 2, 3, 0], [1, 2, 0, 0]])
feature_dict['neg_hist_item_gender'] = np.array([[1, 1, 2, 0], [2, 1, 1, 0], [2, 1, 0, 0]])
feature_columns += [
VarLenSparseFeat('neg_hist_item', maxlen=4, vocabulary_size=3 + 1, embedding_dim=8, embedding_name='item',
length_name="seq_length"),
VarLenSparseFeat('neg_hist_item_gender', maxlen=4, vocabulary_size=3 + 1, embedding_dim=4,
embedding_name='item_gender', length_name="seq_length")]
x = {name: feature_dict[name] for name in get_feature_names(feature_columns)}
y = [1, 0, 1]
return x, y, feature_columns, behavior_feature_list
if __name__ == "__main__":
if tf.__version__ >= '2.0.0':
tf.compat.v1.disable_eager_execution()
x, y, feature_columns, behavior_feature_list = get_xy_fd(use_neg=True)
model = DIEN(feature_columns, behavior_feature_list,
dnn_hidden_units=[4, 4, 4], dnn_dropout=0.6, gru_type="AUGRU", use_negsampling=True)
model.compile('adam', 'binary_crossentropy',
metrics=['binary_crossentropy'])
history = model.fit(x, y, verbose=1, epochs=10, validation_split=0.5)
| 47.225806 | 118 | 0.613046 | import numpy as np
import tensorflow as tf
from deepctr.models import DIEN
from deepctr.inputs import SparseFeat, DenseFeat, VarLenSparseFeat, get_feature_names
def get_xy_fd(use_neg=False, hash_flag=False):
feature_columns = [SparseFeat('user', 3, embedding_dim=10, use_hash=hash_flag),
SparseFeat('gender', 2, embedding_dim=4, use_hash=hash_flag),
SparseFeat('item', 3 + 1, embedding_dim=8, use_hash=hash_flag),
SparseFeat('item_gender', 2 + 1, embedding_dim=4, use_hash=hash_flag),
DenseFeat('score', 1)]
feature_columns += [
VarLenSparseFeat('hist_item', maxlen=4, vocabulary_size=3 + 1, embedding_dim=8, embedding_name='item',
length_name="seq_length"),
VarLenSparseFeat('hist_item_gender', maxlen=4, vocabulary_size=3 + 1, embedding_dim=4,
embedding_name='item_gender', length_name="seq_length")]
behavior_feature_list = ["item", "item_gender"]
uid = np.array([0, 1, 2])
ugender = np.array([0, 1, 0])
iid = np.array([1, 2, 3])
igender = np.array([1, 2, 1])
score = np.array([0.1, 0.2, 0.3])
hist_iid = np.array([[1, 2, 3, 0], [1, 2, 3, 0], [1, 2, 0, 0]])
hist_igender = np.array([[1, 1, 2, 0], [2, 1, 1, 0], [2, 1, 0, 0]])
behavior_length = np.array([3, 3, 2])
feature_dict = {'user': uid, 'gender': ugender, 'item': iid, 'item_gender': igender,
'hist_item': hist_iid, 'hist_item_gender': hist_igender,
'score': score, "seq_length": behavior_length}
if use_neg:
feature_dict['neg_hist_item'] = np.array([[1, 2, 3, 0], [1, 2, 3, 0], [1, 2, 0, 0]])
feature_dict['neg_hist_item_gender'] = np.array([[1, 1, 2, 0], [2, 1, 1, 0], [2, 1, 0, 0]])
feature_columns += [
VarLenSparseFeat('neg_hist_item', maxlen=4, vocabulary_size=3 + 1, embedding_dim=8, embedding_name='item',
length_name="seq_length"),
VarLenSparseFeat('neg_hist_item_gender', maxlen=4, vocabulary_size=3 + 1, embedding_dim=4,
embedding_name='item_gender', length_name="seq_length")]
x = {name: feature_dict[name] for name in get_feature_names(feature_columns)}
y = [1, 0, 1]
return x, y, feature_columns, behavior_feature_list
if __name__ == "__main__":
if tf.__version__ >= '2.0.0':
tf.compat.v1.disable_eager_execution()
x, y, feature_columns, behavior_feature_list = get_xy_fd(use_neg=True)
model = DIEN(feature_columns, behavior_feature_list,
dnn_hidden_units=[4, 4, 4], dnn_dropout=0.6, gru_type="AUGRU", use_negsampling=True)
model.compile('adam', 'binary_crossentropy',
metrics=['binary_crossentropy'])
history = model.fit(x, y, verbose=1, epochs=10, validation_split=0.5)
| true | true |
f7f8ccc7278d89e43fc6896c7da7c83e810a950c | 8,847 | py | Python | summarizer/model_processors.py | ColdTeapot273K/bert-extractive-summarizer | 3301f093534a3a360f496361c697f1b882e05315 | [
"MIT"
] | 2 | 2021-01-15T08:38:11.000Z | 2021-07-22T06:01:10.000Z | summarizer/model_processors.py | Nikoschenk/bert-extractive-summarizer | 19c4b5a5790294bbbc5a26e8248655705710ff14 | [
"MIT"
] | null | null | null | summarizer/model_processors.py | Nikoschenk/bert-extractive-summarizer | 19c4b5a5790294bbbc5a26e8248655705710ff14 | [
"MIT"
] | null | null | null | from summarizer.bert_parent import BertParent
from summarizer.cluster_features import ClusterFeatures
from summarizer.sentence_handler import SentenceHandler
from typing import List
from abc import abstractmethod
import numpy as np
from transformers import *
class ModelProcessor(object):
def __init__(
self,
model: str = 'bert-large-uncased',
custom_model: PreTrainedModel = None,
custom_tokenizer: PreTrainedTokenizer = None,
hidden: int = -2,
reduce_option: str = 'mean',
sentence_handler: SentenceHandler = SentenceHandler(),
random_state: int = 12345
):
"""
This is the parent Bert Summarizer model. New methods should implement this class
:param model: This parameter is associated with the inherit string parameters from the transformers library.
:param custom_model: If you have a pre-trained model, you can add the model class here.
:param custom_tokenizer: If you have a custom tokenizer, you can add the tokenizer here.
:param hidden: This signifies which layer of the BERT model you would like to use as embeddings.
:param reduce_option: Given the output of the bert model, this param determines how you want to reduce results.
:param sentence_handler: The handler to process sentences. If want to use coreference, instantiate and pass CoreferenceHandler instance
:param random_state: The random state to reproduce summarizations.
"""
np.random.seed(random_state)
self.model = BertParent(model, custom_model, custom_tokenizer)
self.hidden = hidden
self.reduce_option = reduce_option
self.sentence_handler = sentence_handler
self.random_state = random_state
def process_content_sentences(self, body: str, min_length:int = 40, max_length: int = 600) -> List[str]:
"""
Processes the content sentences with neural coreference.
:param body: The raw string body to process
:param min_length: Minimum length that the sentences must be
:param max_length: Max length that the sentences mus fall under
:return: Returns a list of sentences with coreference applied.
"""
doc = self.nlp(body)._.coref_resolved
doc = self.nlp(doc)
return [c.string.strip() for c in doc.sents if max_length > len(c.string.strip()) > min_length]
@abstractmethod
def run_clusters(
self,
content: List[str],
ratio:float = 0.2,
algorithm: str = 'kmeans',
use_first: bool = True
) -> List[str]:
"""
Classes must implement this to run the clusters.
"""
raise NotImplementedError("Must Implement run_clusters")
def run(
self,
body: str,
ratio: float = 0.2,
min_length: int = 40,
max_length: int = 600,
use_first: bool = True,
algorithm: str ='kmeans'
) -> str:
"""
Preprocesses the sentences, runs the clusters to find the centroids, then combines the sentences.
:param body: The raw string body to process
:param ratio: Ratio of sentences to use
:param min_length: Minimum length of sentence candidates to utilize for the summary.
:param max_length: Maximum length of sentence candidates to utilize for the summary
:param use_first: Whether or not to use the first sentence
:param algorithm: Which clustering algorithm to use. (kmeans, gmm)
:return: A summary sentence
"""
sentences = self.sentence_handler(body, min_length, max_length)
if sentences:
sentences = self.run_clusters(sentences, ratio, algorithm, use_first)
return ' '.join(sentences)
def __call__(
self,
body: str,
ratio: float = 0.2,
min_length: int = 40,
max_length: int = 600,
use_first: bool = True,
algorithm: str = 'kmeans'
) -> str:
"""
(utility that wraps around the run function)
Preprocesses the sentences, runs the clusters to find the centroids, then combines the sentences.
:param body: The raw string body to process
:param ratio: Ratio of sentences to use
:param min_length: Minimum length of sentence candidates to utilize for the summary.
:param max_length: Maximum length of sentence candidates to utilize for the summary
:param use_first: Whether or not to use the first sentence
:param algorithm: Which clustering algorithm to use. (kmeans, gmm)
:return: A summary sentence
"""
return self.run(body, ratio, min_length, max_length, algorithm=algorithm, use_first=use_first)
class SingleModel(ModelProcessor):
"""
Deprecated for naming sake.
"""
def __init__(
self,
model='bert-large-uncased',
custom_model: PreTrainedModel = None,
custom_tokenizer: PreTrainedTokenizer = None,
hidden: int=-2,
reduce_option: str = 'mean',
sentence_handler: SentenceHandler = SentenceHandler(),
random_state: int=12345
):
super(SingleModel, self).__init__(
model=model, custom_model=custom_model, custom_tokenizer=custom_tokenizer,
hidden=hidden, reduce_option=reduce_option,
sentence_handler=sentence_handler, random_state=random_state
)
def run_clusters(self, content: List[str], ratio=0.2, algorithm='kmeans', use_first: bool= True) -> List[str]:
hidden = self.model(content, self.hidden, self.reduce_option)
hidden_args = ClusterFeatures(hidden, algorithm, random_state=self.random_state).cluster(ratio)
if use_first:
if hidden_args[0] != 0:
hidden_args.insert(0,0)
return [content[j] for j in hidden_args]
class Summarizer(SingleModel):
def __init__(
self,
model: str = 'bert-large-uncased',
custom_model: PreTrainedModel = None,
custom_tokenizer: PreTrainedTokenizer = None,
hidden: int = -2,
reduce_option: str = 'mean',
sentence_handler: SentenceHandler = SentenceHandler(),
random_state: int = 12345
):
"""
This is the main Bert Summarizer class.
:param model: This parameter is associated with the inherit string parameters from the transformers library.
:param custom_model: If you have a pre-trained model, you can add the model class here.
:param custom_tokenizer: If you have a custom tokenizer, you can add the tokenizer here.
:param hidden: This signifies which layer of the BERT model you would like to use as embeddings.
:param reduce_option: Given the output of the bert model, this param determines how you want to reduce results.
:param greedyness: associated with the neuralcoref library. Determines how greedy coref should be.
:param language: Which language to use for training.
:param random_state: The random state to reproduce summarizations.
"""
super(Summarizer, self).__init__(
model, custom_model, custom_tokenizer, hidden, reduce_option, sentence_handler, random_state
)
class TransformerSummarizer(SingleModel):
MODEL_DICT = {
'Bert': (BertModel, BertTokenizer),
'OpenAIGPT': (OpenAIGPTModel, OpenAIGPTTokenizer),
'GPT2': (GPT2Model, GPT2Tokenizer),
'CTRL': (CTRLModel, CTRLTokenizer),
'TransfoXL': (TransfoXLModel, TransfoXLTokenizer),
'XLNet': (XLNetModel, XLNetTokenizer),
'XLM': (XLMModel, XLMTokenizer),
'DistilBert': (DistilBertModel, DistilBertTokenizer),
}
def __init__(
self,
transformer_type: str = 'Bert',
transformer_model_key: str = 'bert-base-uncased',
transformer_tokenizer_key: str = None,
hidden: int = -2,
reduce_option: str = 'mean',
sentence_handler: SentenceHandler = SentenceHandler(),
random_state: int = 12345
):
try:
self.MODEL_DICT['Roberta'] = (RobertaModel, RobertaTokenizer)
self.MODEL_DICT['Albert'] = (AlbertModel, AlbertTokenizer)
self.MODEL_DICT['Camembert'] = (CamembertModel, CamembertTokenizer)
except Exception as e:
pass # older transformer version
model_clz, tokenizer_clz = self.MODEL_DICT[transformer_type]
model = model_clz.from_pretrained(transformer_model_key, output_hidden_states=True)
tokenizer = tokenizer_clz.from_pretrained(
transformer_tokenizer_key if transformer_tokenizer_key is not None else transformer_model_key
)
super().__init__(
None, model, tokenizer, hidden, reduce_option, sentence_handler, random_state
)
| 40.582569 | 143 | 0.663502 | from summarizer.bert_parent import BertParent
from summarizer.cluster_features import ClusterFeatures
from summarizer.sentence_handler import SentenceHandler
from typing import List
from abc import abstractmethod
import numpy as np
from transformers import *
class ModelProcessor(object):
def __init__(
self,
model: str = 'bert-large-uncased',
custom_model: PreTrainedModel = None,
custom_tokenizer: PreTrainedTokenizer = None,
hidden: int = -2,
reduce_option: str = 'mean',
sentence_handler: SentenceHandler = SentenceHandler(),
random_state: int = 12345
):
np.random.seed(random_state)
self.model = BertParent(model, custom_model, custom_tokenizer)
self.hidden = hidden
self.reduce_option = reduce_option
self.sentence_handler = sentence_handler
self.random_state = random_state
def process_content_sentences(self, body: str, min_length:int = 40, max_length: int = 600) -> List[str]:
doc = self.nlp(body)._.coref_resolved
doc = self.nlp(doc)
return [c.string.strip() for c in doc.sents if max_length > len(c.string.strip()) > min_length]
@abstractmethod
def run_clusters(
self,
content: List[str],
ratio:float = 0.2,
algorithm: str = 'kmeans',
use_first: bool = True
) -> List[str]:
raise NotImplementedError("Must Implement run_clusters")
def run(
self,
body: str,
ratio: float = 0.2,
min_length: int = 40,
max_length: int = 600,
use_first: bool = True,
algorithm: str ='kmeans'
) -> str:
sentences = self.sentence_handler(body, min_length, max_length)
if sentences:
sentences = self.run_clusters(sentences, ratio, algorithm, use_first)
return ' '.join(sentences)
def __call__(
self,
body: str,
ratio: float = 0.2,
min_length: int = 40,
max_length: int = 600,
use_first: bool = True,
algorithm: str = 'kmeans'
) -> str:
return self.run(body, ratio, min_length, max_length, algorithm=algorithm, use_first=use_first)
class SingleModel(ModelProcessor):
def __init__(
self,
model='bert-large-uncased',
custom_model: PreTrainedModel = None,
custom_tokenizer: PreTrainedTokenizer = None,
hidden: int=-2,
reduce_option: str = 'mean',
sentence_handler: SentenceHandler = SentenceHandler(),
random_state: int=12345
):
super(SingleModel, self).__init__(
model=model, custom_model=custom_model, custom_tokenizer=custom_tokenizer,
hidden=hidden, reduce_option=reduce_option,
sentence_handler=sentence_handler, random_state=random_state
)
def run_clusters(self, content: List[str], ratio=0.2, algorithm='kmeans', use_first: bool= True) -> List[str]:
hidden = self.model(content, self.hidden, self.reduce_option)
hidden_args = ClusterFeatures(hidden, algorithm, random_state=self.random_state).cluster(ratio)
if use_first:
if hidden_args[0] != 0:
hidden_args.insert(0,0)
return [content[j] for j in hidden_args]
class Summarizer(SingleModel):
def __init__(
self,
model: str = 'bert-large-uncased',
custom_model: PreTrainedModel = None,
custom_tokenizer: PreTrainedTokenizer = None,
hidden: int = -2,
reduce_option: str = 'mean',
sentence_handler: SentenceHandler = SentenceHandler(),
random_state: int = 12345
):
super(Summarizer, self).__init__(
model, custom_model, custom_tokenizer, hidden, reduce_option, sentence_handler, random_state
)
class TransformerSummarizer(SingleModel):
MODEL_DICT = {
'Bert': (BertModel, BertTokenizer),
'OpenAIGPT': (OpenAIGPTModel, OpenAIGPTTokenizer),
'GPT2': (GPT2Model, GPT2Tokenizer),
'CTRL': (CTRLModel, CTRLTokenizer),
'TransfoXL': (TransfoXLModel, TransfoXLTokenizer),
'XLNet': (XLNetModel, XLNetTokenizer),
'XLM': (XLMModel, XLMTokenizer),
'DistilBert': (DistilBertModel, DistilBertTokenizer),
}
def __init__(
self,
transformer_type: str = 'Bert',
transformer_model_key: str = 'bert-base-uncased',
transformer_tokenizer_key: str = None,
hidden: int = -2,
reduce_option: str = 'mean',
sentence_handler: SentenceHandler = SentenceHandler(),
random_state: int = 12345
):
try:
self.MODEL_DICT['Roberta'] = (RobertaModel, RobertaTokenizer)
self.MODEL_DICT['Albert'] = (AlbertModel, AlbertTokenizer)
self.MODEL_DICT['Camembert'] = (CamembertModel, CamembertTokenizer)
except Exception as e:
pass
model_clz, tokenizer_clz = self.MODEL_DICT[transformer_type]
model = model_clz.from_pretrained(transformer_model_key, output_hidden_states=True)
tokenizer = tokenizer_clz.from_pretrained(
transformer_tokenizer_key if transformer_tokenizer_key is not None else transformer_model_key
)
super().__init__(
None, model, tokenizer, hidden, reduce_option, sentence_handler, random_state
)
| true | true |
f7f8cd0ad60d911caa71b3d94c5c5fdb28dafea6 | 540 | py | Python | OpenGLWrapper_JE/venv/Lib/site-packages/OpenGL/raw/GLES2/EXT/conservative_depth.py | JE-Chen/je_old_repo | a8b2f1ac2eec25758bd15b71c64b59b27e0bcda5 | [
"MIT"
] | null | null | null | OpenGLWrapper_JE/venv/Lib/site-packages/OpenGL/raw/GLES2/EXT/conservative_depth.py | JE-Chen/je_old_repo | a8b2f1ac2eec25758bd15b71c64b59b27e0bcda5 | [
"MIT"
] | null | null | null | OpenGLWrapper_JE/venv/Lib/site-packages/OpenGL/raw/GLES2/EXT/conservative_depth.py | JE-Chen/je_old_repo | a8b2f1ac2eec25758bd15b71c64b59b27e0bcda5 | [
"MIT"
] | null | null | null | '''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GLES2 import _types as _cs
# End users want this...
from OpenGL.raw.GLES2._types import *
from OpenGL.raw.GLES2 import _errors
from OpenGL.constant import Constant as _C
import ctypes
_EXTENSION_NAME = 'GLES2_EXT_conservative_depth'
def _f( function ):
return _p.createFunction( function,_p.PLATFORM.GLES2,'GLES2_EXT_conservative_depth',error_checker=_errors._error_checker)
| 33.75 | 126 | 0.77963 | from OpenGL import platform as _p, arrays
from OpenGL.raw.GLES2 import _types as _cs
from OpenGL.raw.GLES2._types import *
from OpenGL.raw.GLES2 import _errors
from OpenGL.constant import Constant as _C
import ctypes
_EXTENSION_NAME = 'GLES2_EXT_conservative_depth'
def _f( function ):
return _p.createFunction( function,_p.PLATFORM.GLES2,'GLES2_EXT_conservative_depth',error_checker=_errors._error_checker)
| true | true |
f7f8cdbe1b2d15e1b6a3b75394debfe18cb51538 | 164 | py | Python | biggestnumber.py | jaejun1679-cmis/jaejun1679-cmis-cs2 | 3098c276e7c2bad692ab88682c694efd936ae18f | [
"CC0-1.0"
] | null | null | null | biggestnumber.py | jaejun1679-cmis/jaejun1679-cmis-cs2 | 3098c276e7c2bad692ab88682c694efd936ae18f | [
"CC0-1.0"
] | null | null | null | biggestnumber.py | jaejun1679-cmis/jaejun1679-cmis-cs2 | 3098c276e7c2bad692ab88682c694efd936ae18f | [
"CC0-1.0"
] | null | null | null | import time
import math
def findbignumber(bignumber=0):
number = raw_input("Insert a number: ")
if number == "":
return number
else:
| 16.4 | 43 | 0.597561 | import time
import math
def findbignumber(bignumber=0):
number = raw_input("Insert a number: ")
if number == "":
return number
else:
| false | true |
f7f8cea08ee59a4cf933b319d4f8d0ca77fc4635 | 852 | py | Python | setup.py | aino/django-superuser | 637abd471219183c6716bd4fadb1bbbf40940032 | [
"0BSD"
] | null | null | null | setup.py | aino/django-superuser | 637abd471219183c6716bd4fadb1bbbf40940032 | [
"0BSD"
] | null | null | null | setup.py | aino/django-superuser | 637abd471219183c6716bd4fadb1bbbf40940032 | [
"0BSD"
] | null | null | null | from setuptools import setup
setup(
name='django-superuser',
version='0.2.3',
description='Middleware that gives you super powers.',
long_description=open('README.rst').read(),
long_description_content_type='text/markdown',
author='Mikko Hellsing',
author_email='mikko@sumusm.se',
url='http://github.com/sorl/django-superuser',
packages=['superuser'],
include_package_data=True,
zip_safe=False,
license='ICS',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.7',
'Framework :: Django',
],
)
| 30.428571 | 58 | 0.637324 | from setuptools import setup
setup(
name='django-superuser',
version='0.2.3',
description='Middleware that gives you super powers.',
long_description=open('README.rst').read(),
long_description_content_type='text/markdown',
author='Mikko Hellsing',
author_email='mikko@sumusm.se',
url='http://github.com/sorl/django-superuser',
packages=['superuser'],
include_package_data=True,
zip_safe=False,
license='ICS',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.7',
'Framework :: Django',
],
)
| true | true |
f7f8cebe1ddccf1c61244432e5bfecf174f95ccf | 2,493 | py | Python | quotations/views.py | jessamynsmith/socialjusticebingo | 91ea2cae4250db7f6023cde04ae4848aec59449c | [
"MIT"
] | null | null | null | quotations/views.py | jessamynsmith/socialjusticebingo | 91ea2cae4250db7f6023cde04ae4848aec59449c | [
"MIT"
] | 3 | 2020-06-05T18:41:44.000Z | 2021-06-10T20:38:30.000Z | quotations/views.py | jessamynsmith/socialjusticebingo | 91ea2cae4250db7f6023cde04ae4848aec59449c | [
"MIT"
] | null | null | null | from django.conf import settings
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from rest_framework import viewsets
from quotations import models as quotation_models, serializers
from libs import query_set
def _search_quotations(search_terms):
quotation_query = Q()
author_query = Q()
for search_term in search_terms:
quotation_query = quotation_query & Q(text__icontains=search_term)
author_query = author_query & Q(author__name__icontains=search_term)
quotations = quotation_models.Quotation.objects.filter(quotation_query | author_query)
return quotations
class QuotationViewSet(viewsets.ModelViewSet):
serializer_class = serializers.QuotationSerializer
def get_queryset(self):
quotations = _search_quotations(self.request.GET.getlist('search', ''))
if self.request.GET.get('random', False):
quotations = query_set.get_random(quotations)
return quotations
def redirect_to_random(request):
quotations = query_set.get_random(quotation_models.Quotation.objects.all())
return redirect(quotations[0])
def list_quotations(request):
search_text = request.GET.get('search_text', '').strip()
quotations = _search_quotations(search_text.split())
paginator = Paginator(quotations, settings.MAX_PER_PAGE)
page = request.GET.get('page')
try:
quotations = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
quotations = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
quotations = paginator.page(paginator.num_pages)
return render_to_response('quotations/show.html',
{'quotations': quotations,
'pages': [i for i in range(1, paginator.num_pages+1)],
'search_text': search_text},
context_instance=RequestContext(request))
def show_quotation(request, pk):
quotations = quotation_models.Quotation.objects.filter(pk=pk)
return render_to_response('quotations/show.html',
{'quotations': quotations,
'pages': [1]},
context_instance=RequestContext(request))
| 37.772727 | 90 | 0.685921 | from django.conf import settings
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from rest_framework import viewsets
from quotations import models as quotation_models, serializers
from libs import query_set
def _search_quotations(search_terms):
quotation_query = Q()
author_query = Q()
for search_term in search_terms:
quotation_query = quotation_query & Q(text__icontains=search_term)
author_query = author_query & Q(author__name__icontains=search_term)
quotations = quotation_models.Quotation.objects.filter(quotation_query | author_query)
return quotations
class QuotationViewSet(viewsets.ModelViewSet):
serializer_class = serializers.QuotationSerializer
def get_queryset(self):
quotations = _search_quotations(self.request.GET.getlist('search', ''))
if self.request.GET.get('random', False):
quotations = query_set.get_random(quotations)
return quotations
def redirect_to_random(request):
quotations = query_set.get_random(quotation_models.Quotation.objects.all())
return redirect(quotations[0])
def list_quotations(request):
search_text = request.GET.get('search_text', '').strip()
quotations = _search_quotations(search_text.split())
paginator = Paginator(quotations, settings.MAX_PER_PAGE)
page = request.GET.get('page')
try:
quotations = paginator.page(page)
except PageNotAnInteger:
quotations = paginator.page(1)
except EmptyPage:
quotations = paginator.page(paginator.num_pages)
return render_to_response('quotations/show.html',
{'quotations': quotations,
'pages': [i for i in range(1, paginator.num_pages+1)],
'search_text': search_text},
context_instance=RequestContext(request))
def show_quotation(request, pk):
quotations = quotation_models.Quotation.objects.filter(pk=pk)
return render_to_response('quotations/show.html',
{'quotations': quotations,
'pages': [1]},
context_instance=RequestContext(request))
| true | true |
f7f8ceed1b88183aa79f6ab3921f89f7232393e5 | 1,887 | py | Python | scripts/sdk_notify.py | PelionIoT/mbed-cloud-sdk-java | cc99c51db43cc9ae36601f20f20b7d8cd7515432 | [
"Apache-2.0"
] | 7 | 2017-12-28T11:19:15.000Z | 2020-03-23T19:15:31.000Z | scripts/sdk_notify.py | PelionIoT/mbed-cloud-sdk-java | cc99c51db43cc9ae36601f20f20b7d8cd7515432 | [
"Apache-2.0"
] | 99 | 2018-01-09T23:56:13.000Z | 2020-11-03T05:20:55.000Z | scripts/sdk_notify.py | PelionIoT/mbed-cloud-sdk-java | cc99c51db43cc9ae36601f20f20b7d8cd7515432 | [
"Apache-2.0"
] | 5 | 2018-08-02T06:29:18.000Z | 2019-10-23T11:43:59.000Z | #!/usr/bin/python
import sdk_common
import slackclient
# Block in charge of notifying of a new release
class ReleaseNotifier(sdk_common.BuildStep):
def __init__(self, logger=None):
super(ReleaseNotifier, self).__init__('Release notification', logger)
self.token = self.common_config.get_config().get_slack_token()
self.channel = self.common_config.get_config().get_slack_channel()
self.version = self.common_config.get_config().get_version()
self.should_notify_a_new_release = self.common_config.get_config().is_for_release() and not self.common_config.get_config().is_from_private()
self.message = ":checkered_flag: New version of :java: Java SDK released: *{version}*"
def execute(self):
self.print_title()
try:
if self.should_notify_a_new_release:
if not self.version:
raise Exception("The version is missing")
if not self.token or not self.channel:
self.log_warning(
"Slack token or channel is not specified and therefore, no notification will be sent")
return True
self.log_info("Announcing release [%s] on channel %s" % (str(self.version), str(self.channel)))
payload = self.message.format(version=str(self.version))
sc = slackclient.SlackClient(self.token)
sc.api_call('chat.postMessage',
channel=str(self.channel),
text=payload, )
else:
self.log_info("This is not a new release")
except:
self.log_error('Failed to notify of a new release')
return False
self.log_info("Done.")
return True
def check_if_artifactory_is_accessible(self):
return self.ping_host(self.host)
| 44.928571 | 149 | 0.619502 |
import sdk_common
import slackclient
class ReleaseNotifier(sdk_common.BuildStep):
def __init__(self, logger=None):
super(ReleaseNotifier, self).__init__('Release notification', logger)
self.token = self.common_config.get_config().get_slack_token()
self.channel = self.common_config.get_config().get_slack_channel()
self.version = self.common_config.get_config().get_version()
self.should_notify_a_new_release = self.common_config.get_config().is_for_release() and not self.common_config.get_config().is_from_private()
self.message = ":checkered_flag: New version of :java: Java SDK released: *{version}*"
def execute(self):
self.print_title()
try:
if self.should_notify_a_new_release:
if not self.version:
raise Exception("The version is missing")
if not self.token or not self.channel:
self.log_warning(
"Slack token or channel is not specified and therefore, no notification will be sent")
return True
self.log_info("Announcing release [%s] on channel %s" % (str(self.version), str(self.channel)))
payload = self.message.format(version=str(self.version))
sc = slackclient.SlackClient(self.token)
sc.api_call('chat.postMessage',
channel=str(self.channel),
text=payload, )
else:
self.log_info("This is not a new release")
except:
self.log_error('Failed to notify of a new release')
return False
self.log_info("Done.")
return True
def check_if_artifactory_is_accessible(self):
return self.ping_host(self.host)
| true | true |
f7f8cf3814442b23f4bf05fe9e24a0a981ce4c84 | 256 | py | Python | halolib/const.py | yoramk2/halolib | c05bc9f9c37d09700c5a42dcd3b9a74c0c5c0c29 | [
"MIT"
] | 2 | 2020-07-22T13:28:47.000Z | 2021-02-08T04:38:06.000Z | halolib/const.py | yoramk2/halolib | c05bc9f9c37d09700c5a42dcd3b9a74c0c5c0c29 | [
"MIT"
] | 2 | 2021-06-10T20:59:03.000Z | 2021-11-15T17:47:59.000Z | halolib/const.py | yoramk2/halolib | c05bc9f9c37d09700c5a42dcd3b9a74c0c5c0c29 | [
"MIT"
] | 1 | 2021-02-08T04:38:09.000Z | 2021-02-08T04:38:09.000Z | from __future__ import print_function
import logging
from enum import Enum
logger = logging.getLogger(__name__)
class HTTPChoice(Enum): # A subclass of Enum
get = "GET"
post = "POST"
put = "PUT"
delete = "DELETE"
patch = "PATCH"
| 15.058824 | 45 | 0.667969 | from __future__ import print_function
import logging
from enum import Enum
logger = logging.getLogger(__name__)
class HTTPChoice(Enum):
get = "GET"
post = "POST"
put = "PUT"
delete = "DELETE"
patch = "PATCH"
| true | true |
f7f8cf6586efe758b96d1abc920ca344d5a5763c | 11,633 | py | Python | onmt/utils/loss.py | sajastu/abs-summarization | 9d4b35b457cfd617965ed1fab68c173c98333439 | [
"MIT"
] | 27 | 2019-06-11T07:43:13.000Z | 2021-12-03T02:34:35.000Z | onmt/utils/loss.py | sajastu/abs-summarization | 9d4b35b457cfd617965ed1fab68c173c98333439 | [
"MIT"
] | 29 | 2019-07-18T10:21:57.000Z | 2019-10-24T11:41:59.000Z | onmt/utils/loss.py | sajastu/abs-summarization | 9d4b35b457cfd617965ed1fab68c173c98333439 | [
"MIT"
] | 11 | 2019-06-11T07:43:14.000Z | 2021-01-03T04:34:18.000Z | """
This includes: LossComputeBase and the standard NMTLossCompute, and
sharded loss compute stuff.
"""
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
import onmt
from onmt.modules.sparse_losses import SparsemaxLoss
from onmt.modules.sparse_activations import LogSparsemax
def build_loss_compute(model, tgt_field, opt, train=True):
"""
Returns a LossCompute subclass which wraps around an nn.Module subclass
(such as nn.NLLLoss) which defines the loss criterion. The LossCompute
object allows this loss to be computed in shards and passes the relevant
data to a Statistics object which handles training/validation logging.
Currently, the NMTLossCompute class handles all loss computation except
for when using a copy mechanism.
"""
device = torch.device("cuda" if onmt.utils.misc.use_gpu(opt) else "cpu")
padding_idx = tgt_field.vocab.stoi[tgt_field.pad_token]
unk_idx = tgt_field.vocab.stoi[tgt_field.unk_token]
if opt.copy_attn:
criterion = onmt.modules.CopyGeneratorLoss(
len(tgt_field.vocab), opt.copy_attn_force,
unk_index=unk_idx, ignore_index=padding_idx
)
elif opt.label_smoothing > 0 and train:
criterion = LabelSmoothingLoss(
opt.label_smoothing, len(tgt_field.vocab), ignore_index=padding_idx
)
elif isinstance(model.generator[-1], LogSparsemax):
criterion = SparsemaxLoss(ignore_index=padding_idx, reduction='sum')
else:
criterion = nn.NLLLoss(ignore_index=padding_idx, reduction='sum')
# if the loss function operates on vectors of raw logits instead of
# probabilities, only the first part of the generator needs to be
# passed to the NMTLossCompute. At the moment, the only supported
# loss function of this kind is the sparsemax loss.
use_raw_logits = isinstance(criterion, SparsemaxLoss)
loss_gen = model.generator[0] if use_raw_logits else model.generator
if opt.copy_attn:
compute = onmt.modules.CopyGeneratorLossCompute(
criterion, loss_gen, tgt_field.vocab, opt.copy_loss_by_seqlength
)
else:
compute = NMTLossCompute(criterion, loss_gen)
compute.to(device)
return compute
class LossComputeBase(nn.Module):
"""
Class for managing efficient loss computation. Handles
sharding next step predictions and accumulating multiple
loss computations
Users can implement their own loss computation strategy by making
subclass of this one. Users need to implement the _compute_loss()
and make_shard_state() methods.
Args:
generator (:obj:`nn.Module`) :
module that maps the output of the decoder to a
distribution over the target vocabulary.
tgt_vocab (:obj:`Vocab`) :
torchtext vocab object representing the target output
normalzation (str): normalize by "sents" or "tokens"
"""
def __init__(self, criterion, generator):
super(LossComputeBase, self).__init__()
self.criterion = criterion
self.generator = generator
@property
def padding_idx(self):
return self.criterion.ignore_index
def _make_shard_state(self, batch, output, range_, attns=None):
"""
Make shard state dictionary for shards() to return iterable
shards for efficient loss computation. Subclass must define
this method to match its own _compute_loss() interface.
Args:
batch: the current batch.
output: the predict output from the model.
range_: the range of examples for computing, the whole
batch or a trunc of it?
attns: the attns dictionary returned from the model.
"""
return NotImplementedError
def _compute_loss(self, batch, output, target, **kwargs):
"""
Compute the loss. Subclass must define this method.
Args:
batch: the current batch.
output: the predict output from the model.
target: the validate target to compare output with.
**kwargs(optional): additional info for computing loss.
"""
return NotImplementedError
def __call__(self,
batch,
output,
attns,
normalization=1.0,
shard_size=0,
trunc_start=0,
trunc_size=None):
"""Compute the forward loss, possibly in shards in which case this
method also runs the backward pass and returns ``None`` as the loss
value.
Also supports truncated BPTT for long sequences by taking a
range in the decoder output sequence to back propagate in.
Range is from `(trunc_start, trunc_start + trunc_size)`.
Note sharding is an exact efficiency trick to relieve memory
required for the generation buffers. Truncation is an
approximate efficiency trick to relieve the memory required
in the RNN buffers.
Args:
batch (batch) : batch of labeled examples
output (:obj:`FloatTensor`) :
output of decoder model `[tgt_len x batch x hidden]`
attns (dict) : dictionary of attention distributions
`[tgt_len x batch x src_len]`
normalization: Optional normalization factor.
shard_size (int) : maximum number of examples in a shard
trunc_start (int) : starting position of truncation window
trunc_size (int) : length of truncation window
Returns:
A tuple with the loss and a :obj:`onmt.utils.Statistics` instance.
"""
if trunc_size is None:
trunc_size = batch.tgt.size(0) - trunc_start
trunc_range = (trunc_start, trunc_start + trunc_size)
shard_state = self._make_shard_state(batch, output, trunc_range, attns)
if shard_size == 0:
loss, stats = self._compute_loss(batch, **shard_state)
return loss / float(normalization), stats
batch_stats = onmt.utils.Statistics()
for shard in shards(shard_state, shard_size):
loss, stats = self._compute_loss(batch, **shard)
loss.div(float(normalization)).backward()
batch_stats.update(stats)
return None, batch_stats
def _stats(self, loss, scores, target):
"""
Args:
loss (:obj:`FloatTensor`): the loss computed by the loss criterion.
scores (:obj:`FloatTensor`): a score for each possible output
target (:obj:`FloatTensor`): true targets
Returns:
:obj:`onmt.utils.Statistics` : statistics for this batch.
"""
pred = scores.max(1)[1]
non_padding = target.ne(self.padding_idx)
num_correct = pred.eq(target).masked_select(non_padding).sum().item()
num_non_padding = non_padding.sum().item()
return onmt.utils.Statistics(loss.item(), num_non_padding, num_correct)
def _bottle(self, _v):
return _v.view(-1, _v.size(2))
def _unbottle(self, _v, batch_size):
return _v.view(-1, batch_size, _v.size(1))
class LabelSmoothingLoss(nn.Module):
"""
With label smoothing,
KL-divergence between q_{smoothed ground truth prob.}(w)
and p_{prob. computed by model}(w) is minimized.
"""
def __init__(self, label_smoothing, tgt_vocab_size, ignore_index=-100):
assert 0.0 < label_smoothing <= 1.0
self.ignore_index = ignore_index
super(LabelSmoothingLoss, self).__init__()
smoothing_value = label_smoothing / (tgt_vocab_size - 2)
one_hot = torch.full((tgt_vocab_size,), smoothing_value)
one_hot[self.ignore_index] = 0
self.register_buffer('one_hot', one_hot.unsqueeze(0))
self.confidence = 1.0 - label_smoothing
def forward(self, output, target):
"""
output (FloatTensor): batch_size x n_classes
target (LongTensor): batch_size
"""
model_prob = self.one_hot.repeat(target.size(0), 1)
model_prob.scatter_(1, target.unsqueeze(1), self.confidence)
model_prob.masked_fill_((target == self.ignore_index).unsqueeze(1), 0)
return F.kl_div(output, model_prob, reduction='sum')
class NMTLossCompute(LossComputeBase):
"""
Standard NMT Loss Computation.
"""
def __init__(self, criterion, generator, normalization="sents"):
super(NMTLossCompute, self).__init__(criterion, generator)
def _make_shard_state(self, batch, output, range_, attns=None):
return {
"output": output,
"target": batch.tgt[range_[0] + 1: range_[1], :, 0],
}
def _compute_loss(self, batch, output, target):
bottled_output = self._bottle(output)
scores = self.generator(bottled_output)
gtruth = target.view(-1)
loss = self.criterion(scores, gtruth)
stats = self._stats(loss.clone(), scores, gtruth)
return loss, stats
def filter_shard_state(state, shard_size=None):
for k, v in state.items():
if shard_size is None:
yield k, v
if v is not None:
v_split = []
if isinstance(v, torch.Tensor):
for v_chunk in torch.split(v, shard_size):
v_chunk = v_chunk.data.clone()
v_chunk.requires_grad = v.requires_grad
v_split.append(v_chunk)
yield k, (v, v_split)
def shards(state, shard_size, eval_only=False):
"""
Args:
state: A dictionary which corresponds to the output of
*LossCompute._make_shard_state(). The values for
those keys are Tensor-like or None.
shard_size: The maximum size of the shards yielded by the model.
eval_only: If True, only yield the state, nothing else.
Otherwise, yield shards.
Yields:
Each yielded shard is a dict.
Side effect:
After the last shard, this function does back-propagation.
"""
if eval_only:
yield filter_shard_state(state)
else:
# non_none: the subdict of the state dictionary where the values
# are not None.
non_none = dict(filter_shard_state(state, shard_size))
# Now, the iteration:
# state is a dictionary of sequences of tensor-like but we
# want a sequence of dictionaries of tensors.
# First, unzip the dictionary into a sequence of keys and a
# sequence of tensor-like sequences.
keys, values = zip(*((k, [v_chunk for v_chunk in v_split])
for k, (_, v_split) in non_none.items()))
# Now, yield a dictionary for each shard. The keys are always
# the same. values is a sequence of length #keys where each
# element is a sequence of length #shards. We want to iterate
# over the shards, not over the keys: therefore, the values need
# to be re-zipped by shard and then each shard can be paired
# with the keys.
for shard_tensors in zip(*values):
yield dict(zip(keys, shard_tensors))
# Assumed backprop'd
variables = []
for k, (v, v_split) in non_none.items():
if isinstance(v, torch.Tensor) and state[k].requires_grad:
variables.extend(zip(torch.split(state[k], shard_size),
[v_chunk.grad for v_chunk in v_split]))
inputs, grads = zip(*variables)
torch.autograd.backward(inputs, grads)
| 38.140984 | 79 | 0.641881 | from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
import onmt
from onmt.modules.sparse_losses import SparsemaxLoss
from onmt.modules.sparse_activations import LogSparsemax
def build_loss_compute(model, tgt_field, opt, train=True):
device = torch.device("cuda" if onmt.utils.misc.use_gpu(opt) else "cpu")
padding_idx = tgt_field.vocab.stoi[tgt_field.pad_token]
unk_idx = tgt_field.vocab.stoi[tgt_field.unk_token]
if opt.copy_attn:
criterion = onmt.modules.CopyGeneratorLoss(
len(tgt_field.vocab), opt.copy_attn_force,
unk_index=unk_idx, ignore_index=padding_idx
)
elif opt.label_smoothing > 0 and train:
criterion = LabelSmoothingLoss(
opt.label_smoothing, len(tgt_field.vocab), ignore_index=padding_idx
)
elif isinstance(model.generator[-1], LogSparsemax):
criterion = SparsemaxLoss(ignore_index=padding_idx, reduction='sum')
else:
criterion = nn.NLLLoss(ignore_index=padding_idx, reduction='sum')
use_raw_logits = isinstance(criterion, SparsemaxLoss)
loss_gen = model.generator[0] if use_raw_logits else model.generator
if opt.copy_attn:
compute = onmt.modules.CopyGeneratorLossCompute(
criterion, loss_gen, tgt_field.vocab, opt.copy_loss_by_seqlength
)
else:
compute = NMTLossCompute(criterion, loss_gen)
compute.to(device)
return compute
class LossComputeBase(nn.Module):
def __init__(self, criterion, generator):
super(LossComputeBase, self).__init__()
self.criterion = criterion
self.generator = generator
@property
def padding_idx(self):
return self.criterion.ignore_index
def _make_shard_state(self, batch, output, range_, attns=None):
return NotImplementedError
def _compute_loss(self, batch, output, target, **kwargs):
return NotImplementedError
def __call__(self,
batch,
output,
attns,
normalization=1.0,
shard_size=0,
trunc_start=0,
trunc_size=None):
if trunc_size is None:
trunc_size = batch.tgt.size(0) - trunc_start
trunc_range = (trunc_start, trunc_start + trunc_size)
shard_state = self._make_shard_state(batch, output, trunc_range, attns)
if shard_size == 0:
loss, stats = self._compute_loss(batch, **shard_state)
return loss / float(normalization), stats
batch_stats = onmt.utils.Statistics()
for shard in shards(shard_state, shard_size):
loss, stats = self._compute_loss(batch, **shard)
loss.div(float(normalization)).backward()
batch_stats.update(stats)
return None, batch_stats
def _stats(self, loss, scores, target):
pred = scores.max(1)[1]
non_padding = target.ne(self.padding_idx)
num_correct = pred.eq(target).masked_select(non_padding).sum().item()
num_non_padding = non_padding.sum().item()
return onmt.utils.Statistics(loss.item(), num_non_padding, num_correct)
def _bottle(self, _v):
return _v.view(-1, _v.size(2))
def _unbottle(self, _v, batch_size):
return _v.view(-1, batch_size, _v.size(1))
class LabelSmoothingLoss(nn.Module):
def __init__(self, label_smoothing, tgt_vocab_size, ignore_index=-100):
assert 0.0 < label_smoothing <= 1.0
self.ignore_index = ignore_index
super(LabelSmoothingLoss, self).__init__()
smoothing_value = label_smoothing / (tgt_vocab_size - 2)
one_hot = torch.full((tgt_vocab_size,), smoothing_value)
one_hot[self.ignore_index] = 0
self.register_buffer('one_hot', one_hot.unsqueeze(0))
self.confidence = 1.0 - label_smoothing
def forward(self, output, target):
model_prob = self.one_hot.repeat(target.size(0), 1)
model_prob.scatter_(1, target.unsqueeze(1), self.confidence)
model_prob.masked_fill_((target == self.ignore_index).unsqueeze(1), 0)
return F.kl_div(output, model_prob, reduction='sum')
class NMTLossCompute(LossComputeBase):
def __init__(self, criterion, generator, normalization="sents"):
super(NMTLossCompute, self).__init__(criterion, generator)
def _make_shard_state(self, batch, output, range_, attns=None):
return {
"output": output,
"target": batch.tgt[range_[0] + 1: range_[1], :, 0],
}
def _compute_loss(self, batch, output, target):
bottled_output = self._bottle(output)
scores = self.generator(bottled_output)
gtruth = target.view(-1)
loss = self.criterion(scores, gtruth)
stats = self._stats(loss.clone(), scores, gtruth)
return loss, stats
def filter_shard_state(state, shard_size=None):
for k, v in state.items():
if shard_size is None:
yield k, v
if v is not None:
v_split = []
if isinstance(v, torch.Tensor):
for v_chunk in torch.split(v, shard_size):
v_chunk = v_chunk.data.clone()
v_chunk.requires_grad = v.requires_grad
v_split.append(v_chunk)
yield k, (v, v_split)
def shards(state, shard_size, eval_only=False):
if eval_only:
yield filter_shard_state(state)
else:
non_none = dict(filter_shard_state(state, shard_size))
keys, values = zip(*((k, [v_chunk for v_chunk in v_split])
for k, (_, v_split) in non_none.items()))
for shard_tensors in zip(*values):
yield dict(zip(keys, shard_tensors))
variables = []
for k, (v, v_split) in non_none.items():
if isinstance(v, torch.Tensor) and state[k].requires_grad:
variables.extend(zip(torch.split(state[k], shard_size),
[v_chunk.grad for v_chunk in v_split]))
inputs, grads = zip(*variables)
torch.autograd.backward(inputs, grads)
| true | true |
f7f8d01a0f30ac350a68d924814a77fb331d4563 | 24,698 | py | Python | src/unity/python/turicreate/util/__init__.py | TimothyRHuertas/turicreate | afa00bee56d168190c6f122e14c9fbc6656b4e97 | [
"BSD-3-Clause"
] | 1 | 2018-02-10T12:05:13.000Z | 2018-02-10T12:05:13.000Z | src/unity/python/turicreate/util/__init__.py | TimothyRHuertas/turicreate | afa00bee56d168190c6f122e14c9fbc6656b4e97 | [
"BSD-3-Clause"
] | null | null | null | src/unity/python/turicreate/util/__init__.py | TimothyRHuertas/turicreate | afa00bee56d168190c6f122e14c9fbc6656b4e97 | [
"BSD-3-Clause"
] | 1 | 2020-10-21T17:46:28.000Z | 2020-10-21T17:46:28.000Z | # -*- coding: utf-8 -*-
# Copyright © 2017 Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can
# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from __future__ import print_function as _
from __future__ import division as _
from __future__ import absolute_import as _
# 1st set up logging
import logging
import logging.config
import time as _time
import tempfile as _tempfile
import os as _os
import urllib as _urllib
import re as _re
from zipfile import ZipFile as _ZipFile
import bz2 as _bz2
import tarfile as _tarfile
import itertools as _itertools
import uuid as _uuid
import datetime as _datetime
import sys as _sys
import subprocess as _subprocess
from ..config import get_client_log_location as _get_client_log_location
from .sframe_generation import generate_random_sframe
from .sframe_generation import generate_random_regression_sframe
from .sframe_generation import generate_random_classification_sframe
from .type_checks import _raise_error_if_not_function
from .type_checks import _raise_error_if_not_of_type
from .type_checks import _is_non_string_iterable
from .type_checks import _is_string
try:
import configparser as _ConfigParser
except ImportError:
import ConfigParser as _ConfigParser
def _convert_slashes(path):
"""
Converts all windows-style slashes to unix-style slashes
"""
return path.replace('\\', '/')
def _get_s3_endpoint():
"""
Returns the current S3 Endpoint"
"""
import turicreate
return turicreate.config.get_runtime_config()['TURI_S3_ENDPOINT']
def _get_aws_credentials():
"""
Returns the values stored in the AWS credential environment variables.
Returns the value stored in the AWS_ACCESS_KEY_ID environment variable and
the value stored in the AWS_SECRET_ACCESS_KEY environment variable.
Returns
-------
out : tuple [string]
The first string of the tuple is the value of the AWS_ACCESS_KEY_ID
environment variable. The second string of the tuple is the value of the
AWS_SECRET_ACCESS_KEY environment variable.
Examples
--------
>>> turicreate.aws.get_credentials()
('RBZH792CTQPP7T435BGQ', '7x2hMqplWsLpU/qQCN6xAPKcmWo46TlPJXYTvKcv')
"""
if (not 'AWS_ACCESS_KEY_ID' in _os.environ):
raise KeyError('No access key found. Please set the environment variable AWS_ACCESS_KEY_ID.')
if (not 'AWS_SECRET_ACCESS_KEY' in _os.environ):
raise KeyError('No secret key found. Please set the environment variable AWS_SECRET_ACCESS_KEY.')
return (_os.environ['AWS_ACCESS_KEY_ID'], _os.environ['AWS_SECRET_ACCESS_KEY'])
def _try_inject_s3_credentials(url):
"""
Inject aws credentials into s3 url as s3://[aws_id]:[aws_key]:[bucket/][objectkey]
If s3 url already contains secret key/id pairs, just return as is.
"""
assert url.startswith('s3://')
path = url[5:]
# Check if the path already contains credentials
tokens = path.split(':')
# If there are two ':', its possible that we have already injected credentials
if len(tokens) == 3:
# Edge case: there are exactly two ':'s in the object key which is a false alarm.
# We prevent this by checking that '/' is not in the assumed key and id.
if ('/' not in tokens[0]) and ('/' not in tokens[1]):
return url
# S3 url does not contain secret key/id pair, query the environment variables
(k, v) = _get_aws_credentials()
return 's3://' + k + ':' + v + ':' + path
def _make_internal_url(url):
"""
Process user input url string with proper normalization
For all urls:
Expands ~ to $HOME
For S3 urls:
Returns the s3 URL with credentials filled in using turicreate.aws.get_aws_credential().
For example: "s3://mybucket/foo" -> "s3://$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY:mybucket/foo".
For hdfs urls:
Error if hadoop classpath is not set
For local file urls:
conver slashes for windows sanity
Parameters
----------
string
A URL (as described above).
Raises
------
ValueError
If a bad url is provided.
"""
if not url:
raise ValueError('Invalid url: %s' % url)
from .. import _sys_util
from . import file_util
# Convert Windows paths to Unix-style slashes
url = _convert_slashes(url)
# Try to split the url into (protocol, path).
protocol = file_util.get_protocol(url)
is_local = False
if protocol in ['http', 'https']:
pass
elif protocol == 'hdfs':
if not _sys_util.get_hadoop_class_path():
raise ValueError("HDFS URL is not supported because Hadoop not found. Please make hadoop available from PATH or set the environment variable HADOOP_HOME and try again.")
elif protocol == 's3':
return _try_inject_s3_credentials(url)
elif protocol == '':
is_local = True
elif (protocol == 'local' or protocol == 'remote'):
# local and remote are legacy protocol for separate server process
is_local = True
# This code assumes local and remote are same machine
url = _re.sub(protocol+'://','',url,count=1)
else:
raise ValueError('Invalid url protocol %s. Supported url protocols are: local, s3://, https:// and hdfs://' % protocol)
if is_local:
url = _os.path.abspath(_os.path.expanduser(url))
return url
def _download_dataset(url_str, extract=True, force=False, output_dir="."):
"""Download a remote dataset and extract the contents.
Parameters
----------
url_str : string
The URL to download from
extract : bool
If true, tries to extract compressed file (zip/gz/bz2)
force : bool
If true, forces to retry the download even if the downloaded file already exists.
output_dir : string
The directory to dump the file. Defaults to current directory.
"""
fname = output_dir + "/" + url_str.split("/")[-1]
#download the file from the web
if not _os.path.isfile(fname) or force:
print("Downloading file from:", url_str)
_urllib.urlretrieve(url_str, fname)
if extract and fname[-3:] == "zip":
print("Decompressing zip archive", fname)
_ZipFile(fname).extractall(output_dir)
elif extract and fname[-6:] == ".tar.gz":
print("Decompressing tar.gz archive", fname)
_tarfile.TarFile(fname).extractall(output_dir)
elif extract and fname[-7:] == ".tar.bz2":
print("Decompressing tar.bz2 archive", fname)
_tarfile.TarFile(fname).extractall(output_dir)
elif extract and fname[-3:] == "bz2":
print("Decompressing bz2 archive:", fname)
outfile = open(fname.split(".bz2")[0], "w")
print("Output file:", outfile)
for line in _bz2.BZ2File(fname, "r"):
outfile.write(line)
outfile.close()
else:
print("File is already downloaded.")
def is_directory_archive(path):
"""
Utility function that returns True if the path provided is a directory that has an SFrame or SGraph in it.
SFrames are written to disk as a directory archive, this function identifies if a given directory is an archive
for an SFrame.
Parameters
----------
path : string
Directory to evaluate.
Returns
-------
True if path provided is an archive location, False otherwise
"""
if path is None:
return False
if not _os.path.isdir(path):
return False
ini_path = '/'.join([_convert_slashes(path), 'dir_archive.ini'])
if not _os.path.exists(ini_path):
return False
if _os.path.isfile(ini_path):
return True
return False
def get_archive_type(path):
"""
Returns the contents type for the provided archive path.
Parameters
----------
path : string
Directory to evaluate.
Returns
-------
Returns a string of: sframe, sgraph, raises TypeError for anything else
"""
if not is_directory_archive(path):
raise TypeError('Unable to determine the type of archive at path: %s' % path)
try:
ini_path = '/'.join([_convert_slashes(path), 'dir_archive.ini'])
parser = _ConfigParser.SafeConfigParser()
parser.read(ini_path)
contents = parser.get('metadata', 'contents')
return contents
except Exception as e:
raise TypeError('Unable to determine type of archive for path: %s' % path, e)
_GLOB_RE = _re.compile("""[*?]""")
def _split_path_elements(url):
parts = _os.path.split(url)
m = _GLOB_RE.search(parts[-1])
if m:
return (parts[0], parts[1])
else:
return (url, "")
def crossproduct(d):
"""
Create an SFrame containing the crossproduct of all provided options.
Parameters
----------
d : dict
Each key is the name of an option, and each value is a list
of the possible values for that option.
Returns
-------
out : SFrame
There will be a column for each key in the provided dictionary,
and a row for each unique combination of all values.
Example
-------
settings = {'argument_1':[0, 1],
'argument_2':['a', 'b', 'c']}
print crossproduct(settings)
+------------+------------+
| argument_2 | argument_1 |
+------------+------------+
| a | 0 |
| a | 1 |
| b | 0 |
| b | 1 |
| c | 0 |
| c | 1 |
+------------+------------+
[6 rows x 2 columns]
"""
from .. import SArray
d = [list(zip(list(d.keys()), x)) for x in _itertools.product(*list(d.values()))]
sa = [{k:v for (k,v) in x} for x in d]
return SArray(sa).unpack(column_name_prefix='')
def get_turicreate_object_type(url):
'''
Given url where a Turi Create object is persisted, return the Turi
Create object type: 'model', 'graph', 'sframe', or 'sarray'
'''
from ..connect import main as _glconnect
ret = _glconnect.get_unity().get_turicreate_object_type(_make_internal_url(url))
# to be consistent, we use sgraph instead of graph here
if ret == 'graph':
ret = 'sgraph'
return ret
def _assert_sframe_equal(sf1,
sf2,
check_column_names=True,
check_column_order=True,
check_row_order=True,
float_column_delta=None):
"""
Assert the two SFrames are equal.
The default behavior of this function uses the strictest possible
definition of equality, where all columns must be in the same order, with
the same names and have the same data in the same order. Each of these
stipulations can be relaxed individually and in concert with another, with
the exception of `check_column_order` and `check_column_names`, we must use
one of these to determine which columns to compare with one another.
Parameters
----------
sf1 : SFrame
sf2 : SFrame
check_column_names : bool
If true, assert if the data values in two columns are the same, but
they have different names. If False, column order is used to determine
which columns to compare.
check_column_order : bool
If true, assert if the data values in two columns are the same, but are
not in the same column position (one is the i-th column and the other
is the j-th column, i != j). If False, column names are used to
determine which columns to compare.
check_row_order : bool
If true, assert if all rows in the first SFrame exist in the second
SFrame, but they are not in the same order.
float_column_delta : float
The acceptable delta that two float values can be and still be
considered "equal". When this is None, only exact equality is accepted.
This is the default behavior since columns of all Nones are often of
float type. Applies to all float columns.
"""
from .. import SFrame as _SFrame
if (type(sf1) is not _SFrame) or (type(sf2) is not _SFrame):
raise TypeError("Cannot function on types other than SFrames.")
if not check_column_order and not check_column_names:
raise ValueError("Cannot ignore both column order and column names.")
sf1.__materialize__()
sf2.__materialize__()
if sf1.num_columns() != sf2.num_columns():
raise AssertionError("Number of columns mismatched: " +
str(sf1.num_columns()) + " != " + str(sf2.num_columns()))
s1_names = sf1.column_names()
s2_names = sf2.column_names()
sorted_s1_names = sorted(s1_names)
sorted_s2_names = sorted(s2_names)
if check_column_names:
if (check_column_order and (s1_names != s2_names)) or (sorted_s1_names != sorted_s2_names):
raise AssertionError("SFrame does not have same column names: " +
str(sf1.column_names()) + " != " + str(sf2.column_names()))
if sf1.num_rows() != sf2.num_rows():
raise AssertionError("Number of rows mismatched: " +
str(sf1.num_rows()) + " != " + str(sf2.num_rows()))
if not check_row_order and (sf1.num_rows() > 1):
sf1 = sf1.sort(s1_names)
sf2 = sf2.sort(s2_names)
names_to_check = None
if check_column_names:
names_to_check = list(zip(sorted_s1_names, sorted_s2_names))
else:
names_to_check = list(zip(s1_names, s2_names))
for i in names_to_check:
col1 = sf1[i[0]]
col2 = sf2[i[1]]
if col1.dtype != col2.dtype:
raise AssertionError("Columns " + str(i) + " types mismatched.")
compare_ary = None
if col1.dtype == float and float_column_delta is not None:
dt = float_column_delta
compare_ary = ((col1 > col2-dt) & (col1 < col2+dt))
else:
compare_ary = (sf1[i[0]] == sf2[i[1]])
if not compare_ary.all():
count = 0
for j in compare_ary:
if not j:
first_row = count
break
count += 1
raise AssertionError("Columns " + str(i) +
" are not equal! First differing element is at row " +
str(first_row) + ": " + str((col1[first_row],col2[first_row])))
def _get_temp_file_location():
'''
Returns user specified temporary file location.
The temporary location is specified through:
>>> turicreate.set_runtime_config('TURI_CACHE_FILE_LOCATIONS', ...)
'''
from ..connect import main as _glconnect
unity = _glconnect.get_unity()
cache_dir = _convert_slashes(unity.get_current_cache_file_location())
if not _os.path.exists(cache_dir):
_os.makedirs(cache_dir)
return cache_dir
def _make_temp_directory(prefix):
'''
Generate a temporary directory that would not live beyond the lifetime of
unity_server.
Caller is expected to clean up the temp file as soon as the directory is no
longer needed. But the directory will be cleaned as unity_server restarts
'''
temp_dir = _make_temp_filename(prefix=str(prefix))
_os.makedirs(temp_dir)
return temp_dir
def _make_temp_filename(prefix):
'''
Generate a temporary file that would not live beyond the lifetime of
unity_server.
Caller is expected to clean up the temp file as soon as the file is no
longer needed. But temp files created using this method will be cleaned up
when unity_server restarts
'''
temp_location = _get_temp_file_location()
temp_file_name = '/'.join([temp_location, str(prefix)+str(_uuid.uuid4())])
return temp_file_name
# datetime utilities
_ZERO = _datetime.timedelta(0)
class _UTC(_datetime.tzinfo):
"""
A UTC datetime.tzinfo class modeled after the pytz library. It includes a
__reduce__ method for pickling,
"""
def fromutc(self, dt):
if dt.tzinfo is None:
return self.localize(dt)
return super(_utc.__class__, self).fromutc(dt)
def utcoffset(self, dt):
return _ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return _ZERO
def __reduce__(self):
return _UTC, ()
def __repr__(self):
return "<UTC>"
def __str__(self):
return "UTC"
_utc = _UTC()
def _dt_to_utc_timestamp(t):
if t.tzname() == 'UTC':
return (t - _datetime.datetime(1970, 1, 1, tzinfo=_utc)).total_seconds()
elif not t.tzinfo:
return _time.mktime(t.timetuple())
else:
raise ValueError('Only local time and UTC time is supported')
def _pickle_to_temp_location_or_memory(obj):
'''
If obj can be serialized directly into memory (via cloudpickle) this
will return the serialized bytes.
Otherwise, gl_pickle is attempted and it will then
generates a temporary directory serializes an object into it, returning
the directory name. This directory will not have lifespan greater than
that of unity_server.
'''
from . import cloudpickle as cloudpickle
try:
# try cloudpickle first and see if that works
lambda_str = cloudpickle.dumps(obj)
return lambda_str
except:
pass
# nope. that does not work! lets try again with gl pickle
filename = _make_temp_filename('pickle')
from .. import _gl_pickle
pickler = _gl_pickle.GLPickler(filename)
pickler.dump(obj)
pickler.close()
return filename
def get_module_from_object(obj):
mod_str = obj.__class__.__module__.split('.')[0]
return _sys.modules[mod_str]
def infer_dbapi2_types(cursor, mod_info):
desc = cursor.description
result_set_types = [i[1] for i in desc]
dbapi2_to_python = [ # a type code can match more than one, so ordered by
# preference (loop short-circuits when it finds a match
(mod_info['DATETIME'], _datetime.datetime),
(mod_info['ROWID'],int),
(mod_info['NUMBER'],float),
]
ret_types = []
# Ugly nested loop because the standard only guarantees that a type code
# will compare equal to the module-defined types
for i in result_set_types:
type_found = False
for j in dbapi2_to_python:
if i is None or j[0] is None:
break
elif i == j[0]:
ret_types.append(j[1])
type_found = True
break
if not type_found:
ret_types.append(str)
return ret_types
def pytype_to_printf(in_type):
if in_type == int:
return 'd'
elif in_type == float:
return 'f'
else:
return 's'
def subprocess_exe(exe, args, setup=None, teardown=None,
local_log_prefix=None,
out_log_prefix=None,
environment_variables=None):
"""
Wrapper function to execute an external program.
This function is exception safe, and always catches
the error.
Parameters
----------
exe : str
The command to run
args : list[str]
Arguments to passed to the command
setup : function
Setup function to run before executing the command
teardown : function
Teardown function to run after executing the command
local_log_prefix: str
The prefix of a local file path to the log file while the program is running:
<prefix>_commander.stdout
<prefix>_commander.stderr
<prefix>_worker0.stdout
<prefix>_worker0.stderr
If "out_log_prefix" is set, the files will be copied into out_log_prefix
when the process terminates.
out_log_prefix: str
The path prefix to the final saved log file.
If set, the logs will be save to the following locations:
<prefix>.stdout
<prefix>.stderr
and the return value will contain paths to the log files.
The path can be local or hdfs or s3.
Returns
-------
out : dict
A dictionary containing the following keys:
success : bool
True if the command succeeded
return_code : int
The return code of the command
stderr : str
Path to the stderr log of the process
stdout : str
Path to the stdout log of the process
python_exception : Exception
Python exception
"""
import logging
import os
ret = {'success': True,
'return_code': None,
'stdout': None,
'stderr': None,
'python_exception': None,
'proc_object' : None}
blocking = True
# Creates local running log file
try:
if local_log_prefix in [_subprocess.PIPE,
_subprocess.STDOUT]:
local_log_stdout = local_log_prefix
local_log_stderr = local_log_prefix
blocking = False
if out_log_prefix is not None:
raise ValueError("Cannot pipe output and set an output log!")
elif local_log_prefix:
local_log_stdout = open(local_log_prefix + '.stdout', 'w')
local_log_stderr = open(local_log_prefix + '.stderr', 'w')
else:
local_log_stdout = _tempfile.NamedTemporaryFile(delete=False)
local_log_stderr = _tempfile.NamedTemporaryFile(delete=False)
except Exception as e:
ret['success'] = False
ret['python_exception'] = e
# Run setup
try:
if setup is not None:
setup()
except Exception as e:
ret['success'] = False
ret['python_exception'] = e
# Executes the command
if ret['success']:
try:
if environment_variables is not None:
environment_variables = os.environ.copy().update(environment_variables)
proc = _subprocess.Popen([exe] + args,
stdout=local_log_stdout,
stderr=local_log_stderr,
env=environment_variables)
if blocking:
proc.communicate()
ret['success'] = proc.returncode == 0
ret['return_code'] = proc.returncode
else:
ret['success'] = None
ret['stdout'] = proc.stdout
ret['stderr'] = proc.stderr
ret['proc_object'] = proc
except Exception as e:
ret['success'] = False
ret['python_exception'] = e
finally:
if blocking:
try:
local_log_stdout.close()
local_log_stderr.close()
if out_log_prefix is not None:
# persistent logfiles. When local log closed,
# they will be loaded to the corresponding hdfs or s3 path
file_log_stdout = out_log_prefix + '.stdout'
file_log_stderr = out_log_prefix + '.stderr'
# copy to target log path
file_util.copy_from_local(local_log_stdout.name, file_log_stdout)
file_util.copy_from_local(local_log_stderr.name, file_log_stderr)
ret['stdout'] = file_log_stdout
ret['stderr'] = file_log_stderr
else:
ret['stdout'] = open(local_log_stdout.name).read()
ret['stderr'] = open(local_log_stderr.name).read()
except Exception as e:
ret['_save_log_exception'] = e
logging.warn(str(e))
# Teardown
if teardown is not None:
try:
teardown()
except Exception as e:
ret['_tear_down_exception'] = e
logging.warn(str(e))
return ret
# Automatic GPU detection
def _get_cuda_gpus():
"""
Returns a list of 0-based integer indices of available CUDA GPUs.
"""
import subprocess
try:
ret = subprocess.check_output(["nvidia-smi", "-L"], universal_newlines=True).split('\n')
return [i for i, s in enumerate(ret) if 'GPU' in s]
except OSError:
return []
_CUDA_GPU_IDS = _get_cuda_gpus()
def _num_available_gpus():
return len(_CUDA_GPU_IDS)
| 33.786594 | 181 | 0.619686 |
from __future__ import print_function as _
from __future__ import division as _
from __future__ import absolute_import as _
import logging
import logging.config
import time as _time
import tempfile as _tempfile
import os as _os
import urllib as _urllib
import re as _re
from zipfile import ZipFile as _ZipFile
import bz2 as _bz2
import tarfile as _tarfile
import itertools as _itertools
import uuid as _uuid
import datetime as _datetime
import sys as _sys
import subprocess as _subprocess
from ..config import get_client_log_location as _get_client_log_location
from .sframe_generation import generate_random_sframe
from .sframe_generation import generate_random_regression_sframe
from .sframe_generation import generate_random_classification_sframe
from .type_checks import _raise_error_if_not_function
from .type_checks import _raise_error_if_not_of_type
from .type_checks import _is_non_string_iterable
from .type_checks import _is_string
try:
import configparser as _ConfigParser
except ImportError:
import ConfigParser as _ConfigParser
def _convert_slashes(path):
return path.replace('\\', '/')
def _get_s3_endpoint():
import turicreate
return turicreate.config.get_runtime_config()['TURI_S3_ENDPOINT']
def _get_aws_credentials():
if (not 'AWS_ACCESS_KEY_ID' in _os.environ):
raise KeyError('No access key found. Please set the environment variable AWS_ACCESS_KEY_ID.')
if (not 'AWS_SECRET_ACCESS_KEY' in _os.environ):
raise KeyError('No secret key found. Please set the environment variable AWS_SECRET_ACCESS_KEY.')
return (_os.environ['AWS_ACCESS_KEY_ID'], _os.environ['AWS_SECRET_ACCESS_KEY'])
def _try_inject_s3_credentials(url):
assert url.startswith('s3://')
path = url[5:]
tokens = path.split(':')
if len(tokens) == 3:
if ('/' not in tokens[0]) and ('/' not in tokens[1]):
return url
(k, v) = _get_aws_credentials()
return 's3://' + k + ':' + v + ':' + path
def _make_internal_url(url):
if not url:
raise ValueError('Invalid url: %s' % url)
from .. import _sys_util
from . import file_util
url = _convert_slashes(url)
protocol = file_util.get_protocol(url)
is_local = False
if protocol in ['http', 'https']:
pass
elif protocol == 'hdfs':
if not _sys_util.get_hadoop_class_path():
raise ValueError("HDFS URL is not supported because Hadoop not found. Please make hadoop available from PATH or set the environment variable HADOOP_HOME and try again.")
elif protocol == 's3':
return _try_inject_s3_credentials(url)
elif protocol == '':
is_local = True
elif (protocol == 'local' or protocol == 'remote'):
is_local = True
url = _re.sub(protocol+'://','',url,count=1)
else:
raise ValueError('Invalid url protocol %s. Supported url protocols are: local, s3://, https:// and hdfs://' % protocol)
if is_local:
url = _os.path.abspath(_os.path.expanduser(url))
return url
def _download_dataset(url_str, extract=True, force=False, output_dir="."):
fname = output_dir + "/" + url_str.split("/")[-1]
if not _os.path.isfile(fname) or force:
print("Downloading file from:", url_str)
_urllib.urlretrieve(url_str, fname)
if extract and fname[-3:] == "zip":
print("Decompressing zip archive", fname)
_ZipFile(fname).extractall(output_dir)
elif extract and fname[-6:] == ".tar.gz":
print("Decompressing tar.gz archive", fname)
_tarfile.TarFile(fname).extractall(output_dir)
elif extract and fname[-7:] == ".tar.bz2":
print("Decompressing tar.bz2 archive", fname)
_tarfile.TarFile(fname).extractall(output_dir)
elif extract and fname[-3:] == "bz2":
print("Decompressing bz2 archive:", fname)
outfile = open(fname.split(".bz2")[0], "w")
print("Output file:", outfile)
for line in _bz2.BZ2File(fname, "r"):
outfile.write(line)
outfile.close()
else:
print("File is already downloaded.")
def is_directory_archive(path):
if path is None:
return False
if not _os.path.isdir(path):
return False
ini_path = '/'.join([_convert_slashes(path), 'dir_archive.ini'])
if not _os.path.exists(ini_path):
return False
if _os.path.isfile(ini_path):
return True
return False
def get_archive_type(path):
if not is_directory_archive(path):
raise TypeError('Unable to determine the type of archive at path: %s' % path)
try:
ini_path = '/'.join([_convert_slashes(path), 'dir_archive.ini'])
parser = _ConfigParser.SafeConfigParser()
parser.read(ini_path)
contents = parser.get('metadata', 'contents')
return contents
except Exception as e:
raise TypeError('Unable to determine type of archive for path: %s' % path, e)
_GLOB_RE = _re.compile("""[*?]""")
def _split_path_elements(url):
parts = _os.path.split(url)
m = _GLOB_RE.search(parts[-1])
if m:
return (parts[0], parts[1])
else:
return (url, "")
def crossproduct(d):
from .. import SArray
d = [list(zip(list(d.keys()), x)) for x in _itertools.product(*list(d.values()))]
sa = [{k:v for (k,v) in x} for x in d]
return SArray(sa).unpack(column_name_prefix='')
def get_turicreate_object_type(url):
from ..connect import main as _glconnect
ret = _glconnect.get_unity().get_turicreate_object_type(_make_internal_url(url))
if ret == 'graph':
ret = 'sgraph'
return ret
def _assert_sframe_equal(sf1,
sf2,
check_column_names=True,
check_column_order=True,
check_row_order=True,
float_column_delta=None):
from .. import SFrame as _SFrame
if (type(sf1) is not _SFrame) or (type(sf2) is not _SFrame):
raise TypeError("Cannot function on types other than SFrames.")
if not check_column_order and not check_column_names:
raise ValueError("Cannot ignore both column order and column names.")
sf1.__materialize__()
sf2.__materialize__()
if sf1.num_columns() != sf2.num_columns():
raise AssertionError("Number of columns mismatched: " +
str(sf1.num_columns()) + " != " + str(sf2.num_columns()))
s1_names = sf1.column_names()
s2_names = sf2.column_names()
sorted_s1_names = sorted(s1_names)
sorted_s2_names = sorted(s2_names)
if check_column_names:
if (check_column_order and (s1_names != s2_names)) or (sorted_s1_names != sorted_s2_names):
raise AssertionError("SFrame does not have same column names: " +
str(sf1.column_names()) + " != " + str(sf2.column_names()))
if sf1.num_rows() != sf2.num_rows():
raise AssertionError("Number of rows mismatched: " +
str(sf1.num_rows()) + " != " + str(sf2.num_rows()))
if not check_row_order and (sf1.num_rows() > 1):
sf1 = sf1.sort(s1_names)
sf2 = sf2.sort(s2_names)
names_to_check = None
if check_column_names:
names_to_check = list(zip(sorted_s1_names, sorted_s2_names))
else:
names_to_check = list(zip(s1_names, s2_names))
for i in names_to_check:
col1 = sf1[i[0]]
col2 = sf2[i[1]]
if col1.dtype != col2.dtype:
raise AssertionError("Columns " + str(i) + " types mismatched.")
compare_ary = None
if col1.dtype == float and float_column_delta is not None:
dt = float_column_delta
compare_ary = ((col1 > col2-dt) & (col1 < col2+dt))
else:
compare_ary = (sf1[i[0]] == sf2[i[1]])
if not compare_ary.all():
count = 0
for j in compare_ary:
if not j:
first_row = count
break
count += 1
raise AssertionError("Columns " + str(i) +
" are not equal! First differing element is at row " +
str(first_row) + ": " + str((col1[first_row],col2[first_row])))
def _get_temp_file_location():
from ..connect import main as _glconnect
unity = _glconnect.get_unity()
cache_dir = _convert_slashes(unity.get_current_cache_file_location())
if not _os.path.exists(cache_dir):
_os.makedirs(cache_dir)
return cache_dir
def _make_temp_directory(prefix):
temp_dir = _make_temp_filename(prefix=str(prefix))
_os.makedirs(temp_dir)
return temp_dir
def _make_temp_filename(prefix):
temp_location = _get_temp_file_location()
temp_file_name = '/'.join([temp_location, str(prefix)+str(_uuid.uuid4())])
return temp_file_name
_ZERO = _datetime.timedelta(0)
class _UTC(_datetime.tzinfo):
def fromutc(self, dt):
if dt.tzinfo is None:
return self.localize(dt)
return super(_utc.__class__, self).fromutc(dt)
def utcoffset(self, dt):
return _ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return _ZERO
def __reduce__(self):
return _UTC, ()
def __repr__(self):
return "<UTC>"
def __str__(self):
return "UTC"
_utc = _UTC()
def _dt_to_utc_timestamp(t):
if t.tzname() == 'UTC':
return (t - _datetime.datetime(1970, 1, 1, tzinfo=_utc)).total_seconds()
elif not t.tzinfo:
return _time.mktime(t.timetuple())
else:
raise ValueError('Only local time and UTC time is supported')
def _pickle_to_temp_location_or_memory(obj):
from . import cloudpickle as cloudpickle
try:
lambda_str = cloudpickle.dumps(obj)
return lambda_str
except:
pass
filename = _make_temp_filename('pickle')
from .. import _gl_pickle
pickler = _gl_pickle.GLPickler(filename)
pickler.dump(obj)
pickler.close()
return filename
def get_module_from_object(obj):
mod_str = obj.__class__.__module__.split('.')[0]
return _sys.modules[mod_str]
def infer_dbapi2_types(cursor, mod_info):
desc = cursor.description
result_set_types = [i[1] for i in desc]
dbapi2_to_python = [
(mod_info['DATETIME'], _datetime.datetime),
(mod_info['ROWID'],int),
(mod_info['NUMBER'],float),
]
ret_types = []
for i in result_set_types:
type_found = False
for j in dbapi2_to_python:
if i is None or j[0] is None:
break
elif i == j[0]:
ret_types.append(j[1])
type_found = True
break
if not type_found:
ret_types.append(str)
return ret_types
def pytype_to_printf(in_type):
if in_type == int:
return 'd'
elif in_type == float:
return 'f'
else:
return 's'
def subprocess_exe(exe, args, setup=None, teardown=None,
local_log_prefix=None,
out_log_prefix=None,
environment_variables=None):
import logging
import os
ret = {'success': True,
'return_code': None,
'stdout': None,
'stderr': None,
'python_exception': None,
'proc_object' : None}
blocking = True
try:
if local_log_prefix in [_subprocess.PIPE,
_subprocess.STDOUT]:
local_log_stdout = local_log_prefix
local_log_stderr = local_log_prefix
blocking = False
if out_log_prefix is not None:
raise ValueError("Cannot pipe output and set an output log!")
elif local_log_prefix:
local_log_stdout = open(local_log_prefix + '.stdout', 'w')
local_log_stderr = open(local_log_prefix + '.stderr', 'w')
else:
local_log_stdout = _tempfile.NamedTemporaryFile(delete=False)
local_log_stderr = _tempfile.NamedTemporaryFile(delete=False)
except Exception as e:
ret['success'] = False
ret['python_exception'] = e
try:
if setup is not None:
setup()
except Exception as e:
ret['success'] = False
ret['python_exception'] = e
if ret['success']:
try:
if environment_variables is not None:
environment_variables = os.environ.copy().update(environment_variables)
proc = _subprocess.Popen([exe] + args,
stdout=local_log_stdout,
stderr=local_log_stderr,
env=environment_variables)
if blocking:
proc.communicate()
ret['success'] = proc.returncode == 0
ret['return_code'] = proc.returncode
else:
ret['success'] = None
ret['stdout'] = proc.stdout
ret['stderr'] = proc.stderr
ret['proc_object'] = proc
except Exception as e:
ret['success'] = False
ret['python_exception'] = e
finally:
if blocking:
try:
local_log_stdout.close()
local_log_stderr.close()
if out_log_prefix is not None:
file_log_stdout = out_log_prefix + '.stdout'
file_log_stderr = out_log_prefix + '.stderr'
file_util.copy_from_local(local_log_stdout.name, file_log_stdout)
file_util.copy_from_local(local_log_stderr.name, file_log_stderr)
ret['stdout'] = file_log_stdout
ret['stderr'] = file_log_stderr
else:
ret['stdout'] = open(local_log_stdout.name).read()
ret['stderr'] = open(local_log_stderr.name).read()
except Exception as e:
ret['_save_log_exception'] = e
logging.warn(str(e))
if teardown is not None:
try:
teardown()
except Exception as e:
ret['_tear_down_exception'] = e
logging.warn(str(e))
return ret
def _get_cuda_gpus():
import subprocess
try:
ret = subprocess.check_output(["nvidia-smi", "-L"], universal_newlines=True).split('\n')
return [i for i, s in enumerate(ret) if 'GPU' in s]
except OSError:
return []
_CUDA_GPU_IDS = _get_cuda_gpus()
def _num_available_gpus():
return len(_CUDA_GPU_IDS)
| true | true |
f7f8d06153f4836710ae26ae715a70bb03f0916c | 12,056 | py | Python | utils.py | Fred62879/ACORN | 2de0bf747d595dbdc4d67311fb8f46cf47f9b4cb | [
"MIT"
] | null | null | null | utils.py | Fred62879/ACORN | 2de0bf747d595dbdc4d67311fb8f46cf47f9b4cb | [
"MIT"
] | null | null | null | utils.py | Fred62879/ACORN | 2de0bf747d595dbdc4d67311fb8f46cf47f9b4cb | [
"MIT"
] | null | null | null | import os
import torch
import numpy as np
import skimage.measure
import matplotlib.pyplot as plt
from tqdm import tqdm
from astropy.io import fits
from astropy.wcs import WCS
from astropy.nddata import Cutout2D
from torchvision.utils import make_grid
def cond_mkdir(path):
if not os.path.exists(path):
os.makedirs(path)
def write_psnr(pred_img, gt_img, writer, iter, prefix):
batch_size = pred_img.shape[0]
pred_img = pred_img.detach().cpu().numpy()
gt_img = gt_img.detach().cpu().numpy()
psnrs = list()
for i in range(batch_size):
p = pred_img[i].transpose(1, 2, 0)
trgt = gt_img[i].transpose(1, 2, 0)
p = (p / 2.) + 0.5
p = np.clip(p, a_min=0., a_max=1.)
trgt = (trgt / 2.) + 0.5
psnr = skimage.metrics.peak_signal_noise_ratio(p, trgt, data_range=1)
psnrs.append(psnr)
writer.add_scalar(prefix + "psnr", np.mean(psnrs), iter)
def write_image_patch_multiscale_summary(image_resolution, patch_size, dataset, model, model_input, gt,
model_output, writer, total_steps, prefix='train_',
model_type='multiscale', skip=False):
if skip:
return
# uniformly sample the image
dataset.toggle_eval()
model_input, gt = dataset[0]
dataset.toggle_eval()
# convert to cuda and add batch dimension
tmp = {}
for key, value in model_input.items():
if isinstance(value, torch.Tensor):
tmp.update({key: value[None, ...].cpu()})
else:
tmp.update({key: value})
model_input = tmp
tmp = {}
for key, value in gt.items():
if isinstance(value, torch.Tensor):
tmp.update({key: value[None, ...].cpu()})
else:
tmp.update({key: value})
gt = tmp
# run the model on uniform samples
n_channels = gt['img'].shape[-1]
pred_img = process_batch_in_chunks(model_input, model)['model_out']['output']
# get pixel idx for each coordinate
coords = model_input['fine_abs_coords'].detach().cpu().numpy()
pixel_idx = np.zeros_like(coords).astype(np.int32)
pixel_idx[..., 0] = np.round((coords[..., 0] + 1.)/2. * (dataset.sidelength[0]-1)).astype(np.int32)
pixel_idx[..., 1] = np.round((coords[..., 1] + 1.)/2. * (dataset.sidelength[1]-1)).astype(np.int32)
pixel_idx = pixel_idx.reshape(-1, 2)
# get pixel idx for each coordinate in frozen patches
frozen_coords, frozen_values = dataset.get_frozen_patches()
if frozen_coords is not None:
frozen_coords = frozen_coords.detach().cpu().numpy()
frozen_pixel_idx = np.zeros_like(frozen_coords).astype(np.int32)
frozen_pixel_idx[..., 0] = np.round((frozen_coords[..., 0] + 1.) / 2. * (dataset.sidelength[0] - 1)).astype(np.int32)
frozen_pixel_idx[..., 1] = np.round((frozen_coords[..., 1] + 1.) / 2. * (dataset.sidelength[1] - 1)).astype(np.int32)
frozen_pixel_idx = frozen_pixel_idx.reshape(-1, 2)
# init a new reconstructed image
display_pred = np.zeros((*dataset.sidelength, n_channels))
# assign predicted image values into a new array
# need to use numpy since it supports index assignment
pred_img = pred_img.reshape(-1, n_channels).detach().cpu().numpy()
display_pred[[pixel_idx[:, 0]], [pixel_idx[:, 1]]] = pred_img
# assign frozen image values into the array too
if frozen_coords is not None:
frozen_values = frozen_values.reshape(-1, n_channels).detach().cpu().numpy()
display_pred[[frozen_pixel_idx[:, 0]], [frozen_pixel_idx[:, 1]]] = frozen_values
# show reconstructed img
display_pred = torch.tensor(display_pred)[None, ...]
display_pred = display_pred.permute(0, 3, 1, 2)
gt_img = gt['img'].reshape(-1, n_channels).detach().cpu().numpy()
display_gt = np.zeros((*dataset.sidelength, n_channels))
display_gt[[pixel_idx[:, 0]], [pixel_idx[:, 1]]] = gt_img
display_gt = torch.tensor(display_gt)[None, ...]
display_gt = display_gt.permute(0, 3, 1, 2)
fig = dataset.quadtree.draw()
writer.add_figure(prefix + 'tiling', fig, global_step=total_steps)
if 'img' in gt:
output_vs_gt = torch.cat((display_gt, display_pred), dim=0)
writer.add_image(prefix + 'gt_vs_pred', make_grid(output_vs_gt, scale_each=False, normalize=True),
global_step=total_steps)
write_psnr(display_pred, display_gt, writer, total_steps, prefix+'img_')
def dict2cuda(a_dict):
tmp = {}
for key, value in a_dict.items():
if isinstance(value, torch.Tensor):
tmp.update({key: value.cuda()})
else:
tmp.update({key: value})
return tmp
def dict2cpu(a_dict):
tmp = {}
for key, value in a_dict.items():
if isinstance(value, torch.Tensor):
tmp.update({key: value.cpu()})
elif isinstance(value, dict):
tmp.update({key: dict2cpu(value)})
else:
tmp.update({key: value})
return tmp
def process_batch_in_chunks(in_dict, model, max_chunk_size=1024, progress=None):
in_chunked = []
for key in in_dict:
chunks = torch.split(in_dict[key], max_chunk_size, dim=1)
in_chunked.append(chunks)
list_chunked_batched_in = \
[{k: v for k, v in zip(in_dict.keys(), curr_chunks)} for curr_chunks in zip(*in_chunked)]
del in_chunked
list_chunked_batched_out_out = {}
list_chunked_batched_out_in = {}
for chunk_batched_in in tqdm(list_chunked_batched_in):
if torch.cuda.is_available():
chunk_batched_in = {k: v.cuda() for k, v in chunk_batched_in.items()}
else:
chunk_batched_in = {k: v for k, v in chunk_batched_in.items()}
tmp = model(chunk_batched_in)
tmp = dict2cpu(tmp)
for key in tmp['model_out']:
if tmp['model_out'][key] is None:
continue
out_ = tmp['model_out'][key].detach().clone().requires_grad_(False)
list_chunked_batched_out_out.setdefault(key, []).append(out_)
for key in tmp['model_in']:
if tmp['model_in'][key] is None:
continue
in_ = tmp['model_in'][key].detach().clone().requires_grad_(False)
list_chunked_batched_out_in.setdefault(key, []).append(in_)
del tmp, chunk_batched_in
# Reassemble the output chunks in a batch
batched_out = {}
for key in list_chunked_batched_out_out:
batched_out_lin = torch.cat(list_chunked_batched_out_out[key], dim=1)
batched_out[key] = batched_out_lin
batched_in = {}
for key in list_chunked_batched_out_in:
batched_in_lin = torch.cat(list_chunked_batched_out_in[key], dim=1)
batched_in[key] = batched_in_lin
return {'model_in': batched_in, 'model_out': batched_out}
def subsample_dict(in_dict, num_views, multiscale=False):
if multiscale:
out = {}
for k, v in in_dict.items():
if v.shape[0] == in_dict['octant_coords'].shape[0]:
# this is arranged by blocks
out.update({k: v[0:num_views[0]]})
else:
# arranged by rays
out.update({k: v[0:num_views[1]]})
else:
out = {key: value[0:num_views, ...] for key, value in in_dict.items()}
return out
def get_header(dir, sz):
hdu = fits.open(os.path.join(dir, 'pdr3_dud/calexp-HSC-G-9813-0%2C0.fits'))[1]
header = hdu.header
cutout = Cutout2D(hdu.data, position=(sz//2, sz//2),
size=sz, wcs=WCS(header))
return cutout.wcs.to_header()
def reconstruct_trail(id, coord_dataset, gt, model_input, model, recon_dir, header):
n_channels = gt['img'].shape[-1]
pred_img = pred_img.detach().cpu().numpy().reshape(-1, n_channels)
display_pred = np.zeros((*coord_dataset.sidelength, n_channels))
display_pred[[pixel_idx[:, 0]], [pixel_idx[:, 1]]] = pred_img
display_pred = torch.tensor(display_pred)[None, ...]
display_pred = display_pred.permute(0, 3, 1, 2)
if not saved_gt:
gt_img = gt['img'].detach().cpu().numpy().reshape(-1, n_channels)
display_gt = np.zeros((*coord_dataset.sidelength, n_channels))
display_gt[[pixel_idx[:, 0]], [pixel_idx[:, 1]]] = gt_img
display_gt = torch.tensor(display_gt)[None, ...]
display_gt = display_gt.permute(0, 3, 1, 2)
print(f'Reshape: {time() - start:.02f}')
# record metrics
start = time()
psnr, ssim = get_metrics(display_pred, display_gt)
metrics.update({curr_iter: {'psnr': psnr, 'ssim': ssim}})
print(f'Metrics: {time() - start:.02f}')
print(f'Iter: {curr_iter}, PSNR: {psnr:.02f}')
# save images
pred_out = np.clip((display_pred.squeeze().numpy()/2.) + 0.5, a_min=0., a_max=1.).transpose(1, 2, 0)*255
pred_out = pred_out.astype(np.uint8)
pred_fname = os.path.join(eval_dir, f'pred_{curr_iter:06d}.png')
print('Saving image')
cv2.imwrite(pred_fname, cv2.cvtColor(pred_out, cv2.COLOR_RGB2BGR))
if not saved_gt:
gt_out = np.clip((display_gt.squeeze().numpy()/2.) + 0.5, a_min=0., a_max=1.).transpose(1, 2, 0)*255
gt_out = gt_out.astype(np.uint8)
gt_fname = os.path.join(eval_dir, 'gt.png')
cv2.imwrite(gt_fname, cv2.cvtColor(gt_out, cv2.COLOR_RGB2BGR))
saved_gt = True
# record and save metrics
psnr, ssim, mse = get_metrics(recon, gt)
print(f'PSNR: {psnr:.04f}, SSIM: {ssim:.04f}, MSE:{mse:.06f}')
# save images
recon_fn = os.path.join(recon_dir, '{}'.format(id))
np.save(recon_fn + '.npy', recon)
hdu = fits.PrimaryHDU(data=recon, header=header)
hdu.writeto(recon_fn + '.fits', overwrite=True)
# save tiling
tiling_fname = os.path.join(recon_dir, 'tiling_{}.pdf'.format(id))
coord_dataset.quadtree.draw()
plt.savefig(tiling_fname)
return mse, psnr, ssim
def reconstruct_astro(id, coord_dataset, gt, model_input, model, recon_dir, header):
n_channels = gt['img'].shape[-1]
with torch.no_grad():
recon = process_batch_in_chunks\
(model_input, model, max_chunk_size=512)['model_out']['output']
if torch.cuda.is_available():
torch.cuda.synchronize()
# get pixel idx for each coordinate
coords = model_input['fine_abs_coords'].detach().cpu().numpy()
pixel_idx = np.zeros_like(coords).astype(np.int32)
pixel_idx[..., 0] = np.round((coords[..., 0] + 1.)/2.*
(coord_dataset.sidelength[0] - 1)).astype(np.int32)
pixel_idx[..., 1] = np.round((coords[..., 1] + 1.)/2. *
(coord_dataset.sidelength[1] - 1)).astype(np.int32)
pixel_idx = pixel_idx.reshape(-1, 2)
recon = recon.detach().cpu().numpy()[0].transpose((2,0,1))
gt = gt['img'].detach().cpu().numpy()[0].transpose((2,0,1))
print(gt.shape)
# record and save metrics
psnr, ssim, mse = get_metrics(recon, gt)
print(f'PSNR: {psnr:.04f}, SSIM: {ssim:.04f}, MSE:{mse:.06f}')
# save images
recon_fn = os.path.join(recon_dir, '{}'.format(id))
np.save(recon_fn + '.npy', recon)
hdu = fits.PrimaryHDU(data=recon, header=header)
hdu.writeto(recon_fn + '.fits', overwrite=True)
# save tiling
tiling_fname = os.path.join(recon_dir, 'tiling_{}.pdf'.format(id))
coord_dataset.quadtree.draw()
plt.savefig(tiling_fname)
return mse, psnr, ssim
def get_metrics(pred_img, gt_img):
#pred_img = pred_img.detach().cpu().numpy().squeeze()
#gt_img = gt_img.detach().cpu().numpy().squeeze()
p = pred_img.transpose(1, 2, 0)
trgt = gt_img.transpose(1, 2, 0)
p = (p / 2.) + 0.5
p = np.clip(p, a_min=0., a_max=1.)
trgt = (trgt / 2.) + 0.5
range = np.max(gt_img) - np.min(gt_img)
mse = np.mean((p-trgt)**2)
print(p.shape, trgt.shape)
psnr = skimage.metrics.peak_signal_noise_ratio(p, trgt, data_range=range)
ssim = skimage.metrics.structural_similarity(p, trgt, multichannel=True, data_range=range)
return psnr, ssim, mse
| 35.98806 | 125 | 0.626576 | import os
import torch
import numpy as np
import skimage.measure
import matplotlib.pyplot as plt
from tqdm import tqdm
from astropy.io import fits
from astropy.wcs import WCS
from astropy.nddata import Cutout2D
from torchvision.utils import make_grid
def cond_mkdir(path):
if not os.path.exists(path):
os.makedirs(path)
def write_psnr(pred_img, gt_img, writer, iter, prefix):
batch_size = pred_img.shape[0]
pred_img = pred_img.detach().cpu().numpy()
gt_img = gt_img.detach().cpu().numpy()
psnrs = list()
for i in range(batch_size):
p = pred_img[i].transpose(1, 2, 0)
trgt = gt_img[i].transpose(1, 2, 0)
p = (p / 2.) + 0.5
p = np.clip(p, a_min=0., a_max=1.)
trgt = (trgt / 2.) + 0.5
psnr = skimage.metrics.peak_signal_noise_ratio(p, trgt, data_range=1)
psnrs.append(psnr)
writer.add_scalar(prefix + "psnr", np.mean(psnrs), iter)
def write_image_patch_multiscale_summary(image_resolution, patch_size, dataset, model, model_input, gt,
model_output, writer, total_steps, prefix='train_',
model_type='multiscale', skip=False):
if skip:
return
dataset.toggle_eval()
model_input, gt = dataset[0]
dataset.toggle_eval()
tmp = {}
for key, value in model_input.items():
if isinstance(value, torch.Tensor):
tmp.update({key: value[None, ...].cpu()})
else:
tmp.update({key: value})
model_input = tmp
tmp = {}
for key, value in gt.items():
if isinstance(value, torch.Tensor):
tmp.update({key: value[None, ...].cpu()})
else:
tmp.update({key: value})
gt = tmp
n_channels = gt['img'].shape[-1]
pred_img = process_batch_in_chunks(model_input, model)['model_out']['output']
coords = model_input['fine_abs_coords'].detach().cpu().numpy()
pixel_idx = np.zeros_like(coords).astype(np.int32)
pixel_idx[..., 0] = np.round((coords[..., 0] + 1.)/2. * (dataset.sidelength[0]-1)).astype(np.int32)
pixel_idx[..., 1] = np.round((coords[..., 1] + 1.)/2. * (dataset.sidelength[1]-1)).astype(np.int32)
pixel_idx = pixel_idx.reshape(-1, 2)
frozen_coords, frozen_values = dataset.get_frozen_patches()
if frozen_coords is not None:
frozen_coords = frozen_coords.detach().cpu().numpy()
frozen_pixel_idx = np.zeros_like(frozen_coords).astype(np.int32)
frozen_pixel_idx[..., 0] = np.round((frozen_coords[..., 0] + 1.) / 2. * (dataset.sidelength[0] - 1)).astype(np.int32)
frozen_pixel_idx[..., 1] = np.round((frozen_coords[..., 1] + 1.) / 2. * (dataset.sidelength[1] - 1)).astype(np.int32)
frozen_pixel_idx = frozen_pixel_idx.reshape(-1, 2)
display_pred = np.zeros((*dataset.sidelength, n_channels))
pred_img = pred_img.reshape(-1, n_channels).detach().cpu().numpy()
display_pred[[pixel_idx[:, 0]], [pixel_idx[:, 1]]] = pred_img
if frozen_coords is not None:
frozen_values = frozen_values.reshape(-1, n_channels).detach().cpu().numpy()
display_pred[[frozen_pixel_idx[:, 0]], [frozen_pixel_idx[:, 1]]] = frozen_values
display_pred = torch.tensor(display_pred)[None, ...]
display_pred = display_pred.permute(0, 3, 1, 2)
gt_img = gt['img'].reshape(-1, n_channels).detach().cpu().numpy()
display_gt = np.zeros((*dataset.sidelength, n_channels))
display_gt[[pixel_idx[:, 0]], [pixel_idx[:, 1]]] = gt_img
display_gt = torch.tensor(display_gt)[None, ...]
display_gt = display_gt.permute(0, 3, 1, 2)
fig = dataset.quadtree.draw()
writer.add_figure(prefix + 'tiling', fig, global_step=total_steps)
if 'img' in gt:
output_vs_gt = torch.cat((display_gt, display_pred), dim=0)
writer.add_image(prefix + 'gt_vs_pred', make_grid(output_vs_gt, scale_each=False, normalize=True),
global_step=total_steps)
write_psnr(display_pred, display_gt, writer, total_steps, prefix+'img_')
def dict2cuda(a_dict):
tmp = {}
for key, value in a_dict.items():
if isinstance(value, torch.Tensor):
tmp.update({key: value.cuda()})
else:
tmp.update({key: value})
return tmp
def dict2cpu(a_dict):
tmp = {}
for key, value in a_dict.items():
if isinstance(value, torch.Tensor):
tmp.update({key: value.cpu()})
elif isinstance(value, dict):
tmp.update({key: dict2cpu(value)})
else:
tmp.update({key: value})
return tmp
def process_batch_in_chunks(in_dict, model, max_chunk_size=1024, progress=None):
in_chunked = []
for key in in_dict:
chunks = torch.split(in_dict[key], max_chunk_size, dim=1)
in_chunked.append(chunks)
list_chunked_batched_in = \
[{k: v for k, v in zip(in_dict.keys(), curr_chunks)} for curr_chunks in zip(*in_chunked)]
del in_chunked
list_chunked_batched_out_out = {}
list_chunked_batched_out_in = {}
for chunk_batched_in in tqdm(list_chunked_batched_in):
if torch.cuda.is_available():
chunk_batched_in = {k: v.cuda() for k, v in chunk_batched_in.items()}
else:
chunk_batched_in = {k: v for k, v in chunk_batched_in.items()}
tmp = model(chunk_batched_in)
tmp = dict2cpu(tmp)
for key in tmp['model_out']:
if tmp['model_out'][key] is None:
continue
out_ = tmp['model_out'][key].detach().clone().requires_grad_(False)
list_chunked_batched_out_out.setdefault(key, []).append(out_)
for key in tmp['model_in']:
if tmp['model_in'][key] is None:
continue
in_ = tmp['model_in'][key].detach().clone().requires_grad_(False)
list_chunked_batched_out_in.setdefault(key, []).append(in_)
del tmp, chunk_batched_in
batched_out = {}
for key in list_chunked_batched_out_out:
batched_out_lin = torch.cat(list_chunked_batched_out_out[key], dim=1)
batched_out[key] = batched_out_lin
batched_in = {}
for key in list_chunked_batched_out_in:
batched_in_lin = torch.cat(list_chunked_batched_out_in[key], dim=1)
batched_in[key] = batched_in_lin
return {'model_in': batched_in, 'model_out': batched_out}
def subsample_dict(in_dict, num_views, multiscale=False):
if multiscale:
out = {}
for k, v in in_dict.items():
if v.shape[0] == in_dict['octant_coords'].shape[0]:
out.update({k: v[0:num_views[0]]})
else:
out.update({k: v[0:num_views[1]]})
else:
out = {key: value[0:num_views, ...] for key, value in in_dict.items()}
return out
def get_header(dir, sz):
hdu = fits.open(os.path.join(dir, 'pdr3_dud/calexp-HSC-G-9813-0%2C0.fits'))[1]
header = hdu.header
cutout = Cutout2D(hdu.data, position=(sz//2, sz//2),
size=sz, wcs=WCS(header))
return cutout.wcs.to_header()
def reconstruct_trail(id, coord_dataset, gt, model_input, model, recon_dir, header):
n_channels = gt['img'].shape[-1]
pred_img = pred_img.detach().cpu().numpy().reshape(-1, n_channels)
display_pred = np.zeros((*coord_dataset.sidelength, n_channels))
display_pred[[pixel_idx[:, 0]], [pixel_idx[:, 1]]] = pred_img
display_pred = torch.tensor(display_pred)[None, ...]
display_pred = display_pred.permute(0, 3, 1, 2)
if not saved_gt:
gt_img = gt['img'].detach().cpu().numpy().reshape(-1, n_channels)
display_gt = np.zeros((*coord_dataset.sidelength, n_channels))
display_gt[[pixel_idx[:, 0]], [pixel_idx[:, 1]]] = gt_img
display_gt = torch.tensor(display_gt)[None, ...]
display_gt = display_gt.permute(0, 3, 1, 2)
print(f'Reshape: {time() - start:.02f}')
start = time()
psnr, ssim = get_metrics(display_pred, display_gt)
metrics.update({curr_iter: {'psnr': psnr, 'ssim': ssim}})
print(f'Metrics: {time() - start:.02f}')
print(f'Iter: {curr_iter}, PSNR: {psnr:.02f}')
pred_out = np.clip((display_pred.squeeze().numpy()/2.) + 0.5, a_min=0., a_max=1.).transpose(1, 2, 0)*255
pred_out = pred_out.astype(np.uint8)
pred_fname = os.path.join(eval_dir, f'pred_{curr_iter:06d}.png')
print('Saving image')
cv2.imwrite(pred_fname, cv2.cvtColor(pred_out, cv2.COLOR_RGB2BGR))
if not saved_gt:
gt_out = np.clip((display_gt.squeeze().numpy()/2.) + 0.5, a_min=0., a_max=1.).transpose(1, 2, 0)*255
gt_out = gt_out.astype(np.uint8)
gt_fname = os.path.join(eval_dir, 'gt.png')
cv2.imwrite(gt_fname, cv2.cvtColor(gt_out, cv2.COLOR_RGB2BGR))
saved_gt = True
psnr, ssim, mse = get_metrics(recon, gt)
print(f'PSNR: {psnr:.04f}, SSIM: {ssim:.04f}, MSE:{mse:.06f}')
recon_fn = os.path.join(recon_dir, '{}'.format(id))
np.save(recon_fn + '.npy', recon)
hdu = fits.PrimaryHDU(data=recon, header=header)
hdu.writeto(recon_fn + '.fits', overwrite=True)
tiling_fname = os.path.join(recon_dir, 'tiling_{}.pdf'.format(id))
coord_dataset.quadtree.draw()
plt.savefig(tiling_fname)
return mse, psnr, ssim
def reconstruct_astro(id, coord_dataset, gt, model_input, model, recon_dir, header):
n_channels = gt['img'].shape[-1]
with torch.no_grad():
recon = process_batch_in_chunks\
(model_input, model, max_chunk_size=512)['model_out']['output']
if torch.cuda.is_available():
torch.cuda.synchronize()
coords = model_input['fine_abs_coords'].detach().cpu().numpy()
pixel_idx = np.zeros_like(coords).astype(np.int32)
pixel_idx[..., 0] = np.round((coords[..., 0] + 1.)/2.*
(coord_dataset.sidelength[0] - 1)).astype(np.int32)
pixel_idx[..., 1] = np.round((coords[..., 1] + 1.)/2. *
(coord_dataset.sidelength[1] - 1)).astype(np.int32)
pixel_idx = pixel_idx.reshape(-1, 2)
recon = recon.detach().cpu().numpy()[0].transpose((2,0,1))
gt = gt['img'].detach().cpu().numpy()[0].transpose((2,0,1))
print(gt.shape)
psnr, ssim, mse = get_metrics(recon, gt)
print(f'PSNR: {psnr:.04f}, SSIM: {ssim:.04f}, MSE:{mse:.06f}')
recon_fn = os.path.join(recon_dir, '{}'.format(id))
np.save(recon_fn + '.npy', recon)
hdu = fits.PrimaryHDU(data=recon, header=header)
hdu.writeto(recon_fn + '.fits', overwrite=True)
tiling_fname = os.path.join(recon_dir, 'tiling_{}.pdf'.format(id))
coord_dataset.quadtree.draw()
plt.savefig(tiling_fname)
return mse, psnr, ssim
def get_metrics(pred_img, gt_img):
p = pred_img.transpose(1, 2, 0)
trgt = gt_img.transpose(1, 2, 0)
p = (p / 2.) + 0.5
p = np.clip(p, a_min=0., a_max=1.)
trgt = (trgt / 2.) + 0.5
range = np.max(gt_img) - np.min(gt_img)
mse = np.mean((p-trgt)**2)
print(p.shape, trgt.shape)
psnr = skimage.metrics.peak_signal_noise_ratio(p, trgt, data_range=range)
ssim = skimage.metrics.structural_similarity(p, trgt, multichannel=True, data_range=range)
return psnr, ssim, mse
| true | true |
f7f8d3a44d63bdc4f8af5771ff42b779f07acb06 | 9,499 | py | Python | infobip_api_client/model/tfa_message.py | DavadDi/infobip-api-python-client | 2268b154b5462d90773fd47f9813f88c0c7d56e2 | [
"MIT"
] | 23 | 2015-07-24T14:13:12.000Z | 2022-03-24T19:36:54.000Z | infobip_api_client/model/tfa_message.py | DavadDi/infobip-api-python-client | 2268b154b5462d90773fd47f9813f88c0c7d56e2 | [
"MIT"
] | 9 | 2017-01-22T14:07:22.000Z | 2021-10-04T10:54:08.000Z | infobip_api_client/model/tfa_message.py | DavadDi/infobip-api-python-client | 2268b154b5462d90773fd47f9813f88c0c7d56e2 | [
"MIT"
] | 36 | 2015-07-24T14:40:22.000Z | 2022-03-15T18:33:01.000Z | """
Infobip Client API Libraries OpenAPI Specification
OpenAPI specification containing public endpoints supported in client API libraries. # noqa: E501
The version of the OpenAPI document: 1.0.172
Contact: support@infobip.com
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from infobip_api_client.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
)
def lazy_import():
from infobip_api_client.model.tfa_language import TfaLanguage
from infobip_api_client.model.tfa_pin_type import TfaPinType
from infobip_api_client.model.tfa_regional_options import TfaRegionalOptions
globals()["TfaLanguage"] = TfaLanguage
globals()["TfaPinType"] = TfaPinType
globals()["TfaRegionalOptions"] = TfaRegionalOptions
class TfaMessage(ModelNormal):
"""
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
"""
allowed_values = {}
validations = {}
additional_properties_type = None
_nullable = False
@cached_property
def openapi_types():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
"""
lazy_import()
return {
"application_id": (str,), # noqa: E501
"language": (TfaLanguage,), # noqa: E501
"message_id": (str,), # noqa: E501
"message_text": (str,), # noqa: E501
"pin_length": (int,), # noqa: E501
"pin_placeholder": (str,), # noqa: E501
"pin_type": (TfaPinType,), # noqa: E501
"regional": (TfaRegionalOptions,), # noqa: E501
"repeat_dtmf": (str,), # noqa: E501
"sender_id": (str,), # noqa: E501
"speech_rate": (float,), # noqa: E501
}
@cached_property
def discriminator():
return None
attribute_map = {
"application_id": "applicationId", # noqa: E501
"language": "language", # noqa: E501
"message_id": "messageId", # noqa: E501
"message_text": "messageText", # noqa: E501
"pin_length": "pinLength", # noqa: E501
"pin_placeholder": "pinPlaceholder", # noqa: E501
"pin_type": "pinType", # noqa: E501
"regional": "regional", # noqa: E501
"repeat_dtmf": "repeatDTMF", # noqa: E501
"sender_id": "senderId", # noqa: E501
"speech_rate": "speechRate", # noqa: E501
}
_composed_schemas = {}
required_properties = set(
[
"_data_store",
"_check_type",
"_spec_property_naming",
"_path_to_item",
"_configuration",
"_visited_composed_classes",
]
)
@convert_js_args_to_python_args
def __init__(self, *args, **kwargs): # noqa: E501
"""TfaMessage - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
application_id (str): 2FA application ID for which the requested message is created.. [optional] # noqa: E501
language (TfaLanguage): Language code of language in which message text is written. It is used for reading the message when it is sent via voice. If no language is set, message will be read in `English`.. [optional] # noqa: E501
message_id (str): Message template ID.. [optional] # noqa: E501
message_text (str): Text of a message that will be sent. Message text must contain `pinPlaceholder`.. [optional] # noqa: E501
pin_length (int): PIN code length.. [optional] # noqa: E501
pin_placeholder (str): PIN code placeholder that will be replaced with generated PIN code.. [optional] # noqa: E501
pin_type (TfaPinType): Type of PIN code that will be generated and sent as part of 2FA message. You can set PIN type to numeric, alpha, alphanumeric or hex.. [optional] # noqa: E501
regional (TfaRegionalOptions): Region specific parameters, often specified by local laws. Use this if country or region that you are sending SMS to requires some extra parameters.. [optional] # noqa: E501
repeat_dtmf (str): In case PIN message is sent by Voice, DTMF code will enable replaying the message.. [optional] # noqa: E501
sender_id (str): The name that will appear as the sender of the 2FA message (Example: CompanyName).. [optional] # noqa: E501
speech_rate (float): In case PIN message is sent by Voice, the speed of speech can be set for the message. Supported range is from `0.5` to `2`.. [optional] # noqa: E501
"""
_check_type = kwargs.pop("_check_type", True)
_spec_property_naming = kwargs.pop("_spec_property_naming", False)
_path_to_item = kwargs.pop("_path_to_item", ())
_configuration = kwargs.pop("_configuration", None)
_visited_composed_classes = kwargs.pop("_visited_composed_classes", ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments."
% (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
for var_name, var_value in kwargs.items():
if (
var_name not in self.attribute_map
and self._configuration is not None
and self._configuration.discard_unknown_keys
and self.additional_properties_type is None
):
# discard variable.
continue
setattr(self, var_name, var_value)
| 45.888889 | 241 | 0.600905 |
import re
import sys
from infobip_api_client.model_utils import (
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
)
def lazy_import():
from infobip_api_client.model.tfa_language import TfaLanguage
from infobip_api_client.model.tfa_pin_type import TfaPinType
from infobip_api_client.model.tfa_regional_options import TfaRegionalOptions
globals()["TfaLanguage"] = TfaLanguage
globals()["TfaPinType"] = TfaPinType
globals()["TfaRegionalOptions"] = TfaRegionalOptions
class TfaMessage(ModelNormal):
allowed_values = {}
validations = {}
additional_properties_type = None
_nullable = False
@cached_property
def openapi_types():
lazy_import()
return {
"application_id": (str,),
"language": (TfaLanguage,),
"message_id": (str,),
"message_text": (str,),
"pin_length": (int,),
"pin_placeholder": (str,),
"pin_type": (TfaPinType,),
"regional": (TfaRegionalOptions,),
"repeat_dtmf": (str,),
"sender_id": (str,),
"speech_rate": (float,),
}
@cached_property
def discriminator():
return None
attribute_map = {
"application_id": "applicationId",
"language": "language",
"message_id": "messageId",
"message_text": "messageText",
"pin_length": "pinLength",
"pin_placeholder": "pinPlaceholder",
"pin_type": "pinType",
"regional": "regional",
"repeat_dtmf": "repeatDTMF",
"sender_id": "senderId",
"speech_rate": "speechRate",
}
_composed_schemas = {}
required_properties = set(
[
"_data_store",
"_check_type",
"_spec_property_naming",
"_path_to_item",
"_configuration",
"_visited_composed_classes",
]
)
@convert_js_args_to_python_args
def __init__(self, *args, **kwargs):
_check_type = kwargs.pop("_check_type", True)
_spec_property_naming = kwargs.pop("_spec_property_naming", False)
_path_to_item = kwargs.pop("_path_to_item", ())
_configuration = kwargs.pop("_configuration", None)
_visited_composed_classes = kwargs.pop("_visited_composed_classes", ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments."
% (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
for var_name, var_value in kwargs.items():
if (
var_name not in self.attribute_map
and self._configuration is not None
and self._configuration.discard_unknown_keys
and self.additional_properties_type is None
):
continue
setattr(self, var_name, var_value)
| true | true |
f7f8d3b469cb3c4fabc761ca5ca0ac50691d06a6 | 10,902 | py | Python | old_projects/brachistochrone/graveyard.py | dezren39/manim | 80d7742446c588dc296bd3afb3465a63b63383db | [
"MIT"
] | 1 | 2020-07-05T12:56:31.000Z | 2020-07-05T12:56:31.000Z | old_projects/brachistochrone/graveyard.py | elphasminyato/manim | 8488b621ef3367e6a911354d2765684321fed20e | [
"MIT"
] | 3 | 2021-09-08T02:19:38.000Z | 2022-03-12T00:41:00.000Z | old_projects/brachistochrone/graveyard.py | dezren39/manim | 80d7742446c588dc296bd3afb3465a63b63383db | [
"MIT"
] | 1 | 2020-07-05T12:56:33.000Z | 2020-07-05T12:56:33.000Z | import numpy as np
import itertools as it
from big_ol_pile_of_manim_imports import *
from old_projects.brachistochrone.curves import Cycloid
class MultilayeredGlass(PhotonScene, ZoomedScene):
CONFIG = {
"num_discrete_layers" : 5,
"num_variables" : 3,
"top_color" : BLUE_E,
"bottom_color" : BLUE_A,
"zoomed_canvas_frame_shape" : (5, 5),
"square_color" : GREEN_B,
}
def construct(self):
self.cycloid = Cycloid(end_theta = np.pi)
self.cycloid.set_color(YELLOW)
self.top = self.cycloid.get_top()[1]
self.bottom = self.cycloid.get_bottom()[1]-1
self.generate_layers()
self.generate_discrete_path()
photon_run = self.photon_run_along_path(
self.discrete_path,
run_time = 1,
rate_func = rush_into
)
self.continuous_to_smooth()
self.add(*self.layers)
self.show_layer_variables()
self.play(photon_run)
self.play(ShowCreation(self.discrete_path))
self.isolate_bend_points()
self.clear()
self.add(*self.layers)
self.show_main_equation()
self.ask_continuous_question()
def continuous_to_smooth(self):
self.add(*self.layers)
continuous = self.get_continuous_background()
self.add(continuous)
self.wait()
self.play(ShowCreation(
continuous,
rate_func = lambda t : smooth(1-t)
))
self.remove(continuous)
self.wait()
def get_continuous_background(self):
glass = FilledRectangle(
height = self.top-self.bottom,
width = FRAME_WIDTH,
)
glass.sort_points(lambda p : -p[1])
glass.shift((self.top-glass.get_top()[1])*UP)
glass.set_color_by_gradient(self.top_color, self.bottom_color)
return glass
def generate_layer_info(self):
self.layer_thickness = float(self.top-self.bottom)/self.num_discrete_layers
self.layer_tops = np.arange(
self.top, self.bottom, -self.layer_thickness
)
top_rgb, bottom_rgb = [
np.array(Color(color).get_rgb())
for color in self.top_color, self.bottom_color
]
epsilon = 1./(self.num_discrete_layers-1)
self.layer_colors = [
Color(rgb = interpolate(top_rgb, bottom_rgb, alpha))
for alpha in np.arange(0, 1+epsilon, epsilon)
]
def generate_layers(self):
self.generate_layer_info()
def create_region(top, color):
return Region(
lambda x, y : (y < top) & (y > top-self.layer_thickness),
color = color
)
self.layers = [
create_region(top, color)
for top, color in zip(self.layer_tops, self.layer_colors)
]
def generate_discrete_path(self):
points = self.cycloid.points
tops = list(self.layer_tops)
tops.append(tops[-1]-self.layer_thickness)
indices = [
np.argmin(np.abs(points[:, 1]-top))
for top in tops
]
self.bend_points = points[indices[1:-1]]
self.path_angles = []
self.discrete_path = Mobject1D(
color = YELLOW,
density = 3*DEFAULT_POINT_DENSITY_1D
)
for start, end in zip(indices, indices[1:]):
start_point, end_point = points[start], points[end]
self.discrete_path.add_line(
start_point, end_point
)
self.path_angles.append(
angle_of_vector(start_point-end_point)-np.pi/2
)
self.discrete_path.add_line(
points[end], FRAME_X_RADIUS*RIGHT+(self.layer_tops[-1]-1)*UP
)
def show_layer_variables(self):
layer_top_pairs = zip(
self.layer_tops[:self.num_variables],
self.layer_tops[1:]
)
v_equations = []
start_ys = []
end_ys = []
center_paths = []
braces = []
for (top1, top2), x in zip(layer_top_pairs, it.count(1)):
eq_mob = TexMobject(
["v_%d"%x, "=", "\sqrt{\phantom{y_1}}"],
size = "\\Large"
)
midpoint = UP*(top1+top2)/2
eq_mob.shift(midpoint)
v_eq = eq_mob.split()
center_paths.append(Line(
midpoint+FRAME_X_RADIUS*LEFT,
midpoint+FRAME_X_RADIUS*RIGHT
))
brace_endpoints = Mobject(
Point(self.top*UP+x*RIGHT),
Point(top2*UP+x*RIGHT)
)
brace = Brace(brace_endpoints, RIGHT)
start_y = TexMobject("y_%d"%x, size = "\\Large")
end_y = start_y.copy()
start_y.next_to(brace, RIGHT)
end_y.shift(v_eq[-1].get_center())
end_y.shift(0.2*RIGHT)
v_equations.append(v_eq)
start_ys.append(start_y)
end_ys.append(end_y)
braces.append(brace)
for v_eq, path, time in zip(v_equations, center_paths, [2, 1, 0.5]):
photon_run = self.photon_run_along_path(
path,
rate_func = None
)
self.play(
ShimmerIn(v_eq[0]),
photon_run,
run_time = time
)
self.wait()
for start_y, brace in zip(start_ys, braces):
self.add(start_y)
self.play(GrowFromCenter(brace))
self.wait()
quads = zip(v_equations, start_ys, end_ys, braces)
self.equations = []
for v_eq, start_y, end_y, brace in quads:
self.remove(brace)
self.play(
ShowCreation(v_eq[1]),
ShowCreation(v_eq[2]),
Transform(start_y, end_y)
)
v_eq.append(start_y)
self.equations.append(Mobject(*v_eq))
def isolate_bend_points(self):
arc_radius = 0.1
self.activate_zooming()
little_square = self.get_zoomed_camera_mobject()
for index in range(3):
bend_point = self.bend_points[index]
line = Line(
bend_point+DOWN,
bend_point+UP,
color = WHITE,
density = self.zoom_factor*DEFAULT_POINT_DENSITY_1D
)
angle_arcs = []
for i, rotation in [(index, np.pi/2), (index+1, -np.pi/2)]:
arc = Arc(angle = self.path_angles[i])
arc.scale(arc_radius)
arc.rotate(rotation)
arc.shift(bend_point)
angle_arcs.append(arc)
thetas = []
for i in [index+1, index+2]:
theta = TexMobject("\\theta_%d"%i)
theta.scale(0.5/self.zoom_factor)
vert = UP if i == index+1 else DOWN
horiz = rotate_vector(vert, np.pi/2)
theta.next_to(
Point(bend_point),
horiz,
buff = 0.01
)
theta.shift(1.5*arc_radius*vert)
thetas.append(theta)
figure_marks = [line] + angle_arcs + thetas
self.play(ApplyMethod(
little_square.shift,
bend_point - little_square.get_center(),
run_time = 2
))
self.play(*map(ShowCreation, figure_marks))
self.wait()
equation_frame = little_square.copy()
equation_frame.scale(0.5)
equation_frame.shift(
little_square.get_corner(UP+RIGHT) - \
equation_frame.get_corner(UP+RIGHT)
)
equation_frame.scale_in_place(0.9)
self.show_snells(index+1, equation_frame)
self.remove(*figure_marks)
self.disactivate_zooming()
def show_snells(self, index, frame):
left_text, right_text = [
"\\dfrac{\\sin(\\theta_%d)}{\\phantom{\\sqrt{y_1}}}"%x
for x in index, index+1
]
left, equals, right = TexMobject(
[left_text, "=", right_text]
).split()
vs = []
sqrt_ys = []
for x, numerator in [(index, left), (index+1, right)]:
v, sqrt_y = [
TexMobject(
text, size = "\\Large"
).next_to(numerator, DOWN)
for text in "v_%d"%x, "\\sqrt{y_%d}"%x
]
vs.append(v)
sqrt_ys.append(sqrt_y)
start, end = [
Mobject(
left.copy(), mobs[0], equals.copy(), right.copy(), mobs[1]
).replace(frame)
for mobs in vs, sqrt_ys
]
self.add(start)
self.wait(2)
self.play(Transform(
start, end,
path_func = counterclockwise_path()
))
self.wait(2)
self.remove(start, end)
def show_main_equation(self):
self.equation = TexMobject("""
\\dfrac{\\sin(\\theta)}{\\sqrt{y}} =
\\text{constant}
""")
self.equation.shift(LEFT)
self.equation.shift(
(self.layer_tops[0]-self.equation.get_top())*UP
)
self.add(self.equation)
self.wait()
def ask_continuous_question(self):
continuous = self.get_continuous_background()
line = Line(
UP, DOWN,
density = self.zoom_factor*DEFAULT_POINT_DENSITY_1D
)
theta = TexMobject("\\theta")
theta.scale(0.5/self.zoom_factor)
self.play(
ShowCreation(continuous),
Animation(self.equation)
)
self.remove(*self.layers)
self.play(ShowCreation(self.cycloid))
self.activate_zooming()
little_square = self.get_zoomed_camera_mobject()
self.add(line)
indices = np.arange(
0, self.cycloid.get_num_points()-1, 10
)
for index in indices:
point = self.cycloid.points[index]
next_point = self.cycloid.points[index+1]
angle = angle_of_vector(point - next_point)
for mob in little_square, line:
mob.shift(point - mob.get_center())
arc = Arc(angle-np.pi/2, start_angle = np.pi/2)
arc.scale(0.1)
arc.shift(point)
self.add(arc)
if angle > np.pi/2 + np.pi/6:
vect_angle = interpolate(np.pi/2, angle, 0.5)
vect = rotate_vector(RIGHT, vect_angle)
theta.center()
theta.shift(point)
theta.shift(0.15*vect)
self.add(theta)
self.wait(self.frame_duration)
self.remove(arc) | 33.441718 | 83 | 0.52495 | import numpy as np
import itertools as it
from big_ol_pile_of_manim_imports import *
from old_projects.brachistochrone.curves import Cycloid
class MultilayeredGlass(PhotonScene, ZoomedScene):
CONFIG = {
"num_discrete_layers" : 5,
"num_variables" : 3,
"top_color" : BLUE_E,
"bottom_color" : BLUE_A,
"zoomed_canvas_frame_shape" : (5, 5),
"square_color" : GREEN_B,
}
def construct(self):
self.cycloid = Cycloid(end_theta = np.pi)
self.cycloid.set_color(YELLOW)
self.top = self.cycloid.get_top()[1]
self.bottom = self.cycloid.get_bottom()[1]-1
self.generate_layers()
self.generate_discrete_path()
photon_run = self.photon_run_along_path(
self.discrete_path,
run_time = 1,
rate_func = rush_into
)
self.continuous_to_smooth()
self.add(*self.layers)
self.show_layer_variables()
self.play(photon_run)
self.play(ShowCreation(self.discrete_path))
self.isolate_bend_points()
self.clear()
self.add(*self.layers)
self.show_main_equation()
self.ask_continuous_question()
def continuous_to_smooth(self):
self.add(*self.layers)
continuous = self.get_continuous_background()
self.add(continuous)
self.wait()
self.play(ShowCreation(
continuous,
rate_func = lambda t : smooth(1-t)
))
self.remove(continuous)
self.wait()
def get_continuous_background(self):
glass = FilledRectangle(
height = self.top-self.bottom,
width = FRAME_WIDTH,
)
glass.sort_points(lambda p : -p[1])
glass.shift((self.top-glass.get_top()[1])*UP)
glass.set_color_by_gradient(self.top_color, self.bottom_color)
return glass
def generate_layer_info(self):
self.layer_thickness = float(self.top-self.bottom)/self.num_discrete_layers
self.layer_tops = np.arange(
self.top, self.bottom, -self.layer_thickness
)
top_rgb, bottom_rgb = [
np.array(Color(color).get_rgb())
for color in self.top_color, self.bottom_color
]
epsilon = 1./(self.num_discrete_layers-1)
self.layer_colors = [
Color(rgb = interpolate(top_rgb, bottom_rgb, alpha))
for alpha in np.arange(0, 1+epsilon, epsilon)
]
def generate_layers(self):
self.generate_layer_info()
def create_region(top, color):
return Region(
lambda x, y : (y < top) & (y > top-self.layer_thickness),
color = color
)
self.layers = [
create_region(top, color)
for top, color in zip(self.layer_tops, self.layer_colors)
]
def generate_discrete_path(self):
points = self.cycloid.points
tops = list(self.layer_tops)
tops.append(tops[-1]-self.layer_thickness)
indices = [
np.argmin(np.abs(points[:, 1]-top))
for top in tops
]
self.bend_points = points[indices[1:-1]]
self.path_angles = []
self.discrete_path = Mobject1D(
color = YELLOW,
density = 3*DEFAULT_POINT_DENSITY_1D
)
for start, end in zip(indices, indices[1:]):
start_point, end_point = points[start], points[end]
self.discrete_path.add_line(
start_point, end_point
)
self.path_angles.append(
angle_of_vector(start_point-end_point)-np.pi/2
)
self.discrete_path.add_line(
points[end], FRAME_X_RADIUS*RIGHT+(self.layer_tops[-1]-1)*UP
)
def show_layer_variables(self):
layer_top_pairs = zip(
self.layer_tops[:self.num_variables],
self.layer_tops[1:]
)
v_equations = []
start_ys = []
end_ys = []
center_paths = []
braces = []
for (top1, top2), x in zip(layer_top_pairs, it.count(1)):
eq_mob = TexMobject(
["v_%d"%x, "=", "\sqrt{\phantom{y_1}}"],
size = "\\Large"
)
midpoint = UP*(top1+top2)/2
eq_mob.shift(midpoint)
v_eq = eq_mob.split()
center_paths.append(Line(
midpoint+FRAME_X_RADIUS*LEFT,
midpoint+FRAME_X_RADIUS*RIGHT
))
brace_endpoints = Mobject(
Point(self.top*UP+x*RIGHT),
Point(top2*UP+x*RIGHT)
)
brace = Brace(brace_endpoints, RIGHT)
start_y = TexMobject("y_%d"%x, size = "\\Large")
end_y = start_y.copy()
start_y.next_to(brace, RIGHT)
end_y.shift(v_eq[-1].get_center())
end_y.shift(0.2*RIGHT)
v_equations.append(v_eq)
start_ys.append(start_y)
end_ys.append(end_y)
braces.append(brace)
for v_eq, path, time in zip(v_equations, center_paths, [2, 1, 0.5]):
photon_run = self.photon_run_along_path(
path,
rate_func = None
)
self.play(
ShimmerIn(v_eq[0]),
photon_run,
run_time = time
)
self.wait()
for start_y, brace in zip(start_ys, braces):
self.add(start_y)
self.play(GrowFromCenter(brace))
self.wait()
quads = zip(v_equations, start_ys, end_ys, braces)
self.equations = []
for v_eq, start_y, end_y, brace in quads:
self.remove(brace)
self.play(
ShowCreation(v_eq[1]),
ShowCreation(v_eq[2]),
Transform(start_y, end_y)
)
v_eq.append(start_y)
self.equations.append(Mobject(*v_eq))
def isolate_bend_points(self):
arc_radius = 0.1
self.activate_zooming()
little_square = self.get_zoomed_camera_mobject()
for index in range(3):
bend_point = self.bend_points[index]
line = Line(
bend_point+DOWN,
bend_point+UP,
color = WHITE,
density = self.zoom_factor*DEFAULT_POINT_DENSITY_1D
)
angle_arcs = []
for i, rotation in [(index, np.pi/2), (index+1, -np.pi/2)]:
arc = Arc(angle = self.path_angles[i])
arc.scale(arc_radius)
arc.rotate(rotation)
arc.shift(bend_point)
angle_arcs.append(arc)
thetas = []
for i in [index+1, index+2]:
theta = TexMobject("\\theta_%d"%i)
theta.scale(0.5/self.zoom_factor)
vert = UP if i == index+1 else DOWN
horiz = rotate_vector(vert, np.pi/2)
theta.next_to(
Point(bend_point),
horiz,
buff = 0.01
)
theta.shift(1.5*arc_radius*vert)
thetas.append(theta)
figure_marks = [line] + angle_arcs + thetas
self.play(ApplyMethod(
little_square.shift,
bend_point - little_square.get_center(),
run_time = 2
))
self.play(*map(ShowCreation, figure_marks))
self.wait()
equation_frame = little_square.copy()
equation_frame.scale(0.5)
equation_frame.shift(
little_square.get_corner(UP+RIGHT) - \
equation_frame.get_corner(UP+RIGHT)
)
equation_frame.scale_in_place(0.9)
self.show_snells(index+1, equation_frame)
self.remove(*figure_marks)
self.disactivate_zooming()
def show_snells(self, index, frame):
left_text, right_text = [
"\\dfrac{\\sin(\\theta_%d)}{\\phantom{\\sqrt{y_1}}}"%x
for x in index, index+1
]
left, equals, right = TexMobject(
[left_text, "=", right_text]
).split()
vs = []
sqrt_ys = []
for x, numerator in [(index, left), (index+1, right)]:
v, sqrt_y = [
TexMobject(
text, size = "\\Large"
).next_to(numerator, DOWN)
for text in "v_%d"%x, "\\sqrt{y_%d}"%x
]
vs.append(v)
sqrt_ys.append(sqrt_y)
start, end = [
Mobject(
left.copy(), mobs[0], equals.copy(), right.copy(), mobs[1]
).replace(frame)
for mobs in vs, sqrt_ys
]
self.add(start)
self.wait(2)
self.play(Transform(
start, end,
path_func = counterclockwise_path()
))
self.wait(2)
self.remove(start, end)
def show_main_equation(self):
self.equation = TexMobject("""
\\dfrac{\\sin(\\theta)}{\\sqrt{y}} =
\\text{constant}
""")
self.equation.shift(LEFT)
self.equation.shift(
(self.layer_tops[0]-self.equation.get_top())*UP
)
self.add(self.equation)
self.wait()
def ask_continuous_question(self):
continuous = self.get_continuous_background()
line = Line(
UP, DOWN,
density = self.zoom_factor*DEFAULT_POINT_DENSITY_1D
)
theta = TexMobject("\\theta")
theta.scale(0.5/self.zoom_factor)
self.play(
ShowCreation(continuous),
Animation(self.equation)
)
self.remove(*self.layers)
self.play(ShowCreation(self.cycloid))
self.activate_zooming()
little_square = self.get_zoomed_camera_mobject()
self.add(line)
indices = np.arange(
0, self.cycloid.get_num_points()-1, 10
)
for index in indices:
point = self.cycloid.points[index]
next_point = self.cycloid.points[index+1]
angle = angle_of_vector(point - next_point)
for mob in little_square, line:
mob.shift(point - mob.get_center())
arc = Arc(angle-np.pi/2, start_angle = np.pi/2)
arc.scale(0.1)
arc.shift(point)
self.add(arc)
if angle > np.pi/2 + np.pi/6:
vect_angle = interpolate(np.pi/2, angle, 0.5)
vect = rotate_vector(RIGHT, vect_angle)
theta.center()
theta.shift(point)
theta.shift(0.15*vect)
self.add(theta)
self.wait(self.frame_duration)
self.remove(arc) | false | true |
f7f8d4a4578b4d6e0ef086afe1aaa973893c6861 | 4,388 | py | Python | models/transformer_fine_tune/kbert_model.py | ktodorov/eval-historical-texts | e2994d594525d1d92056a6398935376a96659abb | [
"MIT"
] | 9 | 2020-08-27T15:03:46.000Z | 2022-01-02T10:48:35.000Z | models/transformer_fine_tune/kbert_model.py | ktodorov/eval-historical-texts | e2994d594525d1d92056a6398935376a96659abb | [
"MIT"
] | 16 | 2020-09-12T17:37:59.000Z | 2020-11-18T10:36:32.000Z | models/transformer_fine_tune/kbert_model.py | ktodorov/eval-historical-texts | e2994d594525d1d92056a6398935376a96659abb | [
"MIT"
] | 1 | 2022-03-08T16:16:52.000Z | 2022-03-08T16:16:52.000Z | import os
from typing import Callable
from overrides import overrides
from transformers import BertForMaskedLM, BertPreTrainedModel, BertConfig
from entities.model_checkpoint import ModelCheckpoint
from entities.metric import Metric
from models.model_base import ModelBase
from services.arguments.semantic_arguments_service import SemanticArgumentsService
from services.data_service import DataService
class KBertModel(ModelBase):
def __init__(
self,
arguments_service: SemanticArgumentsService,
data_service: DataService,
output_hidden_states: bool = False):
super(KBertModel, self).__init__(data_service, arguments_service)
self._output_hidden_states = output_hidden_states
if arguments_service.resume_training or arguments_service.evaluate or arguments_service.run_experiments:
self._bert_model = None
else:
config = BertConfig.from_pretrained(arguments_service.pretrained_weights)
config.output_hidden_states = output_hidden_states
self._bert_model: BertPreTrainedModel = self._model_type.from_pretrained(
arguments_service.pretrained_weights, config=config)
self._arguments_service = arguments_service
@overrides
def forward(self, input_batch, **kwargs):
if isinstance(input_batch, tuple):
(inputs, labels) = input_batch
outputs = self._bert_model.forward(inputs, masked_lm_labels=labels)
return outputs[0]
else:
outputs = self._bert_model.forward(input_batch)
return outputs[1][-1]
@overrides
def named_parameters(self):
return self._bert_model.named_parameters()
@overrides
def parameters(self):
return self._bert_model.parameters()
@overrides
def compare_metric(self, best_metric: Metric, new_metrics: Metric) -> bool:
if best_metric.is_new or best_metric.get_current_loss() > new_metrics.get_current_loss():
return True
return False
@overrides
def save(
self,
path: str,
epoch: int,
iteration: int,
best_metrics: object,
resets_left: int,
name_prefix: str = None) -> bool:
checkpoint_name = self._arguments_service.checkpoint_name
if checkpoint_name:
name_prefix = f'{name_prefix}_{checkpoint_name}'
saved = super().save(path, epoch, iteration, best_metrics,
resets_left, name_prefix, save_model_dict=False)
if not saved:
return saved
pretrained_weights_path = self._get_pretrained_path(
path, name_prefix, create_if_missing=True)
self._bert_model.save_pretrained(pretrained_weights_path)
return saved
@overrides
def load(
self,
path: str,
name_prefix: str = None,
load_model_dict: bool = True,
load_model_only: bool = False) -> ModelCheckpoint:
checkpoint_name = self._arguments_service.checkpoint_name
if checkpoint_name:
name_prefix = f'{name_prefix}_{checkpoint_name}'
model_checkpoint = super().load(path, name_prefix, load_model_dict=False)
if not load_model_only and not model_checkpoint:
return None
if load_model_dict:
self._load_kbert_model(path, name_prefix)
return model_checkpoint
@property
def _model_type(self) -> BertPreTrainedModel:
return BertForMaskedLM
def _load_kbert_model(self, path: str, name_prefix: str):
pretrained_weights_path = self._get_pretrained_path(path, name_prefix)
config = BertConfig.from_pretrained(pretrained_weights_path)
config.output_hidden_states = True
self._bert_model = self._model_type.from_pretrained(
pretrained_weights_path, config=config).to(self._arguments_service.device)
def _get_pretrained_path(self, path: str, name_prefix: str, create_if_missing: bool = False):
file_name = f'{name_prefix}_pretrained_weights'
pretrained_weights_path = os.path.join(path, file_name)
if create_if_missing and not os.path.exists(pretrained_weights_path):
os.mkdir(pretrained_weights_path)
return pretrained_weights_path | 33.242424 | 112 | 0.682088 | import os
from typing import Callable
from overrides import overrides
from transformers import BertForMaskedLM, BertPreTrainedModel, BertConfig
from entities.model_checkpoint import ModelCheckpoint
from entities.metric import Metric
from models.model_base import ModelBase
from services.arguments.semantic_arguments_service import SemanticArgumentsService
from services.data_service import DataService
class KBertModel(ModelBase):
def __init__(
self,
arguments_service: SemanticArgumentsService,
data_service: DataService,
output_hidden_states: bool = False):
super(KBertModel, self).__init__(data_service, arguments_service)
self._output_hidden_states = output_hidden_states
if arguments_service.resume_training or arguments_service.evaluate or arguments_service.run_experiments:
self._bert_model = None
else:
config = BertConfig.from_pretrained(arguments_service.pretrained_weights)
config.output_hidden_states = output_hidden_states
self._bert_model: BertPreTrainedModel = self._model_type.from_pretrained(
arguments_service.pretrained_weights, config=config)
self._arguments_service = arguments_service
@overrides
def forward(self, input_batch, **kwargs):
if isinstance(input_batch, tuple):
(inputs, labels) = input_batch
outputs = self._bert_model.forward(inputs, masked_lm_labels=labels)
return outputs[0]
else:
outputs = self._bert_model.forward(input_batch)
return outputs[1][-1]
@overrides
def named_parameters(self):
return self._bert_model.named_parameters()
@overrides
def parameters(self):
return self._bert_model.parameters()
@overrides
def compare_metric(self, best_metric: Metric, new_metrics: Metric) -> bool:
if best_metric.is_new or best_metric.get_current_loss() > new_metrics.get_current_loss():
return True
return False
@overrides
def save(
self,
path: str,
epoch: int,
iteration: int,
best_metrics: object,
resets_left: int,
name_prefix: str = None) -> bool:
checkpoint_name = self._arguments_service.checkpoint_name
if checkpoint_name:
name_prefix = f'{name_prefix}_{checkpoint_name}'
saved = super().save(path, epoch, iteration, best_metrics,
resets_left, name_prefix, save_model_dict=False)
if not saved:
return saved
pretrained_weights_path = self._get_pretrained_path(
path, name_prefix, create_if_missing=True)
self._bert_model.save_pretrained(pretrained_weights_path)
return saved
@overrides
def load(
self,
path: str,
name_prefix: str = None,
load_model_dict: bool = True,
load_model_only: bool = False) -> ModelCheckpoint:
checkpoint_name = self._arguments_service.checkpoint_name
if checkpoint_name:
name_prefix = f'{name_prefix}_{checkpoint_name}'
model_checkpoint = super().load(path, name_prefix, load_model_dict=False)
if not load_model_only and not model_checkpoint:
return None
if load_model_dict:
self._load_kbert_model(path, name_prefix)
return model_checkpoint
@property
def _model_type(self) -> BertPreTrainedModel:
return BertForMaskedLM
def _load_kbert_model(self, path: str, name_prefix: str):
pretrained_weights_path = self._get_pretrained_path(path, name_prefix)
config = BertConfig.from_pretrained(pretrained_weights_path)
config.output_hidden_states = True
self._bert_model = self._model_type.from_pretrained(
pretrained_weights_path, config=config).to(self._arguments_service.device)
def _get_pretrained_path(self, path: str, name_prefix: str, create_if_missing: bool = False):
file_name = f'{name_prefix}_pretrained_weights'
pretrained_weights_path = os.path.join(path, file_name)
if create_if_missing and not os.path.exists(pretrained_weights_path):
os.mkdir(pretrained_weights_path)
return pretrained_weights_path | true | true |
f7f8d53ff94d325fea3cbf1ba33884d9a79bcf0c | 851 | py | Python | LOOCV.py | FrieAT/MD_CompressedWavelet | 82bd10edd611485cd5f0b81da744e07a3b7c98eb | [
"MIT"
] | 2 | 2020-03-28T11:50:45.000Z | 2020-12-08T13:36:26.000Z | LOOCV.py | FrieAT/MD_CompressedWavelet | 82bd10edd611485cd5f0b81da744e07a3b7c98eb | [
"MIT"
] | 2 | 2020-04-20T11:12:59.000Z | 2020-05-11T05:37:36.000Z | LOOCV.py | FrieAT/MD_CompressedWavelet | 82bd10edd611485cd5f0b81da744e07a3b7c98eb | [
"MIT"
] | null | null | null |
from IProcess import IProcess, EDataType
from ImageData import PipelineManager
#from euclideanDistance import euclideanDistance
#from kNearestNeighbour import kNearestNeighbour
class LOOCV(IProcess):
def __init__(self):
IProcess.__init__(self)
pass
def toId(self):
return self.getTypeAsString()
def getType(self):
return EDataType.LOOCV
# Produce every combination of imageData.data
# Every entry contains the same data array, but with a different index-0 element.
# So we produce n * (1, (n - 1)) set for a future Leave-One-Out-Cross-Validation.
def do(self, imageData):
IProcess.do(self, imageData)
self.data = []
for i in range(len(imageData.data)):
p = PipelineManager()
p.data = imageData.data.copy()
chosenOne = p.data.pop(i)
p.data.insert(0, chosenOne)
self.data.append(p)
return self
| 21.275 | 82 | 0.726204 |
from IProcess import IProcess, EDataType
from ImageData import PipelineManager
class LOOCV(IProcess):
def __init__(self):
IProcess.__init__(self)
pass
def toId(self):
return self.getTypeAsString()
def getType(self):
return EDataType.LOOCV
def do(self, imageData):
IProcess.do(self, imageData)
self.data = []
for i in range(len(imageData.data)):
p = PipelineManager()
p.data = imageData.data.copy()
chosenOne = p.data.pop(i)
p.data.insert(0, chosenOne)
self.data.append(p)
return self
| true | true |
f7f8d5b54a4ba04256f723af36d9fa49bcca3984 | 779 | py | Python | issues/20160522 #20 constraints/vertex-debug.py | jpsantos-mf/ezdxf | 2b542a551b2cfc3c0920a5dbf302ff58cea90fbd | [
"MIT"
] | 1 | 2021-06-05T09:15:15.000Z | 2021-06-05T09:15:15.000Z | issues/20160522 #20 constraints/vertex-debug.py | jpsantos-mf/ezdxf | 2b542a551b2cfc3c0920a5dbf302ff58cea90fbd | [
"MIT"
] | null | null | null | issues/20160522 #20 constraints/vertex-debug.py | jpsantos-mf/ezdxf | 2b542a551b2cfc3c0920a5dbf302ff58cea90fbd | [
"MIT"
] | null | null | null | import ezdxf
import sys
def main():
print 'Python version is: '+(sys.version)
print 'ezdxf version is: ' + ezdxf.__version__
print '\nCoordinate for layer 0'
find_coordinates(filename='test.dxf',layer_name='0')
print '\nCoordinate for layer 1'
find_coordinates(filename='test.dxf',layer_name='Layer 1')
print '\nCoordinate for layer 2'
find_coordinates(filename='test.dxf',layer_name='Layer 2')
def find_coordinates(filename='test.dxf', layer_name='0'):
dwg_dxf = ezdxf.readfile(filename)
for e in dwg_dxf.entities:
if layer_name in e.get_dxf_attrib(key='layer') and e.dxftype() == 'LWPOLYLINE':
polygon_points = []
for i in e.get_rstrip_points():
polygon_points.append(i)
print polygon_points
if __name__ == '__main__':
main() | 21.638889 | 81 | 0.712452 | import ezdxf
import sys
def main():
print 'Python version is: '+(sys.version)
print 'ezdxf version is: ' + ezdxf.__version__
print '\nCoordinate for layer 0'
find_coordinates(filename='test.dxf',layer_name='0')
print '\nCoordinate for layer 1'
find_coordinates(filename='test.dxf',layer_name='Layer 1')
print '\nCoordinate for layer 2'
find_coordinates(filename='test.dxf',layer_name='Layer 2')
def find_coordinates(filename='test.dxf', layer_name='0'):
dwg_dxf = ezdxf.readfile(filename)
for e in dwg_dxf.entities:
if layer_name in e.get_dxf_attrib(key='layer') and e.dxftype() == 'LWPOLYLINE':
polygon_points = []
for i in e.get_rstrip_points():
polygon_points.append(i)
print polygon_points
if __name__ == '__main__':
main() | false | true |
f7f8d60c9eff13bbebc60cccf2f48e503e89357c | 2,570 | py | Python | discordbot.py | RyoYukkuri/discordpy-startup | d59d6a4b93663699fd3d5e68c16c441379140d1f | [
"MIT"
] | null | null | null | discordbot.py | RyoYukkuri/discordpy-startup | d59d6a4b93663699fd3d5e68c16c441379140d1f | [
"MIT"
] | null | null | null | discordbot.py | RyoYukkuri/discordpy-startup | d59d6a4b93663699fd3d5e68c16c441379140d1f | [
"MIT"
] | null | null | null | import discord
from googletrans import Translator
TOKEN = os.environ['DISCORD_BOT_TOKEN']
client = discord.Client()
translator = Translator()
@client.event
async def on_ready():
print('==============================')
print('ログインしました・。・v')
print('ユーザー名: ' + client.user.name)
print(client.user.id)
print('==============================')
await client.change_presence(activity=discord.Game(name="[ ! ] ただの翻訳botだよ(*'▽')", type=1))
@client.event
async def on_message(message):
if message.author.bot:
return
if message.content.startswith('!trans'):
say = message.content
say = say[7:]
if say.find('-') == -1:
str = say
detact = translator.detect(str)
befor_lang = detact.lang
if befor_lang == 'ja':
convert_string = translator.translate(str, src=befor_lang, dest='en')
embed = discord.Embed(title='変換結果', color=0xffff00)
embed.add_field(name='Before', value=str)
embed.add_field(name='After', value=convert_string.text, inline=False)
await message.channel.send(embed=embed)
else:
convert_string = translator.translate(str, src=befor_lang, dest='ja')
embed = discord.Embed(title='変換結果', color=0xffff00)
embed.add_field(name='Before', value=str)
embed.add_field(name='After', value=convert_string.text, inline=False)
await message.channel.send(embed=embed)
else:
# !trans [A(元言語(Cの言語))]-[B(変換後言語)]=[C(AからBに翻訳したい文章)]
# 例) !trans ja-el=私はこうだと思います。
# 結果→ Before: 私はこうだと思います。 After: Νομίζω ότι είμαι αυτό.
trans, str = list(say.split('='))
befor_lang, after_lang = list(trans.split('-'))
convert_string = translator.translate(str, src=befor_lang, dest=after_lang)
embed = discord.Embed(title='変換結果', color=0xffff00)
embed.add_field(name='Before', value=str)
embed.add_field(name='After', value=convert_string.text, inline=False)
await message.channel.send(embed=embed)
if message.content.startswith('!detect'):
# !detect [検証したい文章]
# !detect こんにちは!
# 結果→ この文字列の言語は ja です。
say = message.content
s = say[8:]
detect = translator.detect(s)
m = 'この文字列の言語は **' + detect.lang + '** です。'
await message.channel.send(m)
client.run(TOKEN) | 40.15625 | 95 | 0.563035 | import discord
from googletrans import Translator
TOKEN = os.environ['DISCORD_BOT_TOKEN']
client = discord.Client()
translator = Translator()
@client.event
async def on_ready():
print('==============================')
print('ログインしました・。・v')
print('ユーザー名: ' + client.user.name)
print(client.user.id)
print('==============================')
await client.change_presence(activity=discord.Game(name="[ ! ] ただの翻訳botだよ(*'▽')", type=1))
@client.event
async def on_message(message):
if message.author.bot:
return
if message.content.startswith('!trans'):
say = message.content
say = say[7:]
if say.find('-') == -1:
str = say
detact = translator.detect(str)
befor_lang = detact.lang
if befor_lang == 'ja':
convert_string = translator.translate(str, src=befor_lang, dest='en')
embed = discord.Embed(title='変換結果', color=0xffff00)
embed.add_field(name='Before', value=str)
embed.add_field(name='After', value=convert_string.text, inline=False)
await message.channel.send(embed=embed)
else:
convert_string = translator.translate(str, src=befor_lang, dest='ja')
embed = discord.Embed(title='変換結果', color=0xffff00)
embed.add_field(name='Before', value=str)
embed.add_field(name='After', value=convert_string.text, inline=False)
await message.channel.send(embed=embed)
else:
trans, str = list(say.split('='))
befor_lang, after_lang = list(trans.split('-'))
convert_string = translator.translate(str, src=befor_lang, dest=after_lang)
embed = discord.Embed(title='変換結果', color=0xffff00)
embed.add_field(name='Before', value=str)
embed.add_field(name='After', value=convert_string.text, inline=False)
await message.channel.send(embed=embed)
if message.content.startswith('!detect'):
say = message.content
s = say[8:]
detect = translator.detect(s)
m = 'この文字列の言語は **' + detect.lang + '** です。'
await message.channel.send(m)
client.run(TOKEN) | true | true |
f7f8d67589fc3d0bad8b49b75a05f4c2011463fe | 7,744 | py | Python | tests/components/sonos/conftest.py | emes30/core | 489d85d862789523788bcc539a2701400052ae26 | [
"Apache-2.0"
] | 2 | 2021-07-30T19:15:52.000Z | 2021-07-30T19:16:00.000Z | tests/components/sonos/conftest.py | emes30/core | 489d85d862789523788bcc539a2701400052ae26 | [
"Apache-2.0"
] | 74 | 2020-08-05T07:20:27.000Z | 2022-03-23T12:47:28.000Z | tests/components/sonos/conftest.py | marecabo/home-assistant | e33774a61e7fcc88aff752dfa4618dd26a746872 | [
"Apache-2.0"
] | 1 | 2021-07-30T19:16:02.000Z | 2021-07-30T19:16:02.000Z | """Configuration for Sonos tests."""
from unittest.mock import AsyncMock, MagicMock, Mock, patch as patch
import pytest
from homeassistant.components import ssdp
from homeassistant.components.media_player import DOMAIN as MP_DOMAIN
from homeassistant.components.sonos import DOMAIN
from homeassistant.const import CONF_HOSTS
from tests.common import MockConfigEntry
class SonosMockService:
"""Mock a Sonos Service used in callbacks."""
def __init__(self, service_type):
"""Initialize the instance."""
self.service_type = service_type
self.subscribe = AsyncMock()
class SonosMockEvent:
"""Mock a sonos Event used in callbacks."""
def __init__(self, soco, service, variables):
"""Initialize the instance."""
self.sid = f"{soco.uid}_sub0000000001"
self.seq = "0"
self.timestamp = 1621000000.0
self.service = service
self.variables = variables
def increment_variable(self, var_name):
"""Increment the value of the var_name key in variables dict attribute.
Assumes value has a format of <str>:<int>.
"""
base, count = self.variables[var_name].split(":")
newcount = int(count) + 1
self.variables[var_name] = ":".join([base, str(newcount)])
return self.variables[var_name]
@pytest.fixture(name="config_entry")
def config_entry_fixture():
"""Create a mock Sonos config entry."""
return MockConfigEntry(domain=DOMAIN, title="Sonos")
@pytest.fixture(name="soco")
def soco_fixture(music_library, speaker_info, battery_info, alarm_clock):
"""Create a mock soco SoCo fixture."""
with patch("homeassistant.components.sonos.SoCo", autospec=True) as mock, patch(
"socket.gethostbyname", return_value="192.168.42.2"
):
mock_soco = mock.return_value
mock_soco.ip_address = "192.168.42.2"
mock_soco.uid = "RINCON_test"
mock_soco.play_mode = "NORMAL"
mock_soco.music_library = music_library
mock_soco.get_speaker_info.return_value = speaker_info
mock_soco.avTransport = SonosMockService("AVTransport")
mock_soco.renderingControl = SonosMockService("RenderingControl")
mock_soco.zoneGroupTopology = SonosMockService("ZoneGroupTopology")
mock_soco.contentDirectory = SonosMockService("ContentDirectory")
mock_soco.deviceProperties = SonosMockService("DeviceProperties")
mock_soco.alarmClock = alarm_clock
mock_soco.mute = False
mock_soco.night_mode = True
mock_soco.dialog_mode = True
mock_soco.volume = 19
mock_soco.bass = 1
mock_soco.treble = -1
mock_soco.sub_enabled = False
mock_soco.surround_enabled = True
mock_soco.soundbar_audio_input_format = "Dolby 5.1"
mock_soco.get_battery_info.return_value = battery_info
mock_soco.all_zones = [mock_soco]
yield mock_soco
@pytest.fixture(autouse=True)
async def silent_ssdp_scanner(hass):
"""Start SSDP component and get Scanner, prevent actual SSDP traffic."""
with patch(
"homeassistant.components.ssdp.Scanner._async_start_ssdp_listeners"
), patch("homeassistant.components.ssdp.Scanner._async_stop_ssdp_listeners"), patch(
"homeassistant.components.ssdp.Scanner.async_scan"
):
yield
@pytest.fixture(name="discover", autouse=True)
def discover_fixture(soco):
"""Create a mock soco discover fixture."""
async def do_callback(hass, callback, *args, **kwargs):
await callback(
ssdp.SsdpServiceInfo(
ssdp_location=f"http://{soco.ip_address}/",
ssdp_st="urn:schemas-upnp-org:device:ZonePlayer:1",
ssdp_usn=f"uuid:{soco.uid}_MR::urn:schemas-upnp-org:service:GroupRenderingControl:1",
upnp={
ssdp.ATTR_UPNP_UDN: f"uuid:{soco.uid}",
},
),
ssdp.SsdpChange.ALIVE,
)
return MagicMock()
with patch(
"homeassistant.components.ssdp.async_register_callback", side_effect=do_callback
) as mock:
yield mock
@pytest.fixture(name="config")
def config_fixture():
"""Create hass config fixture."""
return {DOMAIN: {MP_DOMAIN: {CONF_HOSTS: ["192.168.42.1"]}}}
@pytest.fixture(name="music_library")
def music_library_fixture():
"""Create music_library fixture."""
music_library = MagicMock()
music_library.get_sonos_favorites.return_value.update_id = 1
return music_library
@pytest.fixture(name="alarm_clock")
def alarm_clock_fixture():
"""Create alarmClock fixture."""
alarm_clock = SonosMockService("AlarmClock")
alarm_clock.ListAlarms = Mock()
alarm_clock.ListAlarms.return_value = {
"CurrentAlarmListVersion": "RINCON_test:14",
"CurrentAlarmList": "<Alarms>"
'<Alarm ID="14" StartTime="07:00:00" Duration="02:00:00" Recurrence="DAILY" '
'Enabled="1" RoomUUID="RINCON_test" ProgramURI="x-rincon-buzzer:0" '
'ProgramMetaData="" PlayMode="SHUFFLE_NOREPEAT" Volume="25" '
'IncludeLinkedZones="0"/>'
"</Alarms>",
}
return alarm_clock
@pytest.fixture(name="alarm_clock_extended")
def alarm_clock_fixture_extended():
"""Create alarmClock fixture."""
alarm_clock = SonosMockService("AlarmClock")
alarm_clock.ListAlarms = Mock()
alarm_clock.ListAlarms.return_value = {
"CurrentAlarmListVersion": "RINCON_test:15",
"CurrentAlarmList": "<Alarms>"
'<Alarm ID="14" StartTime="07:00:00" Duration="02:00:00" Recurrence="DAILY" '
'Enabled="1" RoomUUID="RINCON_test" ProgramURI="x-rincon-buzzer:0" '
'ProgramMetaData="" PlayMode="SHUFFLE_NOREPEAT" Volume="25" '
'IncludeLinkedZones="0"/>'
'<Alarm ID="15" StartTime="07:00:00" Duration="02:00:00" '
'Recurrence="DAILY" Enabled="1" RoomUUID="RINCON_test" '
'ProgramURI="x-rincon-buzzer:0" ProgramMetaData="" PlayMode="SHUFFLE_NOREPEAT" '
'Volume="25" IncludeLinkedZones="0"/>'
"</Alarms>",
}
return alarm_clock
@pytest.fixture(name="speaker_info")
def speaker_info_fixture():
"""Create speaker_info fixture."""
return {
"zone_name": "Zone A",
"uid": "RINCON_test",
"model_name": "Model Name",
"software_version": "49.2-64250",
"mac_address": "00-11-22-33-44-55",
"display_version": "13.1",
}
@pytest.fixture(name="battery_info")
def battery_info_fixture():
"""Create battery_info fixture."""
return {
"Health": "GREEN",
"Level": 100,
"Temperature": "NORMAL",
"PowerSource": "SONOS_CHARGING_RING",
}
@pytest.fixture(name="battery_event")
def battery_event_fixture(soco):
"""Create battery_event fixture."""
variables = {
"zone_name": "Zone A",
"more_info": "BattChg:NOT_CHARGING,RawBattPct:100,BattPct:100,BattTmp:25",
}
return SonosMockEvent(soco, soco.deviceProperties, variables)
@pytest.fixture(name="alarm_event")
def alarm_event_fixture(soco):
"""Create alarm_event fixture."""
variables = {
"time_zone": "ffc40a000503000003000502ffc4",
"time_server": "0.sonostime.pool.ntp.org,1.sonostime.pool.ntp.org,2.sonostime.pool.ntp.org,3.sonostime.pool.ntp.org",
"time_generation": "20000001",
"alarm_list_version": "RINCON_test:1",
"time_format": "INV",
"date_format": "INV",
"daily_index_refresh_time": None,
}
return SonosMockEvent(soco, soco.alarmClock, variables)
@pytest.fixture(autouse=True)
def mock_get_source_ip(mock_get_source_ip):
"""Mock network util's async_get_source_ip in all sonos tests."""
return mock_get_source_ip
| 34.571429 | 125 | 0.668259 | from unittest.mock import AsyncMock, MagicMock, Mock, patch as patch
import pytest
from homeassistant.components import ssdp
from homeassistant.components.media_player import DOMAIN as MP_DOMAIN
from homeassistant.components.sonos import DOMAIN
from homeassistant.const import CONF_HOSTS
from tests.common import MockConfigEntry
class SonosMockService:
def __init__(self, service_type):
self.service_type = service_type
self.subscribe = AsyncMock()
class SonosMockEvent:
def __init__(self, soco, service, variables):
self.sid = f"{soco.uid}_sub0000000001"
self.seq = "0"
self.timestamp = 1621000000.0
self.service = service
self.variables = variables
def increment_variable(self, var_name):
base, count = self.variables[var_name].split(":")
newcount = int(count) + 1
self.variables[var_name] = ":".join([base, str(newcount)])
return self.variables[var_name]
@pytest.fixture(name="config_entry")
def config_entry_fixture():
return MockConfigEntry(domain=DOMAIN, title="Sonos")
@pytest.fixture(name="soco")
def soco_fixture(music_library, speaker_info, battery_info, alarm_clock):
with patch("homeassistant.components.sonos.SoCo", autospec=True) as mock, patch(
"socket.gethostbyname", return_value="192.168.42.2"
):
mock_soco = mock.return_value
mock_soco.ip_address = "192.168.42.2"
mock_soco.uid = "RINCON_test"
mock_soco.play_mode = "NORMAL"
mock_soco.music_library = music_library
mock_soco.get_speaker_info.return_value = speaker_info
mock_soco.avTransport = SonosMockService("AVTransport")
mock_soco.renderingControl = SonosMockService("RenderingControl")
mock_soco.zoneGroupTopology = SonosMockService("ZoneGroupTopology")
mock_soco.contentDirectory = SonosMockService("ContentDirectory")
mock_soco.deviceProperties = SonosMockService("DeviceProperties")
mock_soco.alarmClock = alarm_clock
mock_soco.mute = False
mock_soco.night_mode = True
mock_soco.dialog_mode = True
mock_soco.volume = 19
mock_soco.bass = 1
mock_soco.treble = -1
mock_soco.sub_enabled = False
mock_soco.surround_enabled = True
mock_soco.soundbar_audio_input_format = "Dolby 5.1"
mock_soco.get_battery_info.return_value = battery_info
mock_soco.all_zones = [mock_soco]
yield mock_soco
@pytest.fixture(autouse=True)
async def silent_ssdp_scanner(hass):
with patch(
"homeassistant.components.ssdp.Scanner._async_start_ssdp_listeners"
), patch("homeassistant.components.ssdp.Scanner._async_stop_ssdp_listeners"), patch(
"homeassistant.components.ssdp.Scanner.async_scan"
):
yield
@pytest.fixture(name="discover", autouse=True)
def discover_fixture(soco):
async def do_callback(hass, callback, *args, **kwargs):
await callback(
ssdp.SsdpServiceInfo(
ssdp_location=f"http://{soco.ip_address}/",
ssdp_st="urn:schemas-upnp-org:device:ZonePlayer:1",
ssdp_usn=f"uuid:{soco.uid}_MR::urn:schemas-upnp-org:service:GroupRenderingControl:1",
upnp={
ssdp.ATTR_UPNP_UDN: f"uuid:{soco.uid}",
},
),
ssdp.SsdpChange.ALIVE,
)
return MagicMock()
with patch(
"homeassistant.components.ssdp.async_register_callback", side_effect=do_callback
) as mock:
yield mock
@pytest.fixture(name="config")
def config_fixture():
return {DOMAIN: {MP_DOMAIN: {CONF_HOSTS: ["192.168.42.1"]}}}
@pytest.fixture(name="music_library")
def music_library_fixture():
music_library = MagicMock()
music_library.get_sonos_favorites.return_value.update_id = 1
return music_library
@pytest.fixture(name="alarm_clock")
def alarm_clock_fixture():
alarm_clock = SonosMockService("AlarmClock")
alarm_clock.ListAlarms = Mock()
alarm_clock.ListAlarms.return_value = {
"CurrentAlarmListVersion": "RINCON_test:14",
"CurrentAlarmList": "<Alarms>"
'<Alarm ID="14" StartTime="07:00:00" Duration="02:00:00" Recurrence="DAILY" '
'Enabled="1" RoomUUID="RINCON_test" ProgramURI="x-rincon-buzzer:0" '
'ProgramMetaData="" PlayMode="SHUFFLE_NOREPEAT" Volume="25" '
'IncludeLinkedZones="0"/>'
"</Alarms>",
}
return alarm_clock
@pytest.fixture(name="alarm_clock_extended")
def alarm_clock_fixture_extended():
alarm_clock = SonosMockService("AlarmClock")
alarm_clock.ListAlarms = Mock()
alarm_clock.ListAlarms.return_value = {
"CurrentAlarmListVersion": "RINCON_test:15",
"CurrentAlarmList": "<Alarms>"
'<Alarm ID="14" StartTime="07:00:00" Duration="02:00:00" Recurrence="DAILY" '
'Enabled="1" RoomUUID="RINCON_test" ProgramURI="x-rincon-buzzer:0" '
'ProgramMetaData="" PlayMode="SHUFFLE_NOREPEAT" Volume="25" '
'IncludeLinkedZones="0"/>'
'<Alarm ID="15" StartTime="07:00:00" Duration="02:00:00" '
'Recurrence="DAILY" Enabled="1" RoomUUID="RINCON_test" '
'ProgramURI="x-rincon-buzzer:0" ProgramMetaData="" PlayMode="SHUFFLE_NOREPEAT" '
'Volume="25" IncludeLinkedZones="0"/>'
"</Alarms>",
}
return alarm_clock
@pytest.fixture(name="speaker_info")
def speaker_info_fixture():
return {
"zone_name": "Zone A",
"uid": "RINCON_test",
"model_name": "Model Name",
"software_version": "49.2-64250",
"mac_address": "00-11-22-33-44-55",
"display_version": "13.1",
}
@pytest.fixture(name="battery_info")
def battery_info_fixture():
return {
"Health": "GREEN",
"Level": 100,
"Temperature": "NORMAL",
"PowerSource": "SONOS_CHARGING_RING",
}
@pytest.fixture(name="battery_event")
def battery_event_fixture(soco):
variables = {
"zone_name": "Zone A",
"more_info": "BattChg:NOT_CHARGING,RawBattPct:100,BattPct:100,BattTmp:25",
}
return SonosMockEvent(soco, soco.deviceProperties, variables)
@pytest.fixture(name="alarm_event")
def alarm_event_fixture(soco):
variables = {
"time_zone": "ffc40a000503000003000502ffc4",
"time_server": "0.sonostime.pool.ntp.org,1.sonostime.pool.ntp.org,2.sonostime.pool.ntp.org,3.sonostime.pool.ntp.org",
"time_generation": "20000001",
"alarm_list_version": "RINCON_test:1",
"time_format": "INV",
"date_format": "INV",
"daily_index_refresh_time": None,
}
return SonosMockEvent(soco, soco.alarmClock, variables)
@pytest.fixture(autouse=True)
def mock_get_source_ip(mock_get_source_ip):
return mock_get_source_ip
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.