feat(content; layouts; static): migrate hexo blog. add new theme fuji.

migrate hexo blog. add new theme fuji.

Signed-off-by: Ching <loooching@gmail.com>
This commit is contained in:
Ching 2022-02-07 23:38:40 +08:00
commit 5ba7024532
50 changed files with 2123 additions and 0 deletions

23
.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# Hugo default output directory
/public
/resources/_gen/
/assets/jsconfig.json
hugo_stats.json
## OS Files
# Windows
Thumbs.db
ehthumbs.db
Desktop.ini
$RECYCLE.BIN/
# OSX
.DS_Store
# Executable may be added to repository
hugo.exe
hugo.darwin
hugo.linux
# Temporary lock file while building
/.hugo_build.lock

3
.gitmodules vendored Normal file
View File

@ -0,0 +1,3 @@
[submodule "themes/fuji"]
path = themes/fuji
url = https://github.com/amzrk2/hugo-theme-fuji.git

6
archetypes/default.md Normal file
View File

@ -0,0 +1,6 @@
---
title: "{{ replace .Name "-" " " | title }}"
date: {{ .Date }}
draft: true
---

155
config.toml Normal file
View File

@ -0,0 +1,155 @@
baseURL = 'https://blog.tunpok.com/'
title = 'MarkDown'
theme = 'fuji'
hasCJKLanguage = true
enableEmoji = true
enableRobotsTXT = true
disableKinds = []
ignoreErrors = ["error-disable-taxonomy"]
## Change this two to switch between different language
languageCode = "zh-cn" # For RSS, view https://www.rssboard.org/rss-language-codes
defaultContentLanguage = "zh-hans" # For HTML page, now support: en, zh-hans, zh-hant, ja, nl, pl, it
summaryLength = 100 # Custom summary length, add <!--more--> in post file to custom split point
paginate = 10
# googleAnalytics = "UA-000000000-0" # Set your Google Analytics UA here
[outputFormats]
[outputFormats.SearchIndex]
isPlainText = true
notAlternative = true
mediaType = "application/json"
path = "/search/"
[outputs]
home = ["HTML", "RSS", "SearchIndex"]
[permalinks]
post = "/:section/:filename/" # Custom post links, e.g. "/:year/:month/:title/"
[params]
author = "Ching" # You can also set author in post front matter individually
subTitle = "「靡不有初,鲜克有终」"
defaultTheme = "auto" # default theme when first visit (auto|dark|light)
# Source URL of the website, will appear in the footer
#sourceURL = "https://github.com/dsrkafuu/hugo-theme-fuji"
# Use CloudFlare Workers to accelerate the Google Analytics
# If you are using this please comment the googleAnalytics above
# Check https://github.com/SukkaW/cloudflare-workers-async-google-analytics for more details
# googleAnalyticsTid = "UA-000000000-0"
# googleAnalyticsRoute = "https://*.*.workers.dev/"
# Google AdSense
# The AdSense code will be inserted between the head tags of your site.
# googleAdsense = "0000000000000000"
# Word counter and read time indicator in post metadata
showWordCounter = true
showReadTime = false
# License in the footer
showLicenseInFooter = false
# License at the end of each post
showLicense = false
showToc = true
# Copyright
copyrightStartYear = ""
# Open Graph & Twitter Card variables
# You can also set description and images in post front matter individually
description = "A minimal Hugo theme with nice theme color."
og = "/img/og.png" # This will use the image called og.png in static/img folder
# Posts shown in homepage
mainSections = ["posts"]
# Bangumi image chart id
# bgmImageChart = "000000"
# License
license = "CC BY-NC-SA 4.0"
licenseLink = "http://creativecommons.org/licenses/by-nc-sa/4.0/"
# Comments
# utterances, see: https://utteranc.es/
# utterancesRepo = "*/*"
# utterancesIssueTerm = "pathname"
# Disqus, see: https://disqus.com/admin/install/platforms/universalcode/
# disqusShortname = "*********"
# Also use DisqusJS for accessing from Mainland China, see: https://github.com/SukkaW/DisqusJS
# If you want to set multiple api key, see theme's README for more details
# disqusJSApi = "https://*********/"
# disqusJSApikey = "**********"
# custom lazyload placeholder
# 16:9
lazyPlaceholder = "/assets/lazyload/dsrca_loading_480x270.svg"
# 32:9
lazyPlaceholderRow = "/assets/lazyload/dsrca_loading_960x270.svg"
# 8:9
lazyPlaceholderCol = "/assets/lazyload/dsrca_loading_480x540.svg"
# Let images display in full brightness under dark mode
# disableDarkImage = true
[markup]
[markup.goldmark]
[markup.goldmark.renderer]
unsafe = true # Enable user to embed HTML snippets in Markdown content
[markup.highlight]
codeFences = false # Disable Hugo's code highlighter
[markup.tableOfContents]
startLevel = 2
endLevel = 3
[taxonomies]
tag = "tags"
category = "categories"
[menu]
[[menu.nav]]
name = "Home"
url = "/"
weight = 1
[[menu.nav]]
name = "Archives"
url = "/archives/"
weight = 2
# [[menu.nav]]
# name = "Categories"
# url = "/categories/"
# weight = 3
[[menu.nav]]
name = "Search"
url = "/search/"
weight = 4
[[menu.nav]]
name = "RSS"
url = "/index.xml"
weight = 5
[[menu.link]]
name = "hea"
url = "https://ghost.tunpok.com/"
weight = 1
# [[menu.link]]
# name = "GitHub"
# url = "https://github.com/dsrkafuu"
# weight = 1
# [[menu.link]]
# name = "Twitter"
# url = "https://twitter.com/dsrkafuu"
# weight = 2
# [[menu.link]]
# name = "bilibili"
# url = "https://space.bilibili.com/19767474"
# weight = 3

View File

@ -0,0 +1,5 @@
---
title: "Archives"
date: 2022-02-07T22:50:44+08:00
---

View File

@ -0,0 +1,53 @@
---
title: bash function and awk
date: 2018-05-31 00:00:48
tags:
- bash
---
I'll come across many hg branch-switching or log searching tasks during my work. Using bash functions and awk greatly reduce the time I spend on dealing with these tasks. So let's see what these functions can do to help me improve my productivity.
#### bash functions
Bash functions are scripts like `alias`, but can do much a lot than aliasThe first kind of usages of function is to run several scripts continuously, the same as `&&` I guess:
```bash
function run {
source ~/Develop/django/bin/activate
./manage.py runserver
}
```
I activate django virtural enviroment first and then run django serve.
Functions, like in any other languages, can take parameters and returns a result. So I can use this ability to do a liitle more complex work:
```bash
function ba { hgba | grep "$1" }
# hgba is an alias for hg branches
```
I can just type `ba release` then get current release branch info.
-----
Append:
I made some updates to the `ba` function and make it auto copying the branch result to my clipboard:
```bash
function ba { var="$(hgba | grep $1)" && echo $var | awk -F ':' END{print} | awk -F ':' '{print $NF}' | tr -d '\n' | pbcopy && echo $var }
```
#### awk
`awk` is a command I just know recently. I need to process a bunch of logs and analyze them. What I used to do is download the logs, grep things I want into a txt file and then process the txt file with python.

View File

@ -0,0 +1,15 @@
---
title: AWS KMS
date: 2019-11-14 15:19:05
tags:
- aws
---
We used to keep private credentials on production servers without any protection or encryption. Well, luckily we don't have any leak but this practice is not recommended for both security and easy of use reasons.
Since AWS finally provides [KMS(Key Management Service)][1] in our local region, we try to encrypt every private credentials by KMS and store them on S3.
*TBD*
[1]: https://www.amazonaws.cn/kms/

View File

@ -0,0 +1,61 @@
---
title: leetcode-121
date: 2020-03-17 18:06:45
tags:
- leetcode
categories:
- leetcode
---
### 121. 买卖股票的最佳时机
[题目](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/)
<!--more-->
原始答案:
```python
class Solution:
def maxProfit(self, prices) -> int:
profit = 0
if not prices:
return profit
min_buyin = prices[0]
max_sellout = prices[0]
l = len(prices)
i = 0
for buyin in prices:
if i == l:
return profit
if min_buyin <= buyin:
max_sellout = max(prices[i:])
p = max_sellout - min_buyin
if p > profit:
profit = p
if buyin < min_buyin:
min_buyin = buyin
i += 1
return profit
#1880 ms 14.4 MB
```
主要思路是找到波谷如果当前价格比前一天要低则还是在去往波谷的路上当价格比前一天高或相同时则到达了一个波谷计算波谷和之后的波峰的差就是这一段的利润。将从头至尾过一次就能找到所有波谷和其后波峰的差返回最大的即可。但是这个明显地在重复max时间复杂度是O(n^2),看起来就很傻逼。
仔细想想其实并不需要直接找出波谷后的波峰只要在for loop时保持波谷为最低的那个就能算出每一个后续与波谷的差找最大差即可。改了下代码变成这样
```python
class Solution:
def maxProfit(self, prices) -> int:
profit = 0
if not prices:
return profit
min_buyin = prices[0]
for i in range(1, len(prices)):
min_buyin = min(min_buyin, prices[i-1])
profit = max(prices[i] - min_buyin, profit)
return profit
#44 ms 14.4 MB
```

View File

@ -0,0 +1,89 @@
---
title: leetcode-206
date: 2020-03-18 23:33:03
tagstags:
- leetcode:
categories: leetcode
---
### 206. 反转链表
[题目](https://leetcode-cn.com/problems/reverse-linked-list/)
<!--more-->
最简单的思路是遍历链表一个列表去做存储,通过倒序读取列表的同时改写链表。
```python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head):
if not head or not head.next:
return head
nl = []
while head.next:
nl.append(head)
head = head.next
nl.append(head)
l = len(nl)
for x in range(l):
if x == 0:
nl[x].next = None
continue
nl[x].next = nl[x-1]
if x == (l - 1):
return nl[x]
```
仔细想想自己又傻逼了,何必要遍历两次呢,在第一遍遍历的同时就能操作了:
```python
class Solution:
def reverseList(self, head):
if not head or not head.next:
return head
prev_node = None
next_node = head.next
while head:
next_node = head.next
head.next = prev_node
prev_node = head
head = next_node
return prev_node
```
然后是递归的做法,主要思路是一直进到最深一层--也就是链表的最后一个--的时候开始返回,同时修改那一层的两个 node。一开始踩了一个坑是返回了每一个node结果最后回到第一层的时候得到的是链表的末端其实只需要修改链表并不需要返回 node所以一开始到达链表末端的时候直接返回那一个node就可以了。
```python
class Solution:
def reverseList(self, head):
if not head:
return head
if head.next:
ss = Solution()
last = ss.reverseList(head.next)
head.next.next = head
head.next = None
return last
return head
```
一开始是用list来打草稿不过想明白递归之后就大同小异了
```python
def a(l:list)->list:
k=[l[0]]
if l[1:]:
b=a(l[1:])
b.extend(k)
else:
return [l[0]]
return b
```

View File

@ -0,0 +1,63 @@
---
title: leetcode-169
date: 2020-03-23 23:12:57
tagstags:
- leetcode:
categories: leetcode
---
### 169. 多数元素
[题目](https://leetcode-cn.com/problems/majority-element/)
<!--more-->
一开始的思路是遍历一遍整个列表,用一个字典去记录每个元素出现的次数,当次数大于 $\cfrac{n}{2}$ 时就可以得出结果。
```python
class Solution:
def majorityElement(self, nums) -> int:
d = {}
l = len(nums)
for n in nums:
if not n in d:
d[n] = 0
d[n] = d[n] + 1
if d[n] > l/2:
return n
# 64 ms 15.1 MB
```
Python 也有专门计数的库,写起来更简单一点:
```python
class Solution:
def majorityElement(self, nums):
counts = collections.Counter(nums)
return max(counts.keys(), key=counts.get)
# 44 ms 15.1 MB
```
由于要找的数出现次数大于 $\cfrac{n}{2}$,脑子里掠过一下[蒙特卡罗算法](https://zh.wikipedia.org/wiki/%E8%92%99%E5%9C%B0%E5%8D%A1%E7%BE%85%E6%96%B9%E6%B3%95),后来在官方解答中也看到类似的思路了:
```python
class Solution:
def majorityElement(self, nums):
majority_count = len(nums)//2
while True:
candidate = random.choice(nums)
if sum(1 for elem in nums if elem == candidate) > majority_count:
return candidate
#作者LeetCode-Solution
#链接https://leetcode-cn.com/problems/majority-element/solution/duo-shu-yuan-su-by-leetcode-solution/
#来源力扣LeetCode
#著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
```

View File

@ -0,0 +1,70 @@
---
title: leetcode-225
date: 2020-03-23 23:35:05
tags:
- leetcode
categories: leetcode
---
### 225. 用队列实现栈
[题目](https://leetcode-cn.com/problems/implement-stack-using-queues/)
<!--more-->
注意栈是 FILO(First In Last Out)Python 的 list 是 FIFO(First In First Out)。
```python
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.data = []
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.data.append(x)
return
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
return self.data.pop(-1)
def top(self) -> int:
"""
Get the top element.
"""
return self.data[-1]
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
return not bool(self.data)
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
#24 ms 13.5 MB
```

View File

@ -0,0 +1,50 @@
---
title: leetcode-409
date: 2020-03-25 21:55:38
tags:
- leetcode
categories: leetcode
---
### 409. 最长回文串
[题目](https://leetcode-cn.com/problems/longest-palindrome/)
<!--more-->
一开始理解错题目了,以为是寻找字符串中的最长回文串,结果是构造。但是原理基本一样,由于回文中心对称,所以是由多个偶数个相同字母和至多一个奇数个相同字母组成。
这样只要数给出的字符串中有几个偶数个相同字母和几个奇数个相同字母就可以了。奇数个相同字母可以减少一个当偶数个用,最后再加回去一个。
```python
class Solution:
def longestPalindrome(self, s: str) -> int:
d = {}
for l in s:
if not l in d:
d[l] = 0
d[l] += 1
i = 0
odd = False
for k, v in d.items():
if v % 2:
i += (v-1)
odd = True
else:
i += v
if odd:
i += 1
return i
#40 ms 13.6 MB
```

View File

@ -0,0 +1,113 @@
---
title: leetcode-543
date: 2020-03-25 19:13:52
tags:
- leetcode
categories: leetcode
---
### 543. 二叉树的直径
[题目](https://leetcode-cn.com/problems/diameter-of-binary-tree/)
<!--more-->
这题做出来了但是没有通过运行时间的测试,主要还是没想明白二叉树的直径到底是什么东西,用了个蠢办法。
```python
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if not root:
return 0
last_node = -1
routes = []
start = root
node_stack = [root]
while (start.left or start.right or node_stack):
if start != node_stack[-1]:
node_stack.append(start)
if last_node == start.right:
node_stack = node_stack[:-1]
if not node_stack:
break
last_node = start
start = node_stack[-1]
continue
if start.left and last_node != start.left:
start = start.left
last_node = start
continue
if start.right:
start = start.right
last_node = start
continue
routes.append(node_stack)
node_stack = node_stack[:-1]
if not node_stack:
break
last_node = start
start = node_stack[-1]
max_l = 0
for route in routes:
for route_ in routes:
intersection = 0
if route != route_:
intersection = len(set(route).intersection(set(route_)))
if intersection:
intersection -= 1
max_l = max(max_l, len(set(route)| set(route_)) - intersection)
return max_l - 1
```
L43 之前做的是以深度优先的方式遍历一遍树,得出每个点的路径。后面的是将所有路径组合在一起得出任意两个点间的路径,算出最大长度。
其实以某个点为根节点的树的直径,就是某个节点的**左子树的深度和右子树的深度的和**,用递归来处理这个会比较容易理解
```python
class Solution(object):
def diameterOfBinaryTree(self, root):
self.ans = 1
def depth(node):
# 访问到空节点了返回0
if not node: return 0
# 左儿子为根的子树的深度
L = depth(node.left)
# 右儿子为根的子树的深度
R = depth(node.right)
# 计算d_node即L+R+1 并更新ans
self.ans = max(self.ans, L+R+1)
# 返回该节点为根的子树的深度
return max(L, R) + 1
depth(root)
return self.ans - 1
作者LeetCode-Solution
链接https://leetcode-cn.com/problems/diameter-of-binary-tree/solution/er-cha-shu-de-zhi-jing-by-leetcode-solution/
来源力扣LeetCode
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
```

View File

@ -0,0 +1,34 @@
---
title: leetcode-836
date: 2020-03-25 22:41:25
tags:
- leetcode
categories: leetcode
---
### 836. 矩形重叠
[题目](https://leetcode-cn.com/problems/rectangle-overlap/)
<!--more-->
看两个矩形有没有重叠,就看两个矩形在坐标轴上的投影有没有重叠。
```python
class Solution:
def isRectangleOverlap(self, rec1, rec2) -> bool:
return ((min(rec1[2], rec2[2]) > max(rec1[0], rec2[0]))
and (min(rec1[3], rec2[3]) > max(rec1[1], rec2[1])))
s = Solution()
s.isRectangleOverlap(rec1 = [0,0,2,2], rec2 = [1,1,3,3])
#40 ms 13.7 MB
```

View File

@ -0,0 +1,68 @@
---
title: leetcode-876
date: 2020-03-26 21:18:41
tags:
- leetcode
categories: leetcode
---
### 876. 链表的中间结点
[题目](https://leetcode-cn.com/problems/middle-of-the-linked-list/)
<!--more-->
思路是遍历一遍得到整个链表,讲每个 node 放进一个 list就可以通过下标得到中间的。
```python
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
l = []
n = head
while n.next:
l.append(n)
n = n.next
l.append(n)
return l[len(l)//2]
#44 ms 13.7 MB
```
看官方解答,还有一个骚操作,通过两个速度不一样的指针,一个一次走一步,一个两次走一步,快的走到底时,慢的就在中间了。
```python
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
作者LeetCode-Solution
链接https://leetcode-cn.com/problems/middle-of-the-linked-list/solution/lian-biao-de-zhong-jian-jie-dian-by-leetcode-solut/
来源力扣LeetCode
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
```

View File

@ -0,0 +1,46 @@
---
title: leetcode-1013
date: 2020-03-29 21:09:22
tags:
- leetcode
categories: leetcode
---
### 1013. 将数组分成和相等的三个部分
[题目](https://leetcode-cn.com/problems/partition-array-into-three-parts-with-equal-sum/)
<!--more-->
因为是整数数组如果能均分成三份则数组和肯定是3的倍数。然后遍历数组逐端求和使得和为 sum(A)/3。
```python
class Solution:
def canThreePartsEqualSum(self, A) -> bool:
if not A:
return False
sa = sum(A)
if sa % 3:
return False
s = sa // 3
s1 = 0
s2 = 0
for i in range(len(A)):
s1 += A[i]
if s1 == s and (i+1) < len(A):
for j in range(len(A[i+1:])):
s2 += A[i+1+j]
if s2 == s and j+1 < len(A[i+1:]) and sum(A[i+j+2:])== s:
return True
return False
#60 ms 18.7 MB
```

View File

@ -0,0 +1,52 @@
---
title: leetcode-914
date: 2020-03-29 22:41:09
tags:
- leetcode
categories: leetcode
---
### 914. 卡牌分组
[题目](https://leetcode-cn.com/problems/x-of-a-kind-in-a-deck-of-cards/)
<!--more-->
将大牌堆分成多个牌数量相等的小牌堆就是求每张牌数量的公约数。先遍历一遍得到每张牌的数量然后找出比2大的公约数即可。
```python
class Solution:
def hasGroupsSizeX(self, deck) -> bool:
dc = {}
max_d = 0
for d in deck:
if d not in dc:
dc[d] = 0
dc[d] += 1
if max_d < d:
max_d = d
if max_d < dc[d]:
max_d = dc[d]
has_x = True
if max_d == 1:
max_d = 2
for i in range(2, max_d + 1):
has_x = True
for k,v in dc.items():
if v % i:
has_x = False
break
if has_x and i >= 2:
return True
return False
#56 ms 13.8 MB
```

View File

@ -0,0 +1,60 @@
---
title: leetcode-1071
date: 2020-03-30 22:03:01
tags:
- leetcode
categories: leetcode
---
### 1071. 字符串的最大公因子
[题目](https://leetcode-cn.com/problems/greatest-common-divisor-of-strings/)
<!--more-->
如果存在这样字符串,那它最大的长度就是这两个字符串长度的最大公约数。
```python
class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
if str1[0] != str2[0]:
return ''
a = len(str1)
b = len(str2)
print(a, b)
if a < b:
str1, str2 = str2, str1
a = len(str1)
b = len(str2)
if not a%b:
for x in range(0, a//b):
if str1[x*b:(x+1)*b] != str2:
return ''
return str2
else:
for x in range(b, 0, -1):
print(x)
if x==b or b%x or a%x:
continue
for y in range(0, b//x):
if str2[y*x:(y+1)*x] != str2[b-x:b]:
return ''
for y in range(0, a//x):
if str1[y*x:(y+1)*x] != str2[0:x]:
return ''
return str2[0:x]
# 44 ms 13.9 MB
```
官方解答中还给了一种巧妙的解法,如果 str1 + str2 == str2 + str1 的话,[可以证明](https://leetcode-cn.com/problems/greatest-common-divisor-of-strings/solution/zi-fu-chuan-de-zui-da-gong-yin-zi-by-leetcode-solu/)必定存在这样一个字符串,其长度为两个字符串长度的最大公约数。

View File

@ -0,0 +1,72 @@
---
title: leetcode-999
date: 2020-03-30 21:03:25
tags:
- leetcode
categories: leetcode
---
### 999. 可以被一步捕获的棋子数
[题目](https://leetcode-cn.com/problems/available-captures-for-rook/)
<!--more-->
遍历一遍找到车的坐标,然后按上下左右四个方向循环一下看碰到的第一个棋子是什么。
```python
class Solution:
def numRookCaptures(self, board) -> int:
i = j = 0
for row in board:
if 'R' in row:
break
i += 1
j = row.index('R')
count = 0
# right
for x in range(j + 1, 8):
if row[x] == 'p':
count += 1
break
if row[x] == 'B':
break
# left
for x in range(j, 0, -1):
if row[x] == 'p':
count += 1
break
if row[x] == 'B':
break
# up
for x in range(i, 0, -1):
if board[x][j] == 'p':
count += 1
break
if board[x][j] == 'B':
break
# down
for x in range(i+1, 8):
if board[x][j] == 'p':
count += 1
break
if board[x][j] == 'B':
break
return count
#36 ms 13.6 MB
```
问题不难,官方解答中给了一个方向数组的概念,上下左右是 (0, 1) (0, -1) (-1, 0) (1, 0),有点像向量的意思。走的路线等于方向数组乘以步数。

View File

@ -0,0 +1,56 @@
---
title: leetcode-1103
date: 2020-04-01 11:22:20
tags:
- leetcode
categories: leetcode
mathjax: true
---
### 1103. 分糖果 II
[题目](https://leetcode-cn.com/problems/distribute-candies-to-people/)
<!--more-->
小学奥数题。主要思路就是等差数列求和 $\cfrac{(首项 + 末项)×项数}{2}$ 。可以用公式把每一个位置获得的总糖果数表示出来。我的方法稍微蠢了点,算了每一轮的总糖果数,其实可以直接求总共发了多少次糖果,除以每轮的人数就可以得出发了多少轮。
```python
class Solution:
def distributeCandies(self, candies: int, num_people: int):
total = 0
i = 0
# import ipdb; ipdb.set_trace()
while total <= candies:
t = (num_people*i)*num_people + int((1+num_people)*num_people/2)
if total + t <= candies:
total += t
i += 1
else:
break
remaining = candies - total
print(total, remaining, i)
l = []
for n in range(1, num_people+1):
if not total:
current_candy = n
else:
current_candy = n+i*num_people
n_count = int((0+(i-1))*(i)/2)
print(current_candy, n_count)
if remaining >= current_candy:
l.append(n_count*num_people + n*i + current_candy)
remaining -= current_candy
else:
l.append(n_count*num_people + n*i + remaining)
remaining = 0
return l
# 28 ms 13.7 MB,
```

View File

@ -0,0 +1,39 @@
---
title: leetcode-1160
date: 2020-04-01 00:18:48
tags:
- leetcode
categories: leetcode
---
### 1160. 拼写单词
[题目](https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters/)
<!--more-->
利用列表 remove 方法,检查 chars 中是否有足够的字母拼写 word
```python
class Solution:
def countCharacters(self, words, chars: str) -> int:
words_ = ''
for w in words:
lchars = list(chars)
try:
for l in w:
lchars.remove(l)
except:
continue
words_ += w
return len(words_)
# 152 ms 14.1 MB
```

View File

@ -0,0 +1,42 @@
---
title: leetcode-compress-string-lcci
date: 2020-04-01 15:51:22
tags:
- leetcode
categories: leetcode
---
### 面试题 01.06. 字符串压缩
[题目](https://leetcode-cn.com/problems/compress-string-lcci/)
<!--more-->
遍历一遍字符串,遇到跟上一个字符不同的字符时记录上一个字符的重复长度。
```python
class Solution:
def compressString(self, S: str) -> str:
if not S:
return S
c = ''
prev = S[0]
p_len = 1
for w in S[1:]:
if w != prev:
c += '%s%s' % (prev, p_len)
prev = w
p_len = 1
else:
p_len += 1
c += '%s%s' % (prev, p_len)
if len(S) > len(c):
return c
return S
# 52 ms 13.8 MB
```

View File

@ -0,0 +1,43 @@
---
title: leetcode-he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof
date: 2020-04-09 22:14:56
tags:
- leetcode
categories: leetcode
mathjax: true
---
### 面试题57 - II. 和为s的连续正数序列
[题目](https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/)
<!--more-->
又是小学奥数。由等差数列求和公式$\cfrac{(首项 + 末项)×项数}{2}$ 可知,当首项为 1 的时候项数最多,又由于是连续正整数,$n^2 < (1+n)×n < (n+1)^2 $,那最大的 $n$ 就不大于 $\sqrt{2×target} + 1$。
由小到大遍历 $n$,可以求得首项。
```python
import math
class Solution:
def findContinuousSequence(self, target: int):
n = int(math.sqrt(2 * target) + 1)
if n < 2:
return []
sum_list = []
a = 0
for i in range(2, n+1):
a = ((2 * target) / i + 1 - i) / 2
if a and not a % 1:
a = int(a)
s_ = []
for j in range(0, i):
s_.append(a + j)
sum_list.append(s_)
return sorted(sum_list)
# 60 ms 13.7 MB
```

View File

@ -0,0 +1,48 @@
---
title: leetcode-the-masseuse-lcci
date: 2020-04-09 00:35:26
tags:
- leetcode
categories: leetcode
mathjax: true
---
### 面试题 17.16. 按摩师
[题目](https://leetcode-cn.com/problems/the-masseuse-lcci/)
<!--more-->
一开始以为是用递归,想了半天没想出来,偷看了一下答案。答案的思路跟递归类似,假设在当前 $i$ 时刻,$dp[i][0]$ 为当前预约不接的情况下最长预约时间,$dp[i][1]$ 则为接受当前预约的最长预约时间。
那很显然,由于不能接受相邻两个预约,$dp[i][1] = dp[i-1][0] + nums_i$
不接受当前预约的话,上一个预约接不接受都可以,$dp[i][0] = max(dp[i-1][0], dp[i-1][1])$
最后只要比较两种情况即可 $max(dp[i][0], dp[i][1])$
```python
class Solution:
def massage(self, nums) -> int:
if not nums:
return 0
n = len(nums)
not_choose = 0
choose = 0
for n in nums:
not_choose, choose = max(not_choose, choose), not_choose+n
return max(not_choose, choose)
# 52 ms 13.6 MB
```
这种问题原来有个名字叫[动态规划](https://zh.wikipedia.org/wiki/动态规划),上面推导的方程叫[状态转移方程](https://baike.baidu.com/item/状态转移方程),可以找找资料来看一下。

View File

@ -0,0 +1,116 @@
---
title: leetcode-add-two-numbers-ii
date: 2020-04-14 23:22:39
tags:
- leetcode
categories: leetcode
---
### 445. 两数相加 II
[题目](https://leetcode-cn.com/problems/add-two-numbers-ii/)
<!--more-->
看到顺序的链表就想到用倒序链表的方法做,折腾了半天
```python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
def _reverse(l):
if l.next:
last = _reverse(l.next)
l.next.next = l
l.next = None
return last
return l
l1e = _reverse(l1)
l2e = _reverse(l2)
new_l = ListNode(0)
head = new_l
c = 0
import ipdb; ipdb.set_trace()
while l1e and l2e:
new_val = l1e.val + l2e.val
if c==1:
new_val += 1
c = 0
if new_val >= 10:
new_val -= 10
c = 1
new_l.val = new_val
next_n = None
if l1e.next and l2e.next or c:
next_n = ListNode(c)
new_l.next = next_n
new_l = next_n
l1e = l1e.next
l2e = l2e.next
if l2e:
l1e = l2e
if not l1e and c:
l1e = ListNode(0)
while l1e:
new_l.val = l1e.val
new_l.val += c
c = 0
if new_l.val >= 10:
c = 1
new_l.val -= 10
l1e = l1e.next
if l1e:
new_l.next = ListNode(0)
new_l = new_l.next
else:
new_l.next = ListNode(1)
return _reverse(head)
# 84 ms 13.9 MB
```
最后面各种进位的处理应该还可以更清晰优雅一些,但是懒得搞了,感觉很蠢。翻了答案看到了小 tips需要倒序处理的情况可以用栈。
```python
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
s1, s2 = [], []
while l1:
s1.append(l1.val)
l1 = l1.next
while l2:
s2.append(l2.val)
l2 = l2.next
ans = None
carry = 0
while s1 or s2 or carry != 0:
a = 0 if not s1 else s1.pop()
b = 0 if not s2 else s2.pop()
cur = a + b + carry
carry = cur // 10
cur %= 10
curnode = ListNode(cur)
curnode.next = ans
ans = curnode
return ans
作者LeetCode-Solution
链接https://leetcode-cn.com/problems/add-two-numbers-ii/solution/liang-shu-xiang-jia-ii-by-leetcode-solution/
来源力扣LeetCode
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
```
不过就执行效率来看差不多。

View File

@ -0,0 +1,84 @@
---
title: leetcode-design-twitter
date: 2020-04-14 16:11:41
tags:
- leetcode
categories: leetcode
---
### 355. 设计推特
[题目](https://leetcode-cn.com/problems/design-twitter/)
<!--more-->
做出来倒是很简单,由于没有并发和特别的条件,测试数据量也不大。一开始搞错了,以为传入的 `twitterId` 就是自增的 id结果其实是每条推的内容所以增加了一个计数器去标记 id。
主要的考点应该是 `多路归并` 这个东西。我用的是排序,在数据量大的时候应该会有些问题。
```python
class Twitter:
def __init__(self):
"""
Initialize your data structure here.
"""
self.tweets = {}
self.followers = {}
self._tid = 0
def postTweet(self, userId: int, tweetId: int) -> None:
"""
Compose a new tweet.
"""
if not self.tweets.get(userId):
self.tweets[userId] = []
self.tweets[userId].append((self._tid, tweetId))
self._tid += 1
def getNewsFeed(self, userId: int) :
"""
Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
"""
foers = self.followers.get(userId, set())
foers = foers.union((userId,))
tweets = []
for fo in foers:
tweets.extend(self.tweets.get(fo, [])[-10:])
return [tw[1] for tw in sorted(tweets, reverse=True)[:10]]
def follow(self, followerId: int, followeeId: int) -> None:
"""
Follower follows a followee. If the operation is invalid, it should be a no-op.
"""
if not self.followers.get(followerId):
self.followers[followerId] = set()
self.followers[followerId].add(followeeId)
def unfollow(self, followerId: int, followeeId: int) -> None:
"""
Follower unfollows a followee. If the operation is invalid, it should be a no-op.
"""
if not self.followers.get(followerId):
self.followers[followerId] = set()
if followeeId in self.followers[followerId]:
self.followers[followerId].remove(followeeId)
#100 ms 19.2 MB
# Your Twitter object will be instantiated and called as such:
# obj = Twitter()
# obj.postTweet(userId,tweetId)
# param_2 = obj.getNewsFeed(userId)
# obj.follow(followerId,followeeId)
# obj.unfollow(followerId,followeeId)
```

View File

@ -0,0 +1,48 @@
---
title: leetcode-01-matrix
date: 2020-04-16 12:26:34
tags:
- leetcode
categories: leetcode
---
### 542. 01 矩阵
[题目](https://leetcode-cn.com/problems/01-matrix/)
<!--more-->
想了两种思路
1. 0 位置的上下左右是 1 上下左右中有跟 1 相邻的就是 2以此类推从 0 的坐标开始往上下左右四个方向扩散。如果我们把同意个距离的看作是一层,可以用一个队列依次存放每一层的坐标,直至每个坐标都被计算过。
```python
class Solution:
def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
m, n = len(matrix), len(matrix[0])
dist = [[0] * n for _ in range(m)]
zeroes_pos = [(i, j) for i in range(m) for j in range(n) if matrix[i][j] == 0]
# 将所有的 0 添加进初始队列中
q = collections.deque(zeroes_pos)
seen = set(zeroes_pos)
# 广度优先搜索
while q:
i, j = q.popleft()
for ni, nj in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:
if 0 <= ni < m and 0 <= nj < n and (ni, nj) not in seen:
dist[ni][nj] = dist[i][j] + 1
q.append((ni, nj))
seen.add((ni, nj))
return dist
```
2. 从左上角开往右下角遍历矩阵,当前坐标的距离由左和上两个位置的值确定。遍历一遍后,再反过来从右下角开始往左上角遍历,当前坐标的距离根据右和下两个位置的值确定,比较这两次得出的值中较小的一个即为该点的距离。

View File

@ -0,0 +1,51 @@
---
title: leetcode-merge-intervals
date: 2020-04-16 19:22:26
tags:
- leetcode
categories: leetcode
---
### 56. 合并区间
[题目](https://leetcode-cn.com/problems/merge-intervals/)
<!--more-->
首先将区间按起点由小到大排序,这样相邻的两个就能通过终点判断是否重合。
```python
class Solution:
def merge(self, intervals):
if not intervals:
return []
intervals.sort()
merged = []
l = len(intervals)
m = intervals[0]
for x in range(l-1):
j = intervals[x+1]
if m[1] >= j[0]:
if m[1] <= j[1]:
m = [m[0], j[1]]
else:
continue
else:
merged.append(m)
m = j
if m:
merged.append(m)
return merged
```

View File

@ -0,0 +1,56 @@
---
title: leetcode-string-to-integer-atoi
date: 2020-04-16 19:50:10
tags:
- leetcode
categories: leetcode
---
### 8. 字符串转换整数 (atoi)
[题目](https://leetcode-cn.com/problems/string-to-integer-atoi/)
<!--more-->
没什么好说的,注意各种情况,识别到数字之后就一直要是数字。
```python
class Solution:
def myAtoi(self, str: str) -> int:
p = ''
str = str.lstrip()
n = ''
min_int = -2**31
max_int = 2**31-1
isnumeric = False
for x in str:
if not isnumeric and x == '-':
p = '-'
isnumeric = True
continue
if not isnumeric and x == '+':
isnumeric = True
continue
if x.isnumeric():
n += x
isnumeric = True
else:
break
if not n:
return 0
if int(n) > max_int:
if p:
return min_int
else:
return max_int
p += n
return int(p)
# 32 ms 13.6 MB
```

View File

@ -0,0 +1,50 @@
---
title: leetcode-number-of-islands
date: 2020-04-21 12:55:17
tags:
- leetcode
categories: leetcode
---
### 200. 岛屿数量
[题目](https://leetcode-cn.com/problems/number-of-islands/)
<!--more-->
这种矩阵题现在第一反应就是用[广度优先搜索][0]做类似之前算和0之间的距离那题。遍历矩阵遇到 1 就将 1 改成 0然后广度优先搜索找出 1 相邻的所有 1这就是一个岛屿以此类推。
```python
import collections
class Solution:
def numIslands(self, grid) -> int:
rows = len(grid)
if not rows:
return 0
cols = len(grid[0])
islands = 0
for r in range(rows):
for l in range(cols):
if grid[r][l] == '1':
islands += 1
grid[r][l] = '0'
neighbors = collections.deque([(r, l)])
while neighbors:
x, y = neighbors.popleft()
for x_, y_ in [[x-1, y], [x+1, y], [x, y-1], [x, y+1]]:
if 0<=x_<rows and 0<=y_<cols and grid[x_][y_] == '1':
neighbors.append([x_, y_])
grid[x_][y_] = '0'
return islands
```
[0]:(https://zh.wikipedia.org/zh-cn/%E5%B9%BF%E5%BA%A6%E4%BC%98%E5%85%88%E6%90%9C%E7%B4%A2)

View File

@ -0,0 +1,55 @@
---
title: Django Manager Method
date: 2016-04-25 00:00:01
tags:
- django
---
#### Django Manager
Django 里会为每一个 model 生成一个 Manager默认名字为 objects一般情况下对 model 进行的处理都是通过 model.objects.XXX( ) 来进行的。其实是调用了 model 的 manager 的方法,而 manager 之中的方法是 QuerySet 方法的代理QuerySet 方法是对数据库操作的封装。
eg.
```python
from django.db import models
class Person(models.Model):
...
people = models.Manager()
```
上面这个 model`Person.objects`会产生一个`AttributeError`,但是`Person.people`就可以正常操作。因为默认的 manager 已经变成 peopleobjects 这个 manager 没有重新声明,不起作用。
#### 自定义 Manager
通常需要自定义 manager 的情况有两点:
1. 需要修改/扩展 Django 的 manager 方法
2. 需要修改返回的 QuerySet
#### 默认 Manager
如果使用自定义的 manager 需要注意的是Django 将 model 中定义的第一个 manager 认为是默认 manager而且 Django 框架中会用到默认 manager。
笨方法是使用自定义 manager 的时候,对于 model 依然提供 objects 这个默认 manager并放在第一个。
eg.
```python
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
objects = models.Manager() # default manager
custom_objects = CustomBOokManager() # custom manager
```
[source](http://blog.csdn.net/sicofield/article/details/49283751)

View File

@ -0,0 +1,122 @@
---
title: Flask Day 1
date: 2016-02-15 01:23:33
tags:
- flask
---
### "Hello World" in Flask
Create a folder named `microblog` (or whatever you want). Then cd into that folder and run following prompt in terminal:
``` bash
$ python3 -m venv flask
```
Now you'll have a folder named `flask` inside `microblog`, containing a private version of Python interpreter.
And you should install **flask** and extensions by the commands below:
``` bash
$ flask/bin/pip install flask
$ flask/bin/pip install flask-login
$ flask/bin/pip install flask-openid
$ flask/bin/pip install flask-mail
$ flask/bin/pip install flask-sqlalchemy
$ flask/bin/pip install sqlalchemy-migrate
$ flask/bin/pip install flask-whooshalchemy
$ flask/bin/pip install flask-wtf
$ flask/bin/pip install flask-babel
$ flask/bin/pip install guess_language
$ flask/bin/pip install flipflop
$ flask/bin/pip install coverage
```
After that, let's create the basic structure for our application: `app` `app/static` `app/templates` `tmp`.
1. `app` — where the application package is
2. `static` — stores static files like images, javascripts, and css.
3. `templates` — where templates will go.
Then you can start with ``__init__.py`` which should put into app folder (file `app/__init__.py`):
``` python
from flask import Flask
app = Flask(__name__)
from app import views
```
The views are the handlers that response to requests from web browsers or other clients. Each view function is mapped to one or more request URLs.
Let's see what a views function looks like (file `app/views.py`):
``` python
from flask import Flask
app = Flask(__name__)
from app import views
```
Finally we should create a script to starts up the web server with our application(file `run.py`):
``` python
#!flask/bin/python
from app import app
app.run(debug=True)
```
To indicating that is an executable file you need to run this in terminal:
``` bash
$ chmod a+x run.py
```
Now the file structure should look like:
```
microblog\
flask\
<virtual environment files>
app\
static\
templates\
__init__.py
views.py
tmp\
run.py
```
Then start to write the template (file `app/templates/index.html`):
``` html
<html>
<head>
<title>{{ title }} - microblog</title>
</head>
<body>
<h1>Hello, {{ user.nickname }}!</h1>
</body>
</html>
```
Now let's write the view function that uses this template (file `app/views.py`):
``` python
from flask import render_template
from app import app
@app.route('/')
@app.route('/index')
def index():
user = {'nickname': 'ching'} # fake user
return render_template('index.html',
title='Home',
user=user)
```
`render_template` function is what we import from Flask framework to render the template. It uses [Jinja2](http://jinja.pocoo.org/) templating engine.

View File

@ -0,0 +1,82 @@
---
title: Flask Day 2
date: 2016-02-16 22:45:06
tags:
- flask
---
To handle web forms we use [Flask-WTF ](http://packages.python.org/Flask-WTF). So we need to write a config file (file `config.py`):
``` python
WTF_CSRF_ENABLED = True
SECRET_KEY = 'you-will-never-guess'
```
And then you need to use this config (file `app/__init__.py`):
``` python
from flask import Flask
app = Flask(__name__)
app.config.from_object('config')
from app import views
```
Let's build a simple form (file `app/forms.app`):
``` python
from flask.ext.wtf import Form
from wtforms import StringField, BooleanField
from wtforms.validators import DataRequired
class LoginForm(Form):
openid = StringField('openid', validators=[DataRequired()])
remember_me = BooleanField('remember_me', default=False)
```
The `DataRequired()` is a validator that checks the field is empty or not.
After that, we need a HTML page to show the form (file `app/templates/login.html`):
``` html
<!-- extend from base layout -->
{% extends "base.html" %}
{% block content %}
<h1>Sign In</h1>
<form action="" method="post" name="login">
{{ form.hidden_tag() }}
<p>
Please enter your OpenID:<br>
{{ form.openid(size=80) }}<br>
</p>
<p>{{ form.remember_me }} Remember Me</p>
<p><input type="submit" value="Sign In"></p>
</form>
{% endblock %}
```
The final step is to code a view function that renders the template and receiving data from form (file `app/views.py`):
``` python
from flask import render_template, flash, redirect
from app import app
from .forms import LoginForm
# index view function suppressed for brevity
app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
flash('Login requested for OpenID="%s", remember_me=%s' %
(form.openid.data, str(form.remember_me.data)))
return redirect('/index')
return render_template('login.html',
title='Sign In',
form=form)
```

View File

@ -0,0 +1,43 @@
---
title: Postgresql Partitioning
date: 2019-03-12 00:08:48
tags:
- psql
---
`Partitioning` refers to splitting what is logically one large table inot smaller physical pieces.
Currently, PostgreSQL supports partitioning via table [inheritance](https://www.postgresql.org/docs/9.6/ddl-inherit.html). Each partition must be created as a child table of a single parent table. **The parent table itself is normally empty**; It exists just to represent the entire data set.
There are two forms of partitioning can be implemented in PostgreSQL:
* Range Partitioning
The table is partitioning into "range" defined by a key column or a set of columns, with no overlap between the ranges of values assigned to different partitions. eg. partition by date ranges or by identifiers.
* List Partitioning
The table is partitioned by explicitly listing which key values appear in each partition.
### Implementing Partitioning
1. Create the "master" / "parent" table, from which all the partitions will inherit.
This table will not contain any data. Do not define any check on this table, unless you intend them to be applied equally to all partitions. There is no point in defining any indexes or unique constraints on it either.
2. Create "child" tables that each inherit form the master table. Normally, these tables will not add any columns to the set inherited from the master.
3. Add table constraints to the partition tables to define the allowed key values in each partitions.
Ensure that the constraints guarantee that there is no overlap between the key values premitted in different partitions. And there is no difference in syntax between range and list partitioning.
4. Create indexes on column(s) for each partitions.
5. Optionally, define a trigger or rule to redirect data inserted into the master table to the appropriate partition.
6. Ensure hte [constraint_exclusion](https://www.postgresql.org/docs/9.6/runtime-config-query.html#GUC-CONSTRAINT-EXCLUSION) configuration parameter is not disabled in `postgresql.conf`. If it is, queries will not be optimized as desired.
### Trigger
As we are creating new table and hopping data insered to right partition, a trigger function and a trigger are needed.

View File

@ -0,0 +1,47 @@
---
title: TastyPie Note 1
date: 2016-05-10 17:00:00
tags:
- tastypie
- django
---
### Flow Through The Request/Response Cycle
Tastypie can be thought of as a set of class-based view that provide the API functionality. All routing/middleware/response-handling aspectss are the same as a typical Django app. Where the differs is in the view itself.
Walking through what a GET request to a list endpoint looks like:
- The `Resource.urls` are checked by Django's url resolvers.
- On a match for the list view, `Resource.wrap_view('dispatch_list')` is called. `wrap_view` provides basic error handling & allows for returning serilized errors.
- Because dispatch_list was passed to `wrap_view`, `Resource.dispatch_list` is called next. This is a thin wrapper around `Resource.dispatch`.
- `dispatch` does a bunch of havy lifting. It ensures:
- the requested HTTP method is in `allowed_methos` (`method_check`).
- the class has a method that can handle the request(`get_list`)
- the user is authenticated(`is_authenticated`)
- the user has no exceeded their throttle(`throttle_check`).
At this point, `dispatch` actually calls the requested method (`get_list`).
- `get_list` does the actual work of API. It does:
- A fetch of the available objects via `Resource.obj_get_list`. In the case of `ModelResource`, this builds the ORM filters to apply (`ModelResource.build_filters`). It then gets the `QuerySet` via `ModelResource.get_object_list` (which performs `Resource.authorized_read_list` to possibly limit the set the user can work with) and applies the built filters to it.
- It then sorts the objects based on user input (`ModelResource.apply_sorting`).
- Then it paginates the results using the supplied `Paginator` & pulls out the data to be serialized.
- The objects in the page have `full_dehydrate` applied to each of them, causing Tastypie to traslate the raw object data into the fields the endpoint supports.
- Finally, it calls `Resource.create_response`.
- `create_response` is a shortcut method that:
- Determines the desired response format (`Resource.determine_format`).
- Serializes the data given to it in the proper format.
- Returns a Django `HttpResponse` (200 OK) with the serialized data.
- We bubble back up the call stack to `dispatch`. The last thing `dispatch` does is potentially store that a request occured for future throttling (`Resource.log_throttled_access`) then either returns the `HttpResponse` or wraps whatever data came back in a response (so Django doesn't freak out).

41
content/posts/Tastypie.md Normal file
View File

@ -0,0 +1,41 @@
---
title: Tastypie
date: 2016-05-04 12:02:00
tags:
- tastypie
- django
---
#### Resources in Tastypie
Resources are the heart of Tastypie. By defining a resource we can actually convert a model into an API stream. The data is automatically converted into API response.
Understanding the process of creating a resource.
1. Import ModelResource from Tastypie.
2. Import models from services app
3. Create custom resource by inheriting ModelResource and link app model in inner Meta class of resource.
Add API URL in the urls.py of app.
#### Dehydrating the JSON data
![flow](https://impythonist.files.wordpress.com/2016/04/tastypie_ill.png?w=800)
Dehydration in Tastypie means making alterations before sending data to the client. Suppose we need to send capitalized product names instead of small letters. Now we see two kinds of dehydrate methods.
##### Dehydrate_field method
This `dehydrate_field` is uesd to modify field on the response JSON.
##### Dehydrate method
Dehydrate method is useful for aadding additional fields to bundle (response data).
Similarly using `hydrate` method we can alter the bundle data which is generated from request at the time of PUT or POST methods.

View File

@ -0,0 +1,9 @@
---
title: First Post
date: 2016-02-12 18:00:00
---
This is the very first post I wrote,
with [Typora](https://www.typora.io/) & [Hexo](https://hexo.io/).

5
content/search/_index.md Normal file
View File

@ -0,0 +1,5 @@
---
title: "Search"
date: 2022-02-07T22:48:28+08:00
---

1
deploy.sh Executable file
View File

@ -0,0 +1 @@
hugo && rsync -avz --delete public/ root@173.82.143.112:/root/deploy/tunpok-blog

View File

@ -0,0 +1,7 @@
<link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon.png" />
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
<link rel="manifest" href="/site.webmanifest" />
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5" />
<meta name="msapplication-TileColor" content="#da532c" />
<meta name="theme-color" content="#ffffff" />

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

BIN
static/apple-touch-icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

9
static/browserconfig.xml Normal file
View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
<msapplication>
<tile>
<square150x150logo src="/mstile-150x150.png"/>
<TileColor>#da532c</TileColor>
</tile>
</msapplication>
</browserconfig>

BIN
static/favicon-16x16.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

BIN
static/favicon-32x32.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

BIN
static/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

BIN
static/mstile-150x150.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

View File

@ -0,0 +1,16 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
width="157.000000pt" height="157.000000pt" viewBox="0 0 157.000000 157.000000"
preserveAspectRatio="xMidYMid meet">
<metadata>
Created by potrace 1.14, written by Peter Selinger 2001-2017
</metadata>
<g transform="translate(0.000000,157.000000) scale(0.100000,-0.100000)"
fill="#000000" stroke="none">
<path d="M156 1429 c-21 -17 -21 -18 -22 -611 0 -326 2 -601 4 -610 2 -10 23
-30 46 -45 l42 -28 582 1 583 0 21 22 22 22 1 586 0 586 -33 34 c-18 19 -39
34 -45 34 -7 0 -19 6 -25 13 -10 9 -141 12 -584 13 -525 0 -572 -1 -592 -17z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 748 B

14
static/site.webmanifest Normal file
View File

@ -0,0 +1,14 @@
{
"name": "",
"short_name": "",
"icons": [
{
"src": "/android-chrome-144x144.png",
"sizes": "144x144",
"type": "image/png"
}
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone"
}

1
themes/fuji Submodule

@ -0,0 +1 @@
Subproject commit bca1c2222aef812c840cf28d23f991dc1dae1599