index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
20,696
daigo0927/ctci-6th
refs/heads/master
/chap4/Q11.py
import os, sys sys.path.append(os.pardir) import random from utils.tree import TreeNode class Tree: def __init__(self): self.root = None def size(self): return self.root.size() if self.root is not None else 0 def get_random_node(self): if self.root is None: return None i = random.randint(0, self.size()-1) return self.root.get_ith_node(i) def insert_in_order(self, value): if self.root is None: self.root = TreeNode(value) else: self.root.insert_in_order(value) class TreeNode(TreeNode): def __init__(self, data): super().__init__(data) def get_ith_node(self, i): left_size = self.left.size() if self.left is not None else 0 if i < left_size: return self.left.get_ith_node(i) elif i == left_size: return self else: return self.right.get_ith_node(i - (left_size+1)) def insert_in_order(self, d): if d < self.data: if self.left is None: self.left = TreeNode(d) else: self.left.insert_in_order(d) else: if self.right is None: self.right = TreeNode(d) else: self.right.insert_in_order(d) self._size += 1 if __name__ == '__main__': counts = [0]*10 for i in range(10**5): t = Tree() array = [1, 0, 6, 2, 3, 9, 4, 5, 8, 7] for x in array: t.insert_in_order(x) d = t.get_random_node().data counts[d] += 1 for i in range(10): print(f'{i} : {counts[i]}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,697
daigo0927/ctci-6th
refs/heads/master
/chap8/Q3_advance.py
def magic_fast(array, start, end): if end < start: return -1 mid_index = (start + end)//2 mid_value = array[mid_index] if mid_value == mid_index: return mid_index # Search left left_index = min(mid_index-1, mid_value) left = magic_fast(array, start, left_index) if left >= 0: return left # Search right right_index = max(mid_index+1, mid_value) right = magic_fast(array, right_index, end) return right if __name__ == '__main__': array = [-10, -5, 2, 2, 2, 3, 4, 7, 9, 12, 13] print(f'{magic_fast(array, 0, len(array))} is the magix index in {array}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,698
daigo0927/ctci-6th
refs/heads/master
/chap8/Q13_alt1.py
class Box: def __init__(self, width, height, depth): self.width = width self.height = width self.depth = depth def is_smaller(self, box_tar): if self.width < box_tar.width and self.height < box_tar.height and self.depth < box_tar.depth: return True else: return False def create_stack(boxes, bottom_index, stack_map): if bottom_index < len(boxes) and stack_map[bottom_index] > 0: return stack_map[bottom_index] box_b = boxes[bottom_index] max_height = 0 for i in range(bottom_index+1, len(boxes)): if boxes[i].is_smaller(box_b): height = create_stack(boxes, i, stack_map) max_height = max(height, max_height) max_height += box_b.height stack_map[bottom_index] = max_height return max_height if __name__ == '__main__': boxes = [Box(6, 4, 4), Box(8, 6, 2), Box(5, 3, 3), Box(7, 8, 3), Box(4, 2, 2), Box(9, 7, 3)] boxes = sorted(boxes, key = lambda b: b.height, reverse = True) stack_map = [0]*len(boxes) max_height = create_stack(boxes, 0, stack_map) print(f'Max height is {max_height}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,699
daigo0927/ctci-6th
refs/heads/master
/chap4/Q10.py
import os, sys sys.path.append(os.pardir) from utils.misc import create_tree_from_array def contains_tree(tree1, tree2): """ Validate if tree1 contains tree2 """ string1 = get_order_string(tree1, '') string2 = get_order_string(tree2, '') print(string1, string2) return True if string2 in string1 else False def get_order_string(node, string): if node is None: string += "x" return string string += str(node.data) string = get_order_string(node.left, string) string = get_order_string(node.right, string) return string if __name__ == '__main__': # True case array1 = [1, 2, 1, 3, 1, 1, 5] array2 = [2, 3, 1] tree1 = create_tree_from_array(array1) tree2 = create_tree_from_array(array2) if contains_tree(tree1, tree2): print('tree2 is a subtree of tree1') else: print('tree2 is not a subtree of tree1') array3 = [1, 2, 3] tree3 = create_tree_from_array(array3) if contains_tree(tree1, tree3): print('tree3 is a subtree of tree1') else: print('tree3 is not a subtree of tree1')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,700
daigo0927/ctci-6th
refs/heads/master
/chap8/Q14.py
COUNT = 0 def count_eval(s, result): global COUNT COUNT += 1 if len(s) == 0: return 0 if len(s) == 1: return 1 if bool(s) == result else 0 ways = 0 for i in range(1, len(s), 2): c = s[i] left = s[0:i] right = s[i+1:len(s)] left_true = count_eval(left, True) left_false = count_eval(left, False) right_true = count_eval(right, True) right_false = count_eval(right, False) total = (left_true + left_false)*(right_true + right_false) total_true = 0 if c == '^': total_true = left_true*right_false + left_false*right_true elif c == '&': total_true = left_true*right_true elif c == '|': total_true = left_true*right_true + left_false*right_true + left_true*right_false sub_ways = total_true if result else total-total_true ways += sub_ways return ways if __name__ == '__main__': expression = "0^0|1&1^1|0|1" result = True ways = count_eval(expression, result) print(f'{ways}/{COUNT}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,701
daigo0927/ctci-6th
refs/heads/master
/chap8/Q13_alt2.py
class Box: def __init__(self, width, height, depth): self.width = width self.height = width self.depth = depth def is_smaller(self, box_tar): if self.width < box_tar.width and self.height < box_tar.height and self.depth < box_tar.depth: return True else: return False def create_stack(boxes, box_b, offset, stack_map): if offset >= len(boxes): return 0 box_b_new = boxes[offset] height_with_bottom = 0 if box_b is None or box_b_new.is_smaller(box_b): if stack_map[offset] == 0: stack_map[offset] = create_stack(boxes, box_b_new, offset+1, stack_map) stack_map[offset] += box_b_new.height height_with_bottom = stack_map[offset] height_without_bottom = create_stack(boxes, box_b, offset+1, stack_map) return max(height_with_bottom, height_without_bottom) if __name__ == '__main__': boxes = [Box(6, 4, 4), Box(8, 6, 2), Box(5, 3, 3), Box(7, 8, 3), Box(4, 2, 2), Box(9, 7, 3)] boxes = sorted(boxes, key = lambda b: b.height, reverse = True) stack_map = [0]*len(boxes) max_height = create_stack(boxes, None, 0, stack_map) print(f'Max height is {max_height}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,702
daigo0927/ctci-6th
refs/heads/master
/chap10/Q11_alt.py
def sort_valley_peak(array): for i in range(1, len(array), 2): biggest_index = max_index(array, i-1, i, i+1) if i != biggest_index: array = swap(array, i, biggest_index) return array def swap(array, left, right): tmp = array[left] array[left] = array[right] array[right] = tmp return array def max_index(array, a, b, c): l = len(array) a_value = array[a] if a >= 0 and a < l else -float('inf') b_value = array[b] if b >= 0 and b < l else -float('inf') c_value = array[c] if c >= 0 and c < l else -float('inf') max_value = max(a_value, b_value, c_value) if a_value == max_value: return a elif b_value == max_value: return b else: return c if __name__ == '__main__': array = [48, 40, 31, 62, 28, 21, 64, 40, 23, 17] print(f'original array : {array}') vp_array = sort_valley_peak(array) print(f'valley-peak array : {vp_array}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,703
daigo0927/ctci-6th
refs/heads/master
/chap5/Q1.py
def update_bits(n, m, i, j): """ Update given bits n by inserting m with j-i range Args: - int n: target value 1 to be inserted - int m: target value 2 to insert - int i, j: right and left locations of insertion Return: - int: updated (inserted) value """ # Problem regularization if i >= 32 or j < i: return 0 # Create a mask to clear bits i through j in n # EXAMPLE: i = 2, j = 4, reesult should be 11100011. all_ones = (1<<32)-1 left = all_ones<<(j+1) # 1s through position j, then 0s, left = 11100000 right = (1<<i)-1 # 1's after position i, right = 00000011 mask = left|right # All 1s, except for 0s between i and j, mask = 11100011 # Clear i through j, then put m in there n_cleared = n&mask # Clear bits j through i. m_shifted = m<<i # Move m into correct position # Get bit-or, and we're done! return n_cleared | m_shifted if __name__ == '__main__': a = 103217 print(f'a : {bin(a)}') b = 13 print(f'b : {bin(b)}') c = update_bits(a, b, 4, 12) print(f'c : {bin(c)}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,704
daigo0927/ctci-6th
refs/heads/master
/chap10/Q8.py
# This solution is a bit wring as the actual setting def find_dupricate_number(numbers): bit_field = [0]*(32000//8) dups = set([]) for n in numbers: if bit_field[(n-1)//8] & 1<<((n-1)%8): dups.add(n) else: bit_field[(n-1)//8] |= 1<<((n-1)%8) dups_ = [dups.pop() for _ in range(5)] print(f'{dups_} ... are opened') if __name__ == '__main__': import numpy as np # numbers does not nucessarily have whole number between 0-32000 numbers = np.random.random_integers(1, 32000, 40000) find_dupricate_number(numbers)
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,705
daigo0927/ctci-6th
refs/heads/master
/chap8/Q4.py
def get_subsets(set_, index): ''' Get subset of given set Args: - list<int> set_: target set - int index: index Returns: list<list<int>>: all subsets ''' if len(set_) == index: all_subsets = [[]] else: all_subsets = get_subsets(set_, index+1) item = set_[index] more_subsets = [] for subset in all_subsets: new_subset = subset + [item] more_subsets.append(new_subset) all_subsets += more_subsets return all_subsets if __name__ == '__main__': list_ = [1, 2, 3] print(f'Alls subsets of {list_} is') for subset in get_subsets(list_, 0): print(subset)
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,706
daigo0927/ctci-6th
refs/heads/master
/chap5/Q3_alt3.py
BYTES = 4 def flip_bit(a): if a&(a+1) == 0: return len(bin(a))-2 cur_length = 0 prev_length = 0 max_length = 0 while a != 0: if a&1 == 1: cur_length += 1 elif a&1 == 0: prev_length = 0 if a&2 == 0 else cur_length cur_length = 0 max_length = max(prev_length+cur_length+1, max_length) a >>= 1 return max_length if __name__ == '__main__': cases = [(0, 1), (1, 1), (15, 4), (1775, 8)] for num, ans in cases: x = flip_bit(num) result = 'valid' if x == ans else 'invalid' print(f'Case1 {num} -> {x}: {result}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,707
daigo0927/ctci-6th
refs/heads/master
/utils/linkedlist.py
class Node(object): def __init__(self, value, next_node=None, prev_node=None): self.value = value self.next = next_node self.prev = prev_node def __str__(self): return str(self.value) class LinkedList(object): def __init__(self, value=None): self.head = None self.tail = None if value is not None: self.append(value) def __len__(self): length = 0 node = self.head while node is not None: length += 1 node = node.next return length def __str__(self): values = [] node = self.head while node is not None: values.append(str(node)) node = node.next return '->'.join(values) def append(self, value): # append node to the tail of linkedlist, and return the tail node if self.head is None: self.tail = self.head = Node(value) else: self.tail.next = Node(value) self.tail = self.tail.next return self.tail def append_all(self, values): for v in values: self.append(v) return self.tail def pad_head(self): head_new = Node(0, next_node=self.head) self.head = head_new class DoublyLinkedList(LinkedList): def append(self, value): if self.head is None: self.tail = self.head = Node(value, next_node=None, prev_node=self.tail) else: self.tail.next = Node(value) self.tail = self.tail.next return
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,708
daigo0927/ctci-6th
refs/heads/master
/chap4/Q12_alt.py
import os, sys sys.path.append(os.pardir) from utils.tree import TreeNode def count_paths_with_sum(node, sum_tar, sum_run = 0, count_paths = dict()): """ Args: - TreeNode node: node of a tree - int sum_tar: target sum - int sum_run: sum of the running range - dictionary<int, int> count_paths: map from paths sum to count Returns: - int: total number of paths with target """ if node is None: return 0 sum_run += node.data # Count paths with sum ending at the current node sum_ = sum_run - sum_tar paths_total = count_paths.get(sum_, 0) # If sum_run equals sum_tar, one additional path starts at root. Add in this path if sum_run == sum_tar: paths_total += 1 # Add sum_run to count_paths count_paths = increment_hashtable(count_paths, sum_run, 1) # Count paths with sum on the left and right paths_total += count_paths_with_sum(node.left, sum_tar, sum_run, count_paths) paths_total += count_paths_with_sum(node.right, sum_tar, sum_run, count_paths) count_paths = increment_hashtable(count_paths, sum_run, -1) return paths_total def increment_hashtable(hashtable, key, delta): """ Increment the hash value specified by the given key Args: - dictionary<int, int> hashtable - int key: hashkey - int delta: increment value Returns: - dictionary<int, int>: incremented hashtable """ count_new = hashtable.get(key, 0) + delta if count_new == 0 and key in hashtable.keys(): # Remove if the value equals 0 to redume space usage hashtable.pop(key) else: hashtable[key] = count_new return hashtable if __name__ == '__main__': # Tree1 root1 = TreeNode(5); root1.left = TreeNode(3) root1.right = TreeNode(1) root1.left.left = TreeNode(-8) root1.left.right = TreeNode(8) root1.right.left = TreeNode(2) root1.right.right = TreeNode(6) ans1 = count_paths_with_sum(root1, 0) print(f'Tree1 contains {ans1} of with {0} summation') # Tree2 root2 = TreeNode(-7) root2.left = TreeNode(-7) root2.left.right = TreeNode(1) root2.left.right.left = TreeNode(2) root2.right = TreeNode(7) root2.right.left = TreeNode(3) root2.right.right = TreeNode(20) root2.right.right.left = TreeNode(0) root2.right.right.left.left = TreeNode(-3) root2.right.right.left.left.right = TreeNode(2) root2.right.right.left.left.right.left = TreeNode(1) ans2 = count_paths_with_sum(root2, -14) print(f'Tree2 contains {ans2} of with {-14} summation') # Tree3 root3 = TreeNode(0) root3.left = TreeNode(0) root3.right = TreeNode(0) root3.right.left = TreeNode(0) root3.right.left.right = TreeNode(0) root3.right.right = TreeNode(0) ans3 = count_paths_with_sum(root3, 0) ans4 = count_paths_with_sum(root3, 4) print(f'Tree3 contains {ans3} of with {0} summation') print(f'Tree3 contains {ans4} of with {4} summation')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,709
daigo0927/ctci-6th
refs/heads/master
/chap8/Q6.py
from collections import deque class Tower(object): def __init__(self, i): self.disks = deque([]) self.index = i def add(self, d): if len(self.disks) < 0 and self.disks[-1] <= d: print(f'Error for placing disk size {d}') else: self.disks.append(d) def move_to_top(self, t): top = self.disks.pop() t.add(top) return t def print(self): print(f'Contents of tower {self.index} : {list(self.disks)}') def move_disks(self, n, t_dest, t_buff): if n > 0: tag = f'move {n} disks from {self.index} to {t_dest.index} with buffer {t_buff.index}' print(f'<{tag}>') self.move_disks(n-1, t_buff, t_dest) # print(f'<move top from {self.index} to {t_dest.index}>') # print('<before>') # print('<source print>') # self.print() # print(f'</source print>') # print('<dest print>') # print('<before>') t_dest = self.move_to_top(t_dest) # print('<after>') # print('<source print>') self.print() # print('</source print>') # print('dest print') t_dest.print() # print('</dest print>') # print('</after>') # print(f'</move top from {self.index} to {t_dest.index}>') t_buff.move_disks(n-1, t_dest, self) print(f'</{tag}>') if __name__ == '__main__': n = 3 towers = [Tower(i) for i in range(3)] for i in range(n, 0, -1): towers[0].add(i) towers[0].move_disks(n, towers[2], towers[1])
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,710
daigo0927/ctci-6th
refs/heads/master
/chap5/Q4_alt2.py
""" An arithmetic solution """ def get_next_arith(n): c = n c0 = 0 c1 = 0 while c&1 == 0 and c != 0: c0 += 1 c >>= 1 while c&1 == 1: c1 += 1 c >>= 1 if c0+c1 == 31 or c0+c1 == 0: return -1 # Arithmetically, # 2^c0 = 1 << c0 # 2^(c1-1) = 1 << (c0 - 1) # next = n + 2^c0 + 2^(c1-1) - 1 return n + (1<<c0) + (1<<(c1-1)) - 1 def get_prev_arith(n): tmp = n c0 = 0 c1 = 0 while tmp&1 == 1 and tmp != 0: c1 += 1 tmp >>= 1 if tmp == 0: return -1 while tmp&1 == 0 and tmp != 0: c0 += 1 tmp >>= 1 # Arithmetically, # 2^c1 = 1 << c1 # 2^(c0 - 1) = 1 << (c0 - 1) return n - (1<<c1) - (1<<(c0-1)) + 1 if __name__ == '__main__': i = 13948 p1 = get_prev_arith(i) n1 = get_next_arith(i) print(f'Previous : {p1} : {bin(p1)}') print(f'Target : {i} : {bin(i)}') print(f'Next : {n1} : {bin(n1)}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,711
daigo0927/ctci-6th
refs/heads/master
/chap8/Q2.py
def get_path(maze): ''' Get available # of paths Args: int[][] maze: maze 2-dim list Returns: int: # of paths ''' if maze is None or len(maze) == 0: return None path = [] if is_path(maze, len(maze)-1, len(maze[0])-1, path): return path return None def is_path(maze, row, col, path): if col < 0 or row < 0 or not maze[row][col]: return False at_origin = (row == 0) and (col == 0) if at_origin or is_path(maze, row, col-1, path) or is_path(maze, row-1, col, path): point = (row, col) path.append(point) return True return False if __name__ == '__main__': row, col = 3, 4 maze = [[True]*col for _ in range(row)] forbid_y, forbid_x = 1, 2 maze[forbid_y][forbid_x] = False print(get_path(maze))
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,712
daigo0927/ctci-6th
refs/heads/master
/chap10/Q4.py
# Unable to use len(array) class Listy: def __init__(self, array): self.array = array def __len__(self): raise NotImplementedError('len(listy) is not implemented') def element_at(self, index): # only internally able to get size if index >= len(self.array): return -1 else: return self.array[index] def binary_search(listy, value, low, high): while low <= high: mid = (low+high)//2 middle = listy.element_at(mid) if middle > value or middle == -1: high = mid-1 elif middle < value: low = mid+1 else: return mid return -1 def search(listy, value): index = 1 while listy.element_at(index) != -1 and listy.element_at(index) < value: index *= 2 return binary_search(listy, value, index//2, index) if __name__ == '__main__': array = [1, 2, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 16, 18] listy = Listy(array) for a in array: print(f'{a} is at {search(listy, a)}') print(f'{15} is at {search(listy, 15)}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,713
daigo0927/ctci-6th
refs/heads/master
/chap8/Q2_alt.py
def get_path_memorized(maze): ''' Get path by memolization Args: bool[][] maze: target maze by 2D list Returns: list<tuple(int*2)> path ''' if maze == None or len(maze) == 0: return None path = [] failed_points = [] if is_path_memorized(maze, len(maze)-1, len(maze[0])-1, path, failed_points): return path return None def is_path_memorized(maze, row, col, path, failed_points): if col < 0 or row < 0 or not maze[row][col]: return False point = (row, col) if point in failed_points: return False at_origin = (row == 0) and (col == 0) if at_origin or is_path_memorized(maze, row-1, col, path, failed_points) \ or is_path_memorized(maze, row, col-1, path, failed_points): path.append(point) return True failed_points.append(point) return False if __name__ == '__main__': row, col = 3, 4 maze = [[True]*col for _ in range(row)] forbid_y, forbid_x = 1, 2 maze[forbid_y][forbid_x] = False print(get_path_memorized(maze))
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,714
daigo0927/ctci-6th
refs/heads/master
/chap5/Q2.py
def print_binary(num): """ Return binary representation of 0-1 real value Args: - float num: target value Returns: - str: binary representation of input value """ if num >= 1 or num <= 0: return 'ERROR' binary = '.' while num > 0: if len(binary) > 32: return 'ERROR' r = num*2 if r >= 1: binary += '1' num = r-1 else: binary += '0' num = r return binary def print_binary2(num): """ Alternative solution """ if num >= 1 or num <= 0: return 'ERROR' binary = '.' frac = 0.5 while num > 0: # Setting a limit on length: 32 characters if len(binary) >= 32: return 'ERROR' if num >= frac: binary += '1' num -= frac else: binary += '0' frac /= 2 return binary if __name__ == '__main__': bs = print_binary(0.125) print(bs) for i in range(1000): num = i/1000. binary = print_binary(num) binary2 = print_binary2(num) if binary != 'ERROR' or binary2 != 'ERROR': print(f'{num} : {binary} {binary2}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,715
daigo0927/ctci-6th
refs/heads/master
/chap8/Q1.py
def count_ways(n): ''' Count the number of paths by recursive operation Args: int n: # of stairs Returns: int: patterns of path ''' if n < 0: return 0 elif n == 0: return 1 else: return count_ways(n-1) + count_ways(n-2) + count_ways(n-3) if __name__ == '__main__': n = 20 ways = count_ways(n) print(f'{ways} ways found.')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,716
daigo0927/ctci-6th
refs/heads/master
/chap5/Q4_alt1.py
def get_next(n): c = n c0 = 0 c1 = 0 while c&1 == 0 and c != 0: c0 += 1 c >>= 1 while c&1 == 1: c1 += 1 c >>= 1 # If c is 0, then n is a sequence of 1s followed by a sequence of 0s. # This is already the biggest number with c1 ones. Return error if c0+c1 == 31 or c0+c1 == 0: return -1 # Position of right-most non-trailing 0 (where the right most bit is bit 0) pos = c0+c1 # Flip the right-most non-trailing 0 (which will be at position pos) n |= (1<<pos) # Clear all bits to the right of pos n &= ~((1<<pos) - 1) # Put (ones-1) 1s on the right n |= (1 << (c1-1)) - 1 return n def get_prev(n): tmp = n c0 = 0 c1 = 0 while tmp&1 == 1: c1 += 1 tmp >>= 1 # If tmp is 0, then the number is a sequence of 0s folowed by a sequence of 1s, # This is already the smallest number with c1 ones. Return -1 for an error if tmp == 0: return -1 while tmp&1 == 0 and tmp != 0: c0 += 1 tmp >>= 1 # Position od right-most non-trailing one (where the right most bit is bit 0) p = c0+c1 # Flip right-most non-trailing one. # Clears from bit p onwards (to the right) n &= ((~0) << (p+1)) # Create a sequence of (c1+1) 1s. # Sequence of (c1+1) ones mask = (1<<(c1+1))- 1 # Move the ones to be right up next to bit p n |= mask << (c0-1) return n if __name__ == '__main__': i = 13948 p1 = get_prev(i) n1 = get_next(i) print(f'Previous : {p1} : {bin(p1)}') print(f'Target : {i} : {bin(i)}') print(f'Next : {n1} : {bin(n1)}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,717
daigo0927/ctci-6th
refs/heads/master
/chap2/linkedlist.py
class Node: """ import linkedlistがなぜかimportできないので、自分で書く """ def __init__(self, d=None): self.data = d self.next = None # odeを受け渡すようにすると多分ポインター参照になるらし def appendToTail(self, d=None): end = Node(d) # あたらしいノード n = self # 一番終端のノードまで移動する必要がある。 while (n.next != None): n = n.next n.next = end def appendNodeToTail(self, node): n = self # 一番終端のノードまで移動する必要がある。 while (n.next != None): n = n.next n.next = node def printls(self): n = self while n.next != None: print(n.data, end=", ") n = n.next print(n.data) def get_Nth_node(self, N): """ 配列ライクにN番目のノードを返す(データではない) """ n = self if N < 0: print("Index out of bound. return the first node") for _ in range(N): if n.next == None: print("Index out of bound. return the last node") break n = n.next return n def remove_Nth_node(self, N): if N == 0: print( "there is a bug. please use \"get_Nth_node(1)\" to remove the first Node.") # ここにバグが有ってなぜか1つ目の自分自身のポインターが書き換わらない n = self n = n.next else: prerm = self.get_Nth_node(N - 1) # 削除したいノードの一つ前のリンクを書き換える必要がある prerm.next = self.get_Nth_node(N).next #. -> . ->(この矢印を書き換える必要がある) .(削除したい) -> . if __name__ == "__main__": nd = Node(1) nd.appendToTail(3) nd.appendToTail(5) nd.appendToTail(7) nd.appendToTail(9) nd.printls() print(nd.get_Nth_node(3).data) print(nd.get_Nth_node(4).data) print(nd.get_Nth_node(5).data) nd.remove_Nth_node(3) nd.printls()
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,718
daigo0927/ctci-6th
refs/heads/master
/chap2/Q5.py
import os, sys sys.path.append(os.pardir) from utils.linkedlist import LinkedList def solve(llist_1, llist_2): n1, n2 = llist_1.head, llist_2.head llist_ans = LinkedList() carry = 0 while n1 is not None or n2 is not None: result = carry if n1 is not None: result += n1.value n1 = n1.next if n2 is not None: result += n2.value n2 = n2.next llist_ans.append(result%10) carry = result//10 if carry > 0: llist_ans.append(carry) print(f'{str(llist_1)} + {str(llist_2)} = {llist_ans}') def solve2(llist_1, llist_2): if len(llist_1) > len(llist_2): for _ in range(len(llist_1) - len(llist_2)): llist_2.pad_head() elif len(llist_2) > len(llist_1): for _ in range(len(llist_2) - len(llist_1)): llist_1.pad_head() n1, n2 = llist_1.head, llist_2.head llist_ans = LinkedList() result = 0 while n1 is not None and n2 is not None: result = 10*result+n1.value+n2.value n1 = n1.next n2 = n2.next for v in str(result): llist_ans.append(int(v)) print(f'{str(llist_1)} + {str(llist_2)} = {llist_ans}') if __name__ == '__main__': llist_1, llist_2 = LinkedList(), LinkedList() llist_1.append_all([7, 1, 6]) llist_2.append_all([5, 9, 2]) solve(llist_1, llist_2) llist_1, llist_2 = LinkedList(), LinkedList() llist_1.append_all([1, 2, 3, 4]) llist_2.append_all([5, 6, 7]) solve2(llist_1, llist_2)
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,719
daigo0927/ctci-6th
refs/heads/master
/chap10/Q1.py
def merge(a, b, lastA, lastB): index_merged = lastB + lastA - 1 indexA = lastA - 1 indexB = lastB - 1 while indexB >= 0: if indexA >= 0 and a[indexA] > b[indexB]: a[index_merged] = a[indexA] indexA -= 1 else: a[index_merged] = b[indexB] indexB -= 1 index_merged -= 1 return a if __name__ == '__main__': a = [2, 3, 4, 5, 6, 8, 10, 100, 0, 0, 0, 0, 0, 0] b = [1, 4, 7, 6, 7, 7] merged = merge(a, b, 8, 6) print(merged)
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,720
daigo0927/ctci-6th
refs/heads/master
/chap8/Q1_alt.py
def count_ways(n): ''' Count ways of upstairs Args: int n: # of upstairs Returns: int: ways ''' map_ = [-1]*(n+1) return count_ways_(n, map_) def count_ways_(n, memo): ''' Memorize and calculate ways Args: - int n: # of current stair - int[] memo: memo of observed result Returns: int: sum of ways ''' if n < 0: return 0 elif n == 0: return 1 elif memo[n] > -1: return memo[n] else: memo[n] = count_ways_(n-1, memo) + count_ways_(n-2, memo) + count_ways_(n-3, memo) return memo[n] if __name__ == '__main__': n = 20 ways = count_ways(n) print(f'{ways} ways found.')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,721
daigo0927/ctci-6th
refs/heads/master
/utils/misc.py
from collections import deque from .tree import TreeNode def create_tree_from_array(array): """ Create tree by mapping the array left to right, top to bottom Args: - list array: list of contents values Returns: - TreeNode root: root node """ if len(array) > 0: root = TreeNode(array[0]) que = deque() que.append(root) done = False i = 1 while not done: r = que[0] if r.left is None: r.left = TreeNode(array[i]) i += 1 que.append(r.left) elif r.right is None: r.right = TreeNode(array[i]) i += 1 que.append(r.right) else: _ = que.popleft() if i == len(array): done = True return root else: return None
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,722
daigo0927/ctci-6th
refs/heads/master
/chap10/Q3.py
def search(a, x): return _search(a, 0, len(a)-1, x) def _search(a, left, right, x): mid = (left + right)//2 if x == a[mid]: return mid if right < left: return -1 # Operation for inflection point caused by rotation if a[left] < a[mid]: if x >= a[left] and x < a[mid]: return _search(a, left, mid-1, x) else: return _search(a, mid+1, right, x) elif a[mid] < a[left]: if x > a[mid] and x <= a[right]: return _search(a, mid+1, right, x) else: return _search(a, left, mid-1, x) elif a[left] == a[mid]: if a[mid] != a[right]: return _search(a, mid+1, right, x) else: result = _search(a, left, mid-1, x) if result == -1: return _search(a, mid+1, right, x) else: return result return -1 if __name__ == '__main__': a = [2, 3, 1, 2, 2, 2, 2, 2, 2, 2, 2] for n in [2, 3, 4, 1, 8]: print(f'{n} is at {search(a, n)}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,723
daigo0927/ctci-6th
refs/heads/master
/chap5/Q8.py
def compute_byte_num(width, x, y): return (width*y + x) // 8 def draw_line(screen, width, x1, x2, y): start_offset = x1%8 first_full_bytes = x1//8 if start_offset != 0: first_full_bytes += 1 end_offset = x2%8 last_full_bytes = x2//8 if end_offset != 7: last_full_bytes -= 1 for b in range(first_full_bytes, last_full_bytes+1): screen[(width//8) * y + b] = 0xFF start_mask = 0xFF>>start_offset end_mask = ~(0xFF>>(end_offset+1)) if x1//8 == x2//8: mask = start_mask&end_mask screen[(width//8) * y + (x1 // 8)] |= mask else: if start_offset != 0: byte_number = (width//8) * y + first_full_bytes - 1 screen[byte_number] |= start_mask if end_offset != 7: byte_number = (width//8) * y + last_full_bytes + 1 screen[byte_number] |= end_mask return screen def print_byte(b): for i in range(7, -1, -1): c = '1' if (b>>i)&1 == 1 else '_' print(c, end = "") def print_screen(screen, width): height = len(screen)*8//width for r in range(height): for c in range(0, width, 8): b = screen[compute_byte_num(width, c, r)] print_byte(b) print('') if __name__ == '__main__': width = 8*1 height = 1 for r in range(height): for c1 in range(width): for c2 in range(c1, width, 2): screen = [0]*(width*height//8) print(f'Row {r} : {c1} -> {c2} : ', end = '') screen = draw_line(screen, width, c1, c2, r) print_screen(screen, width)
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,724
daigo0927/ctci-6th
refs/heads/master
/chap2/Q7.py
import os, sys sys.path.append(os.pardir) from utils.linkedlist import Node, LinkedList def is_shared(llist_1, llist_2): if llist_1.tail is not llist_2.tail: return False n1, n2 = llist_1.head, llist_2.head if len(llist_1) > len(llist_2): for _ in range(len(llist_1) - len(llist_2)): n1 = n1.next elif len(llist_2) > len(llist_1): for _ in range(len(llist_2) - len(llist_1)): n2 = n2.next while n1 is not None and n2 is not None: if n1 is n2: return n1 n1 = n1.next n2 = n2.next if __name__ == '__main__': # case1 llist_1, llist_2 = LinkedList(), LinkedList() llist_1.append_all([3, 1, 5, 9]) llist_2.append_all([4, 6]) for v in [7, 2, 1]: tail_new = Node(v) llist_1.tail.next = tail_new llist_1.tail = tail_new llist_2.tail.next = tail_new llist_2.tail = tail_new ans = is_shared(llist_1, llist_2) print(f'{str(llist_1)} and {str(llist_2)} share? {ans}') llist_1, llist_2 = LinkedList(), LinkedList() llist_1.append_all([3, 1, 5, 9, 7, 2, 1]) llist_2.append_all([4, 6, 7, 2, 1]) ans = is_shared(llist_1, llist_2) print(f'{str(llist_1)} and {str(llist_2)} share? {ans}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,725
daigo0927/ctci-6th
refs/heads/master
/chap5/Q4.py
""" The most simple but cheap solution """ def count_ones(i): count = 0 while i > 0: if i&1 == 1: count += 1 i >>= 1 return count def count_zeros(i): return 32 - count_ones(i) def has_valid_next(i): if i == 0: return False count = 0 while i&1 == 0: i >>= 1 count += 1 while i&1 == 1: i >>= 1 count += 1 if count == 31: return False return True def has_valid_prev(i): while i&1 == 1: i >>= 1 return True if i != 0 else False def get_next_slow(i): if not has_valid_next(i): return -1 num_ones = count_ones(i) i += 1 while count_ones(i) != num_ones: i += 1 return i def get_prev_slow(i): if not has_valid_prev(i): return -1 num_ones = count_ones(i) i -= 1 while count_ones(i) != num_ones: i -= 1 return i if __name__ == '__main__': i = 13948 p1 = get_prev_slow(i) n1 = get_next_slow(i) print(f'Previous : {p1} : {bin(p1)}') print(f'Target : {i} : {bin(i)}') print(f'Next : {n1} : {bin(n1)}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,726
daigo0927/ctci-6th
refs/heads/master
/chap2/Q8.py
import os, sys sys.path.append(os.pardir) from utils.linkedlist import LinkedList def search(llist): fast = llist.head slow = llist.head # Running until correlation while fast is not None and fast.next is not None: fast = fast.next.next slow = slow.next if fast is slow: break if fast is None or fast.next is None: # loop absence return False fast = llist.head while fast is not slow: fast = fast.next slow = slow.next return fast if __name__ == '__main__': # create looping linkedlist llist = LinkedList() llist.append_all([0, 9, 1, 8]) loop_head = llist.tail llist.append_all([2, 4, 7, 3, 5, 6]) llist.tail.next = loop_head n = llist.head for _ in range(15): if n is loop_head: print(str(n)+'(loop head)', end = ', ') else: print(str(n), end = ', ') n = n.next ans = search(llist) print(f'\nLoop head is {ans}.')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,727
daigo0927/ctci-6th
refs/heads/master
/chap10/Q2.py
def sort(array): map_list = {} for string in array: key = sort_chars(string) if not key in map_list.keys(): map_list[key] = [string] else: map_list[key].append(string) index = 0 for key in map_list.keys(): for t in map_list[key]: array[index] = t index += 1 return array def sort_chars(s): return ''.join(sorted(list(s))) if __name__ == '__main__': array = ["apple", "banana", "carrot", "ele", "duck", "papel", "tarroc", "cudk", "eel", "lee"] array = sort(array) print(array)
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,728
daigo0927/ctci-6th
refs/heads/master
/chap5/Q6_alt.py
def bit_swap_required(a, b): count = 0 if a > 0 and b < 0: b = abs(b) count += 1 elif a < 0 and b > 0: a = abs(a) count += 1 c = a^b while c != 0: count += 1 c = c&(c-1) return count if __name__ == '__main__': a = -23432 b = 512132 ans = bit_swap_required(a, b) print(f'{ans} bit required to convert {bin(a)} <-> {bin(b)}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,729
daigo0927/ctci-6th
refs/heads/master
/chap10/Q7.py
# This solution is a bit wring as the actual setting def find_open_number(numbers): bit_field = [0]*(2**16//8) for n in numbers: bit_field[n//8] |= 1<<(n%8) opens = [] for i in range(len(bit_field)): for j in range(8): if bit_field[i] & (1<<j) == 0: opens.append(i*8+j) print(f'{opens[:5]} ... are opened') if __name__ == '__main__': import numpy as np numbers = np.random.random_integers(0, 2**15, 2**16) find_open_number(numbers)
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,730
daigo0927/ctci-6th
refs/heads/master
/chap8/Q12.py
GRID_SIZE = 8 def place_queens(row, cols, results): if row == GRID_SIZE: # results.append(cols) return 1 else: ways = 0 for col in range(GRID_SIZE): if check_valid(cols, row, col): cols[row] = col # results = place_queens(row+1, cols, results) ways += place_queens(row+1, cols, results) return ways def check_valid(cols, row1, col1): for row2 in range(row1): col2 = cols[row2] if col1 == col2: return False col_dist = abs(col2 - col1) row_dist = row1 - row2 if col_dist == row_dist: return False return True if __name__ == '__main__': results = [] cols = [-1]*GRID_SIZE ways = place_queens(0, cols, results) print(f'8x8 board has {ways} patterns of queen placements')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,731
daigo0927/ctci-6th
refs/heads/master
/chap10/Q5.py
def search(strings, string, first, last): if strings is None or string is None or string == '': return -1 if first > last: return -1 mid = (last + first)//2 if strings[mid] == '': left = mid-1 right = mid+1 while True: if left < first and right > last: return -1 elif right <= last and strings[right] != '': mid = right break elif left >= first and strings[left] != '': mid = left break right += 1 left += 1 if string == strings[mid]: return mid elif strings[mid] < string: return search(strings, string, mid+1, last) else: return search(strings, string, first, mid-1) if __name__ == '__main__': strings = ['apple', '', '', 'banana', '', '', '', 'carrot', 'duck', '', '', 'eel', '', 'flower'] for string in strings: print(f"{string} is at {search(strings, string, 0, len(strings)-1)}")
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,732
daigo0927/ctci-6th
refs/heads/master
/chap2/Q4_partition.py
""" 大小比較して前半のリストと後半のリストをべっこに作り後から連結すれば良い """ from linkedlist import Node def partation(ll, K): """ Kの大きさで分割して並び替えたものを返す。 """ n = ll left, right = Node(), Node() while True: if n.data < K: left.appendToTail(n.data) else: right.appendToTail(n.data) if n.next == None: break n = n.next # これだと宣言の関係上一番始めがNoneになっているのでとりのぞいてから連結する right = right.get_Nth_node(1) left = left.get_Nth_node(1) left.appendNodeToTail(right) return left if __name__ == "__main__": ls = Node(1) ls.appendToTail(10) ls.appendToTail(3) ls.appendToTail(4) ls.appendToTail(5) ls.appendToTail(6) ls.appendToTail(5) ls.appendToTail(8) ls.appendToTail(9) ls.appendToTail(10) ls.printls() new = partation(ls, 5) new.printls()
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,733
daigo0927/ctci-6th
refs/heads/master
/chap2/Q1_remove_dups.py
from linkedlist import Node # すでにある要素をハッシュマップで記録しておけば良い。つまり def remove_dups(ll): """ llはlinkedlist(のつもりだが受け渡す**実体はあるNode**) """ # llから見て何番目を削除するかのカウンター n = ll prev = None isunique = {} while n != None: if n.data in isunique.keys(): prev.next = n.next # uniqueじゃなければprevを動かさない else: # uniqueだったらprevを一個ずれす prev = n isunique[n.data] = True n = n.next # 次のnodeについて考える if __name__ == "__main__": ls = Node(1) ls.appendToTail(2) ls.appendToTail(3) ls.appendToTail(5) # opps ls.appendToTail(5) ls.appendToTail(6) ls.appendToTail(7) ls.appendToTail(2) # opps ls.appendToTail(9) ls.appendToTail(10) ls.appendToTail(10) # opps ls.appendToTail(2) # opps ls.appendToTail(7) # opps ls.printls() remove_dups(ls) ls.printls()
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,734
daigo0927/ctci-6th
refs/heads/master
/chap5/Q3_alt1.py
def longest_seq(n): """ Get the length of the longest 1s sequence Args: int n: input number Returns: int: length of the longest sequence """ if n == -1: raise ValueError('Invalid argument for n : {n}') seqs = get_alternating_seqs(n) return find_longest_seq(seqs) def get_alternating_seqs(n): """ Get alternating sequences by flipping 0 and 1 Args: int n: input number Returns: list<int>: list of length of 1s or 0s sequences """ seqs = [] searching_for = 0 counter = 0 for i in range(len(bin(n))-2): if (n&1) != searching_for: seqs.append(counter) searching_for = n&1 counter = 0 counter += 1 n >>= 1 seqs.append(counter) return seqs def find_longest_seq(seq): """ Find the longest sequence allowing 0-1 flip Args: list<int> seq: target sequences Returns: int: length of the longest sequence """ max_seq = 1 for i in range(0, len(seq), 2): zeros_seq = seq[i] ones_seq_left = seq[i-1] if i-1 >= 0 else 0 ones_seq_right = seq[i+1] if i+1 < len(seq) else 0 this_seq = 0 if zeros_seq == 1: # Can merge this_seq = ones_seq_left + 1 + ones_seq_right elif zeros_seq > 1: # Just add a zero to either side this_seq = 1+max(ones_seq_right, ones_seq_left) elif zeros_seq == 0: # No zero, but take either side this_seq = max(ones_seq_right, ones_seq_left) max_seq = max(this_seq, max_seq) return max_seq if __name__ == '__main__': num = 1775 ans = longest_seq(num) print(f'{num} -> {ans}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,735
daigo0927/ctci-6th
refs/heads/master
/chap10/Q9_alt.py
class Coordinate: def __init__(self, r, c): self.row = r self.col = c def inbounds(self, matrix): return self.row >= 0 and self.col >= 0\ and self.row < len(matrix) and self.col < len(matrix[0]) def is_before(self, p): return self.row <= p.row and self.col <= p.col def clone(self): return Coordinate(self.row, self.col) def move_down_right(self): self.row += 1 self.col += 1 def set_to_average(self, cood_min, cood_max): self.row = (cood_min.row + cood_max.row)//2 self.col = (cood_min.col + cood_max.col)//2 def partition_and_search(matrix, origin, dest, pivot, x): lower_left_origin = Coordinate(pivot.row, origin.col) lower_left_dest = Coordinate(dest.row, pivot.col-1) upper_right_origin = Coordinate(origin.row, pivot.col) upper_right_dest = Coordinate(pivot.row-1, dest.col) lower_left = find_element(matrix, lower_left_origin, lower_left_dest, x) if lower_left is None: return find_element(matrix, upper_right_origin, upper_right_dest, x) return lower_left def find_element(matrix, origin, dest, x): if not origin.inbounds(matrix) or not dest.inbounds(matrix): return None if matrix[origin.row][origin.col] == x: return origin elif not origin.is_before(dest): return None # Set start to start of diagonal and end to the end of the diagonal # Since the grid may not be square, the end of the diagonal may not equal dest. start = origin.clone() diag_dist = min(dest.row-origin.row, dest.col-origin.col) end = Coordinate(start.row+diag_dist, dest.col-origin.col) p = Coordinate(0, 0) # Do binary search on the diagonal, looking for the dirst element greater than x while start.is_before(end): p.set_to_average(start, end) if x > matrix[p.row][p.col]: start.row = p.row+1 start.col = p.col+1 else: end.row = p.row-1 end.col = p.col-1 return partition_and_search(matrix, origin, dest, start, x) if __name__ == '__main__': matrix = [[15, 30, 50, 70, 73], [35, 40, 100, 102, 120], [36, 42, 105, 110, 125], [46, 51, 106, 111, 130], [48, 55, 109, 140, 150]] elem = 111 cood_origin = Coordinate(0, 0) cood_dest = Coordinate(4, 4) c = find_element(matrix, cood_origin, cood_dest, elem) if c is not None: print(f'{elem} is at row:{c.row}, col:{c.col} of below') for m in matrix: print(m) else: print(f'{elem} cound not be found')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,736
daigo0927/ctci-6th
refs/heads/master
/chap5/Q7.py
def swap_odd_even_bits(x): return ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1) if __name__ == '__main__': a = 234321 b = swap_odd_even_bits(a) print(f'Original : {bin(a)}') print(f'Swapped : {bin(b)}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,737
daigo0927/ctci-6th
refs/heads/master
/chap5/Q3.py
SEQ_LENGTH = 32 def get_bit(num, i): """ Return if i-th digit of given number is 1:True or 0:False Args: - int num: given number - int i: target digit Returns: - bool: if i-th digits is 1 or 0 """ return (num&(1<<i)) != 0 def longest_seq(n): """ Get longest 1s sequence of input value with flip each bit Args: - int n: input value Return: - int: maximum length of 1s sequences """ max_seq = 0 for i in range(SEQ_LENGTH): max_seq = max(max_seq, longest_seq_of_1s(n, i)) return max_seq def longest_seq_of_1s(n, index_to_ignore): """ Get longest length of 1s sequences Args: - int n: input value - int index_to_ignore: flipped (= ignored) index Returns: - int: length of longest 1s sequence """ max_ = 0 counter = 0 for i in range(SEQ_LENGTH): if i == index_to_ignore or get_bit(n, i): counter += 1 max_ = max(counter, max_) else: counter = 0 return max_ if __name__ == '__main__': num = 1775 ans = longest_seq(num) print(f'{num} -> {ans}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,738
daigo0927/ctci-6th
refs/heads/master
/chap2/Q2_Kth_to_last.py
from linkedlist import Node as _Node # 愚直に最後まで数える方法 class Node(_Node): def show_Kth_to_last(self, K): lencount = 0 n = self # 一番終端のノードまで移動する回数がつまりリストの長さ。 while (n.next != None): lencount += 1 n = n.next #後ろからK番目はつまりlencount - K番目 # 後ろから0番目を最後のノードだと定義して print(self.get_Nth_node(lencount - K).data) if __name__ == "__main__": ls = Node(1) ls.appendToTail(2) ls.appendToTail(3) ls.appendToTail(4) ls.appendToTail(5) ls.appendToTail(6) ls.appendToTail(7) ls.appendToTail(8) # opps ls.appendToTail(9) ls.appendToTail(10) ls.printls() ls.show_Kth_to_last(0) ls.show_Kth_to_last(3) ls.show_Kth_to_last(12) ls.show_Kth_to_last(-3)
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,739
daigo0927/ctci-6th
refs/heads/master
/chap2/Q6.py
import os, sys sys.path.append(os.pardir) from utils.linkedlist import LinkedList def is_palindrome(llist): # runner technique, method2 fast = llist.head slow = llist.head stack = [] while fast is not None and fast.next is not None: stack.append(slow.value) fast = fast.next.next slow = slow.next if fast is not None: # when the llist length is odd, skip the meddle node slow = slow.next while slow is not None: if stack[-1] != slow.value: return False else: stack = stack[:-1] slow = slow.next return True if __name__ == '__main__': cases = [[1, 2, 3, 2, 1], [1, 2, 5, 2, 4], [1,1, 2, 2, 1, 1]] for case in cases: llist = LinkedList() llist.append_all(case) ans = is_palindrome(llist) print(f'{str(llist)} is palindrome? : {ans}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,740
daigo0927/ctci-6th
refs/heads/master
/chap10/Q11.py
def sort_valley_peak(array): array = sorted(array) for i in range(1, len(array), 2): array = swap(array, i-1, i) return array def swap(array, left, right): tmp = array[left] array[left] = array[right] array[right] = tmp return array if __name__ == '__main__': array = [48, 40, 31, 62, 28, 21, 64, 40, 23, 17] print(f'original array : {array}') vp_array = sort_valley_peak(array) print(f'valley-peak array : {vp_array}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,741
daigo0927/ctci-6th
refs/heads/master
/chap10/Q10.py
class RankNode: def __init__(self, d): self.data = d self.left_size = 0 self.left = None self.right = None def insert(self, d): if d <= self.data: if self.left is not None: self.left.insert(d) else: self.left = RankNode(d) self.left_size += 1 else: if self.right is not None: self.right.insert(d) else: self.right = RankNode(d) def get_rank(self, d): if d == self.data: return self.left_size elif d < self.data: if self.left is None: return -1 else: return self.left.get_rank(d) else: right_rank = -1 if self.right is None else self.right.get_rank(d) if right_rank == -1: return -1 else: return self.left_size+1+right_rank def track(root, number): if root is None: root = RankNode(number) else: root.insert(number) return root def get_rank_of_number(root, number): return root.get_rank(number) if __name__ == '__main__': root = None numbers = [5, 1, 4, 4, 5, 9, 7, 13, 3] for n in numbers: root = track(root, n) for n in [1, 3, 4]: rank = get_rank_of_number(root, n) print(f'{n} is {rank}-rank at {numbers}')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,742
daigo0927/ctci-6th
refs/heads/master
/chap8/Q5_alt2.py
def min_product(a, b): bigger = b if a < b else a smaller = a if a < b else b return min_product_helper(smaller, bigger) def min_product_helper(smaller, bigger): global counter if smaller == 0: return 0 elif smaller == 1: return bigger s = smaller>>1 half_prod = min_product_helper(s, bigger) if smaller%2 == 0: counter += 1 return half_prod + half_prod else: counter += 2 return half_prod + half_prod + bigger if __name__ == '__main__': counter = 0 a, b = 13494, 22323 product = a*b min_prod = min_product(a, b) print(f'Calculate result {min_prod}({product == min_prod}) with {counter}.')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,743
daigo0927/ctci-6th
refs/heads/master
/chap8/Q5_alt1.py
def min_product(a, b): bigger = b if a < b else a smaller = a if a < b else b memo = [-1]*(smaller+1) return min_prod(smaller, bigger, memo) def min_prod(smaller, bigger, memo): global counter if smaller == 0: return 0 elif smaller == 1: return bigger elif memo[smaller] > 0: return memo[smaller] s = smaller>>1 side1 = min_prod(s, bigger, memo) side2 = side1 if smaller%2 == 1: counter += 1 side2 = min_prod(smaller-s, bigger, memo) # Sum and cash counter += 1 memo[smaller] = side1 + side2 return memo[smaller] if __name__ == '__main__': counter = 0 a, b = 13494, 22323 product = a*b min_prod = min_product(a, b) print(f'Calculate result {min_prod}({product == min_prod}) with {counter}.')
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,744
daigo0927/ctci-6th
refs/heads/master
/chap8/Q4_alt.py
def convert_int_to_set(x, set_): subset = [] index = 0 while x > 0: if x&1 == 1: subset.append(set_[index]) index += 1 x >>= 1 return subset def get_subsets(set_): all_subsets = [] for k in range(1<<len(set_)): subset = convert_int_to_set(k, set_) all_subsets.append(subset) return all_subsets if __name__ == '__main__': list_ = [1, 2, 3] print(f'Alls subsets of {list_} is') for subset in get_subsets(list_): print(subset)
{"/chap4/Q12.py": ["/utils/tree.py"], "/chap4/Q11.py": ["/utils/tree.py"], "/chap4/Q10.py": ["/utils/misc.py"], "/chap4/Q12_alt.py": ["/utils/tree.py"], "/chap2/Q5.py": ["/utils/linkedlist.py"], "/utils/misc.py": ["/utils/tree.py"], "/chap2/Q7.py": ["/utils/linkedlist.py"], "/chap2/Q8.py": ["/utils/linkedlist.py"], "/chap2/Q6.py": ["/utils/linkedlist.py"]}
20,748
s18k/Django-Attendance-Analysis
refs/heads/master
/analysis/migrations/0002_auto_20200407_1122.py
# Generated by Django 3.0.5 on 2020-04-07 05:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('analysis', '0001_initial'), ] operations = [ migrations.AddField( model_name='employee', name='employee_contact', field=models.IntegerField(default=0), ), migrations.AddField( model_name='employee', name='employee_email', field=models.CharField(default='', max_length=50), ), migrations.AddField( model_name='employee', name='employee_image', field=models.ImageField(default='', upload_to='analysis/images'), ), ]
{"/analysis/views.py": ["/analysis/models.py"]}
20,749
s18k/Django-Attendance-Analysis
refs/heads/master
/analysis/models.py
from django.db import models # Create your models here. class Employee(models.Model): employee_id = models.IntegerField(default=0) employee_name=models.CharField(max_length=200) employee_email = models.CharField(max_length=50,default="") employee_contact=models.IntegerField(default=0) employee_position = models.CharField(max_length=50) employee_image = models.ImageField(upload_to="analysis/images",default="") def __str__(self): return (str(self.employee_id)+self.employee_name) def getname(self): return self.employee_name class Document(models.Model): monthnumber=models.IntegerField(default=1) year=models.IntegerField(default=0) document=models.FileField(upload_to="analysis/files",default="") def __str__(self): months = {1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October" , 11: "November", 12: "December"} s="" m=self.monthnumber self.month=months[m] s+=months[m] s+=" " s+=str(self.year) return (s)
{"/analysis/views.py": ["/analysis/models.py"]}
20,750
s18k/Django-Attendance-Analysis
refs/heads/master
/analysis/migrations/0004_document.py
# Generated by Django 3.0.5 on 2020-04-12 06:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('analysis', '0003_employee_employee_id'), ] operations = [ migrations.CreateModel( name='Document', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('month', models.IntegerField(default=0)), ('year', models.IntegerField(default=0)), ('document', models.FileField(default='', upload_to='analysis/files')), ], ), ]
{"/analysis/views.py": ["/analysis/models.py"]}
20,751
s18k/Django-Attendance-Analysis
refs/heads/master
/analysis/migrations/0005_auto_20200412_1751.py
# Generated by Django 3.0.5 on 2020-04-12 12:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('analysis', '0004_document'), ] operations = [ migrations.RemoveField( model_name='document', name='month', ), migrations.AddField( model_name='document', name='monthnumber', field=models.IntegerField(default=1), ), ]
{"/analysis/views.py": ["/analysis/models.py"]}
20,752
s18k/Django-Attendance-Analysis
refs/heads/master
/analysis/views.py
from django.shortcuts import render from .models import Employee from django.http import HttpResponse import pandas as pd import datetime from .models import Document from math import ceil def index(request): months={1:"January",2:"February",3:"March",4:"April",5:"May",6:"June",7:"July",8:"August",9:"September",10:"October" ,11:"November",12:"December"} employees=Employee.objects.all() documents=Document.objects.all() print(documents) print(employees) doc=Document.objects.get(monthnumber=1) n=len(employees) nSlides=n//5 +ceil((n/4)-(n//4)) params={'employee':employees,'Document':doc,'month':months[1],'no_of_slides':nSlides,'range':range(n)} return render(request,'analysis/index.html',params) def about(request): return render(request,'analysis/about.html') def chosen(request,id): id=str(id) year=id[:4] month=id[4:] m=int(month) yr=int(year) documents=Document.objects.get(monthnumber=m,year=yr) months = {1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October" , 11: "November", 12: "December"} employees = Employee.objects.all() params={} params['employee']=employees params['Document']=documents params['month']=months[m] s=months[m]+str(yr) params['name']=s n = len(employees) nSlides = n // 5 + ceil((n / 4) - (n // 4)) params['no_of_slides']=nSlides params['range']=range(n) print(documents) return render(request,'analysis/index2.html',params) def instructions(request): return render(request,'analysis/instructions.html') def chose(request): documents = Document.objects.all() n=len(documents) months = ["January","February","March","April","May","June","July","August","September","October" , "November","December"] params={'documents':documents,'number':n,'range':range(n),'months':months} return render(request,'analysis/chose.html',params) def search(request): query=request.GET.get('search') emp=Employee.objects.get(employee_name=query).employee_position print(emp) return HttpResponse(request,"Search") def employeem(request,id,m): m = str(m) year = m[:4] month = m[4:] m = int(month) yr = int(year) months = {1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October" , 11: "November", 12: "December"} name="" name+=months[m] name+=str(yr) name+=".xlsx" link="./media/analysis/files/" link+=name df = pd.read_excel(link) df['InTime'] = df['InTime'].fillna("00:00:00") df['OutTime'] = df['OutTime'].fillna("00:00:00") df['ODINTime'] = df['ODINTime'].fillna("00:00:00") df['ODOutTime'] = df['ODOutTime'].fillna("00:00:00") df['Leave'] = df['Leave'].fillna("N") df['INTimestamp'] = df["Date"].astype(str) + " " + df["InTime"].astype(str) df['OutTimestamp'] = df["Date"].astype(str) + " " + df["OutTime"].astype(str) df['ODINTimestamp'] = df["Date"].astype(str) + " " + df["ODINTime"].astype(str) df['ODOutTimestamp'] = df["Date"].astype(str) + " " + df["ODOutTime"].astype(str) emp_count = df['EmployeeID'].nunique() days = df['Date'].nunique() loop_count = emp_count * days l = [] odleave = [] leaves = {} for i in range(0, loop_count): intime = datetime.datetime.strptime(df["INTimestamp"][i], '%Y-%m-%d %H:%M:%S') outtime = datetime.datetime.strptime(df["OutTimestamp"][i], '%Y-%m-%d %H:%M:%S') odintime = datetime.datetime.strptime(df["ODINTimestamp"][i], '%Y-%m-%d %H:%M:%S') odouttime = datetime.datetime.strptime(df["ODOutTimestamp"][i], '%Y-%m-%d %H:%M:%S') total_out = (outtime.hour * 60 + outtime.minute) total_int = (intime.hour * 60 + intime.minute) total_od_out = (odouttime.hour * 60 + odouttime.minute) total_od_int = (odintime.hour * 60 + odintime.minute) od_leave_time = (total_od_int - total_od_out) / 60 od_leave_time=float("%.2f" % round(od_leave_time,2)) working_time = (total_out - total_int) / 60 working_time = float("%.2f" % round(working_time, 2)) l.append(working_time) odleave.append(od_leave_time) # print(intime,outtime,sep=" ") df['Working_time'] = l df['ODLeave'] = odleave grp_weekdays = df.groupby(['EmployeeID', 'Day']).mean() grp_total_working_time = df.groupby(['EmployeeID']).sum() # print(df) df11 = df.groupby('EmployeeID')['Leave'].apply(lambda x: (x == 'C').sum()).reset_index(name='Casualleavecount') df12 = df.groupby('EmployeeID')['Leave'].apply(lambda x: (x == 'M').sum()).reset_index(name='Medicalleavecount') df13 = df.groupby('EmployeeID')['Leave'].apply(lambda x: (x == 'OD').sum()).reset_index(name='ODleavecount') params={} medical= list(df12[df12['EmployeeID']==id]['Medicalleavecount'])[0] casual = list(df11[df11['EmployeeID'] == id]['Casualleavecount'])[0] odleave = list(df13[df13['EmployeeID'] == id]['ODleavecount'])[0] total_leaves=medical+casual+odleave gc = df.groupby(['EmployeeID', 'Day']).agg({'Working_time': ['mean']}) gc.columns = ['Average_working_hrs'] gc = gc.reset_index() gday = gc[gc['EmployeeID'] == id] monday = list(gday[gday['Day'] == 'Monday']['Average_working_hrs'])[0] monday = float("%.2f" % round(monday, 2)) tuesday = list(gday[gday['Day'] == 'Tuesday']['Average_working_hrs'])[0] tuesday = float("%.2f" % round(tuesday, 2)) wednesday =list(gday[gday['Day'] == 'Wednesday']['Average_working_hrs'])[0] wednesday = float("%.2f" % round(wednesday, 2)) thursday = list(gday[gday['Day'] == 'Thursday']['Average_working_hrs'])[0] thursday = float("%.2f" % round(thursday, 2)) friday = list(gday[gday['Day'] == 'Friday']['Average_working_hrs'])[0] friday = float("%.2f" % round(friday, 2)) saturday = list(gday[gday['Day'] == 'Saturday']['Average_working_hrs'])[0] saturday = float("%.2f" % round(saturday, 2)) l1=(list(df[df['EmployeeID'] == id]['Working_time'])) g = df.groupby('EmployeeID') gp = g.get_group(id) gsum = gp.sum() totalworking=(gsum['Working_time']) totalworking = float("%.2f" % round(totalworking, 2)) totalodleave=(gsum['ODLeave']) dates = (list(df[df['EmployeeID'] == id]['Date'])) date = [] for d in dates: s = str(d) s = s[8:10] date.append(s) emp = Employee.objects.get(employee_id=id) empid=emp.employee_id empname=emp.employee_name empposition=emp.employee_position empemail=emp.employee_email empcontact=emp.employee_contact empimage=emp.employee_image print(empimage) params['monthyr']=months[m]+" "+str(yr) params[emp]=emp params['empid']=empid params['empname']=empname params['empposition']=empposition params['empemail']=empemail params['empcontact']=empcontact params['empimage']=empimage params['totalleaves']=total_leaves params['medical']=medical params['casual']=casual params['odleave']=odleave print(odleave) all_leaves=[medical,casual,odleave] params['all_leaves']=all_leaves params['monday']=monday params['tuesday']=tuesday params['wednesday']=wednesday params['thursday']=thursday params['friday']=friday params['saturday']=saturday params['monthlyworking']=l1 params['date']=date params['range']=range(len(l1)) params['totalworking']=totalworking params['totalodleave']=totalodleave params['emp']=emp print("printing dates and work ") print(date) print(l1) days="" for i in date: days+=str(i) days+="," days=days[:-1] params["days"] = days work="" for i in l1: work+=str(i) work+="," work=work[:-1] params["w1"]=8.3 params["w2"]=9.3 params["w3"]=7.3 params["work"]=work return render(request, 'analysis/employee.html',params) def employee(request,id): months = {1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October" , 11: "November", 12: "December"} name="" name+=months[1] name+=str(2020) name+=".xlsx" link="./media/analysis/files/" link+=name df = pd.read_excel(link) df['InTime'] = df['InTime'].fillna("00:00:00") df['OutTime'] = df['OutTime'].fillna("00:00:00") df['ODINTime'] = df['ODINTime'].fillna("00:00:00") df['ODOutTime'] = df['ODOutTime'].fillna("00:00:00") df['Leave'] = df['Leave'].fillna("N") df['INTimestamp'] = df["Date"].astype(str) + " " + df["InTime"].astype(str) df['OutTimestamp'] = df["Date"].astype(str) + " " + df["OutTime"].astype(str) df['ODINTimestamp'] = df["Date"].astype(str) + " " + df["ODINTime"].astype(str) df['ODOutTimestamp'] = df["Date"].astype(str) + " " + df["ODOutTime"].astype(str) emp_count = df['EmployeeID'].nunique() days = df['Date'].nunique() loop_count = emp_count * days l = [] odleave = [] leaves = {} for i in range(0, loop_count): intime = datetime.datetime.strptime(df["INTimestamp"][i], '%Y-%m-%d %H:%M:%S') outtime = datetime.datetime.strptime(df["OutTimestamp"][i], '%Y-%m-%d %H:%M:%S') odintime = datetime.datetime.strptime(df["ODINTimestamp"][i], '%Y-%m-%d %H:%M:%S') odouttime = datetime.datetime.strptime(df["ODOutTimestamp"][i], '%Y-%m-%d %H:%M:%S') total_out = (outtime.hour * 60 + outtime.minute) total_int = (intime.hour * 60 + intime.minute) total_od_out = (odouttime.hour * 60 + odouttime.minute) total_od_int = (odintime.hour * 60 + odintime.minute) od_leave_time = (total_od_int - total_od_out) / 60 od_leave_time=float("%.2f" % round(od_leave_time,2)) working_time = (total_out - total_int) / 60 working_time = float("%.2f" % round(working_time, 2)) l.append(working_time) odleave.append(od_leave_time) # print(intime,outtime,sep=" ") df['Working_time'] = l df['ODLeave'] = odleave grp_weekdays = df.groupby(['EmployeeID', 'Day']).mean() grp_total_working_time = df.groupby(['EmployeeID']).sum() # print(df) df11 = df.groupby('EmployeeID')['Leave'].apply(lambda x: (x == 'C').sum()).reset_index(name='Casualleavecount') df12 = df.groupby('EmployeeID')['Leave'].apply(lambda x: (x == 'M').sum()).reset_index(name='Medicalleavecount') df13 = df.groupby('EmployeeID')['Leave'].apply(lambda x: (x == 'OD').sum()).reset_index(name='ODleavecount') params={} medical= list(df12[df12['EmployeeID']==id]['Medicalleavecount'])[0] casual = list(df11[df11['EmployeeID'] == id]['Casualleavecount'])[0] odleave = list(df13[df13['EmployeeID'] == id]['ODleavecount'])[0] total_leaves=medical+casual+odleave gc = df.groupby(['EmployeeID', 'Day']).agg({'Working_time': ['mean']}) gc.columns = ['Average_working_hrs'] gc = gc.reset_index() gday = gc[gc['EmployeeID'] == id] monday = list(gday[gday['Day'] == 'Monday']['Average_working_hrs'])[0] monday = float("%.2f" % round(monday, 2)) tuesday = list(gday[gday['Day'] == 'Tuesday']['Average_working_hrs'])[0] tuesday = float("%.2f" % round(tuesday, 2)) wednesday =list(gday[gday['Day'] == 'Wednesday']['Average_working_hrs'])[0] wednesday = float("%.2f" % round(wednesday, 2)) thursday = list(gday[gday['Day'] == 'Thursday']['Average_working_hrs'])[0] thursday = float("%.2f" % round(thursday, 2)) friday = list(gday[gday['Day'] == 'Friday']['Average_working_hrs'])[0] friday = float("%.2f" % round(friday, 2)) saturday = list(gday[gday['Day'] == 'Saturday']['Average_working_hrs'])[0] saturday = float("%.2f" % round(saturday, 2)) l1=(list(df[df['EmployeeID'] == id]['Working_time'])) g = df.groupby('EmployeeID') gp = g.get_group(id) gsum = gp.sum() totalworking=(gsum['Working_time']) totalworking = float("%.2f" % round(totalworking, 2)) totalodleave=(gsum['ODLeave']) dates = (list(df[df['EmployeeID'] == id]['Date'])) date = [] for d in dates: s = str(d) s = s[8:10] date.append(s) emp = Employee.objects.get(employee_id=id) empid=emp.employee_id empname=emp.employee_name empposition=emp.employee_position empemail=emp.employee_email empcontact=emp.employee_contact empimage=emp.employee_image print(empimage) params[emp]=emp params['monthyr']=months[1]+" "+str(2020) params['empid']=empid params['empname']=empname params['empposition']=empposition params['empemail']=empemail params['empcontact']=empcontact params['empimage']=empimage params['totalleaves']=total_leaves params['medical']=medical params['casual']=casual params['odleave']=odleave print(odleave) all_leaves=[medical,casual,odleave] params['all_leaves']=all_leaves params['monday']=monday params['tuesday']=tuesday params['wednesday']=wednesday params['thursday']=thursday params['friday']=friday params['saturday']=saturday params['monthlyworking']=l1 params['date']=date params['range']=range(len(l1)) params['totalworking']=totalworking params['totalodleave']=totalodleave params['emp']=emp print("printing dates and work ") print(date) print(l1) days="" for i in date: days+=str(i) days+="," days=days[:-1] params["days"] = days work="" for i in l1: work+=str(i) work+="," work=work[:-1] params["w1"]=8.3 params["w2"]=9.3 params["w3"]=7.3 params["work"]=work return render(request, 'analysis/employee.html',params)
{"/analysis/views.py": ["/analysis/models.py"]}
20,761
refi93/sms-server
refs/heads/master
/db.py
import sqlite3 import atexit from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker conn = sqlite3.connect('database.db') engine = create_engine('sqlite:///database.db') Session = sessionmaker(bind=engine) session = Session() def execute_raw(raw_sql): return conn.executescript(raw_sql) def select(table): return sqlalchemy.select([table]) def query(table): return session.query(table) def insert(table): return sqlalchemy.insert(table) def update(table): return sqlalchemy.update(table) def close_database(): conn.close() engine.dispose() atexit.register(close_database)
{"/sms_apps/sms_app.py": ["/db.py", "/models.py"], "/message_handler.py": ["/db.py", "/models.py", "/sms_apps/navigator.py"], "/db_init.py": ["/db.py"], "/models.py": ["/db.py"], "/sms_apps/navigator.py": ["/sms_apps/sms_app.py", "/gsm_module.py"], "/gsm_module.py": ["/db.py", "/models.py"]}
20,762
refi93/sms-server
refs/heads/master
/sms_apps/sms_app.py
from datetime import datetime import db from models import MessageToSend class SmsApp: def should_handle(self, sms): pass def get_response(self, sms): pass def handle(self, sms): response = self.get_response(sms) db.session.add(MessageToSend( phone_to=sms.phone_from, msg_body=response )) sms.processed_at = datetime.utcnow() db.session.commit()
{"/sms_apps/sms_app.py": ["/db.py", "/models.py"], "/message_handler.py": ["/db.py", "/models.py", "/sms_apps/navigator.py"], "/db_init.py": ["/db.py"], "/models.py": ["/db.py"], "/sms_apps/navigator.py": ["/sms_apps/sms_app.py", "/gsm_module.py"], "/gsm_module.py": ["/db.py", "/models.py"]}
20,763
refi93/sms-server
refs/heads/master
/message_handler.py
#!/usr/bin/env python3 from time import sleep import config import db from models import ReceivedMessage from sms_apps.navigator import Navigator sms_apps = [ Navigator() ] def handle(message): for sms_app in sms_apps: if ( (message.phone_from in config.senders_whitelist) and sms_app.should_handle(message) ): sms_app.handle(message) while True: new_messages = ( db.query(ReceivedMessage) .filter(ReceivedMessage.processed_at.is_(None)) .all() ) for message in new_messages: handle(message) sleep(5)
{"/sms_apps/sms_app.py": ["/db.py", "/models.py"], "/message_handler.py": ["/db.py", "/models.py", "/sms_apps/navigator.py"], "/db_init.py": ["/db.py"], "/models.py": ["/db.py"], "/sms_apps/navigator.py": ["/sms_apps/sms_app.py", "/gsm_module.py"], "/gsm_module.py": ["/db.py", "/models.py"]}
20,764
refi93/sms-server
refs/heads/master
/db_init.py
import db db.execute_raw(""" DROP TABLE IF EXISTS received_messages; DROP TABLE IF EXISTS messages_to_send; CREATE TABLE received_messages( id INTEGER PRIMARY KEY AUTOINCREMENT, phone_from TEXT, msg_body TEXT, created_at TIMESTAMP, processed_at TIMESTAMP ); CREATE TABLE messages_to_send( id INTEGER PRIMARY KEY AUTOINCREMENT, phone_to TEXT, msg_body TEXT, created_at TIMESTAMP, sent_at TIMESTAMP ); """)
{"/sms_apps/sms_app.py": ["/db.py", "/models.py"], "/message_handler.py": ["/db.py", "/models.py", "/sms_apps/navigator.py"], "/db_init.py": ["/db.py"], "/models.py": ["/db.py"], "/sms_apps/navigator.py": ["/sms_apps/sms_app.py", "/gsm_module.py"], "/gsm_module.py": ["/db.py", "/models.py"]}
20,765
refi93/sms-server
refs/heads/master
/models.py
from sqlalchemy import Column, DateTime, String, Integer, JSON, ForeignKey, Boolean, func from sqlalchemy.orm import relationship, backref from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import class_mapper from sqlalchemy.orm.properties import ColumnProperty import db from datetime import datetime Base = declarative_base() Base.metadata.create_all(db.engine) class BaseMixin(object): def as_dict(self): result = {} for prop in class_mapper(self.__class__).iterate_properties: if isinstance(prop, ColumnProperty): result[prop.key] = getattr(self, prop.key) return result class ReceivedMessage(BaseMixin, Base): __tablename__ = 'received_messages' id = Column(Integer, primary_key=True) phone_from = Column(String, default=None) msg_body = Column(String, default=None) created_at = Column(DateTime, default=datetime.utcnow()) processed_at = Column(DateTime, default=None) class MessageToSend(BaseMixin, Base): __tablename__ = 'messages_to_send' id = Column(Integer, primary_key=True) phone_to = Column(String, default=None) msg_body = Column(String, default=None) created_at = Column(DateTime, default=datetime.utcnow()) sent_at = Column(DateTime, default=None)
{"/sms_apps/sms_app.py": ["/db.py", "/models.py"], "/message_handler.py": ["/db.py", "/models.py", "/sms_apps/navigator.py"], "/db_init.py": ["/db.py"], "/models.py": ["/db.py"], "/sms_apps/navigator.py": ["/sms_apps/sms_app.py", "/gsm_module.py"], "/gsm_module.py": ["/db.py", "/models.py"]}
20,766
refi93/sms-server
refs/heads/master
/sms_apps/navigator.py
import requests from math import radians, cos, sin, asin, sqrt import math from unidecode import unidecode import config from .sms_app import SmsApp import gsm_module geocode_api_url = "https://maps.google.com/maps/api/geocode/json" class Navigator(SmsApp): def should_handle(self, sms): return sms.msg_body.lower().startswith("navigate") def get_response(self, sms): sms_text_splitted = sms.msg_body.split("\"") origin = sms_text_splitted[1] destination = sms_text_splitted[3] origin_info = self.get_address_info(origin) destination_info = self.get_address_info(destination) origin_coord = (origin_info["geometry"]["location"]["lat"], origin_info["geometry"]["location"]["lng"]) destination_coord = (destination_info["geometry"]["location"]["lat"], destination_info["geometry"]["location"]["lng"]) distance = int(haversine(origin_coord, destination_coord)) compass_bearing = int(get_compass_bearing(origin_coord, destination_coord)) return "Dist: " + distance_to_str(distance) + "\r\nHead: " + str(compass_bearing) + " deg\r\nOrig: " + unidecode(origin_info["formatted_address"][:42]) + "\r\nDest: " + unidecode(destination_info["formatted_address"][:42]) def get_address_info(self, address): response = requests.get(geocode_api_url, { "address": address, "key": config.geocode_api_key, }).json() return response["results"][0] def distance_to_str(distance_in_m): if distance_in_m > 1000: return str(round(distance_in_m / 1000, 1)) + " km" else: return str(distance_in_m) + " m" def haversine(point_1, point_2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) """ lat1, lon1 = point_1 lat2, lon2 = point_2 # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 c = 2 * asin(sqrt(a)) # Radius of earth in kilometers is 6371 m = 6371000 * c return m def get_compass_bearing(point_1, point_2): """ Calculates the bearing between two points. The formulae used is the following: θ = atan2(sin(Δlong).cos(lat2), cos(lat1).sin(lat2) − sin(lat1).cos(lat2).cos(Δlong)) :Parameters: - `pointA: The tuple representing the latitude/longitude for the first point. Latitude and longitude must be in decimal degrees - `pointB: The tuple representing the latitude/longitude for the second point. Latitude and longitude must be in decimal degrees :Returns: The bearing in degrees :Returns Type: float """ if (type(point_1) != tuple) or (type(point_2) != tuple): raise TypeError("Only tuples are supported as arguments") lat1 = math.radians(point_1[0]) lat2 = math.radians(point_2[0]) diffLong = math.radians(point_2[1] - point_1[1]) x = math.sin(diffLong) * math.cos(lat2) y = math.cos(lat1) * math.sin(lat2) - (math.sin(lat1) * math.cos(lat2) * math.cos(diffLong)) initial_bearing = math.atan2(x, y) # Now we have the initial bearing but math.atan2 return values # from -180° to + 180° which is not what we want for a compass bearing # The solution is to normalize the initial bearing as shown below initial_bearing = math.degrees(initial_bearing) compass_bearing = (initial_bearing + 360) % 360 return compass_bearing
{"/sms_apps/sms_app.py": ["/db.py", "/models.py"], "/message_handler.py": ["/db.py", "/models.py", "/sms_apps/navigator.py"], "/db_init.py": ["/db.py"], "/models.py": ["/db.py"], "/sms_apps/navigator.py": ["/sms_apps/sms_app.py", "/gsm_module.py"], "/gsm_module.py": ["/db.py", "/models.py"]}
20,767
refi93/sms-server
refs/heads/master
/gsm_module.py
#!/usr/bin/env python3 import serial from datetime import datetime import config import db from models import MessageToSend, ReceivedMessage port = serial.Serial(config.serial_port, 9600, timeout=4) if (not port.isOpen()): port.open() def send_at_command(command, append_eol=True): command = command + "\r\n" if append_eol else command port.write(command.encode()) return list(map(lambda elem: elem.decode("utf-8"), port.readlines())) def init(pin=None): while True: result = send_at_command("ATI") if len(result) > 0 and result[-1] == "OK\r\n": break if (not enter_pin(pin)): raise Error("PIN authentification has failed!") # switch to text mode so commands look nicer send_at_command("AT+CMGF=1") # store received sms on sim card # i.e. disable cnmi notifications and set storage # of newly arrived messages to gsm module memory send_at_command("AT+CNMI=0,0,0,0,0") send_at_command("AT+CPMS=\"ME\",\"ME\",\"ME\"") print("GSM module initialized!") def enter_pin(pin=None): pin_status = send_at_command("AT+CPIN?")[2] if pin_status == "+CPIN:READY\r\n": return True elif pin_status == "+CPIN:SIM PIN\r\n": auth_result = send_at_command("AT+CPIN=\"" + pin + "\"") return auth_result[2] == "OK\r\n" else: return False def send_sms_message(phone_number, text): assert phone_number.startswith("+421") command_sequence = [ "AT+CMGF=1", "AT+CMGS=" + phone_number, text ] for command in command_sequence: send_at_command(command) result = send_at_command(chr(26), False) print(result) def get_sms_messages(category="ALL"): assert category in [ "ALL", "REC READ", "REC UNREAD", "STO UNSENT", "STO SENT" ] result = [] response_raw = send_at_command("AT+CMGL=" + category) print(response_raw) sms_list_raw = response_raw[2:-2] # the odd elements are sms metadata, the even ones are sms texts sms_pairs = zip(sms_list_raw[0::2], sms_list_raw[1::2]) for sms_meta, sms_text in sms_pairs: result.append(parse_sms(sms_meta, sms_text)) print(result) return result def delete_all_sms_messages(): sms_messages_to_delete = get_sms_messages("ALL") for sms_message in sms_messages_to_delete: delete_sms_message(sms_message["index"]) def delete_sms_message(index): return send_at_command("AT+CMGD=" + str(index)) def parse_sms(sms_meta, sms_text): sms_meta = sms_meta.split(',') return { 'index': int(sms_meta[0].split(': ')[1]), 'category': sms_meta[1].split("\"")[1], 'sender': sms_meta[2].split("\"")[1], 'date': sms_meta[4].split("\"")[1], 'text': sms_text } if __name__ == '__main__': init(pin=config.sim_card_pin) while (True): # check received messages for sms_message in get_sms_messages(): print('new message arrived') msg = ReceivedMessage( phone_from=sms_message['sender'], msg_body=sms_message['text'], ) db.session.add(msg) db.session.commit() delete_sms_message(sms_message["index"]) # send messages waiting to be sent messages_to_send = ( db.query(MessageToSend) .filter(MessageToSend.sent_at.is_(None)) .all() ) for message in messages_to_send: send_sms_message(message.phone_to, message.msg_body) message.sent_at = datetime.utcnow() db.session.commit()
{"/sms_apps/sms_app.py": ["/db.py", "/models.py"], "/message_handler.py": ["/db.py", "/models.py", "/sms_apps/navigator.py"], "/db_init.py": ["/db.py"], "/models.py": ["/db.py"], "/sms_apps/navigator.py": ["/sms_apps/sms_app.py", "/gsm_module.py"], "/gsm_module.py": ["/db.py", "/models.py"]}
20,797
leovd100/Django-controle-de-gastos
refs/heads/master
/contas/forms.py
from django.forms import ModelForm from .models import Transacao class Constru_Form (ModelForm): class Meta: model = Transacao fields = ['data','descricao','valor','categoria','observacoes']
{"/contas/forms.py": ["/contas/models.py"], "/contas/views.py": ["/contas/models.py", "/contas/forms.py"]}
20,798
leovd100/Django-controle-de-gastos
refs/heads/master
/contas/views.py
from django.shortcuts import render, redirect from django.http import HttpResponse from datetime import datetime from .models import Transacao from .forms import Constru_Form # Create your views here. def home(request): data = { 'trasacoes':['t1','t2','t3'] } #data_today = f'{datetime.now().day}/{datetime.now().month}/{datetime.now().year}' data['agora'] = datetime.now().strftime('%d/%m/%Y') #html = '<html><body>Data e Hora atual %s</body></html>'% agora return render(request, 'contas/home.html',data) def listagem(request): data = {} data['transacao'] = Transacao.objects.all() return render(request, 'contas/lista.html',data) def newTransfer(request): data = {} formulario = Constru_Form(request.POST or None) if formulario.is_valid(): formulario.save() return redirect('url_lista') data['form'] = formulario return render(request, 'contas/form.html',data) def update(request, primary): data = {} transacao = Transacao.objects.get(pk=primary) form = Constru_Form(request.POST or None, instance=transacao) if form.is_valid(): form.save() return redirect('url_lista') data['form'] = form data['obj'] = transacao return render(request, 'contas/form.html',data) def delete(request, pk): if form.is_valid(): Transacao.objects.get(pk=pk).delete() return redirect('url_lista')
{"/contas/forms.py": ["/contas/models.py"], "/contas/views.py": ["/contas/models.py", "/contas/forms.py"]}
20,799
leovd100/Django-controle-de-gastos
refs/heads/master
/controle_gastos/contas/views.py
from django.shortcuts import render from django.http import HttpResponse import datetime # Create your views here. def home(requests): agora = datetime.datetime.now() #html = '<html><body>Data e Hora atual %s</body></html>'% agora return render(requests, 'contas/home.html')
{"/contas/forms.py": ["/contas/models.py"], "/contas/views.py": ["/contas/models.py", "/contas/forms.py"]}
20,800
leovd100/Django-controle-de-gastos
refs/heads/master
/contas/models.py
from django.db import models from random import randint # Create your models here. class Categoria(models.Model): nome = models.CharField(max_length = 100) dt_criacao = models.DateTimeField(auto_now_add = True) def __str__(self): return self.nome class Transacao(models.Model): data = models.DateTimeField() descricao = models.CharField(max_length = 200) valor = models.DecimalField(max_digits=7,decimal_places=2) categoria = models.ForeignKey(Categoria,on_delete=models.CASCADE) observacoes = models.TextField(null=True, blank=True) class Meta: verbose_name_plural = 'Transacoes' def __str__(self): return self.descricao
{"/contas/forms.py": ["/contas/models.py"], "/contas/views.py": ["/contas/models.py", "/contas/forms.py"]}
20,801
leovd100/Django-controle-de-gastos
refs/heads/master
/contas/migrations/0003_auto_20200603_1205.py
# Generated by Django 3.0.6 on 2020-06-03 15:05 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('contas', '0002_transacao'), ] operations = [ migrations.AlterModelOptions( name='transacao', options={'verbose_name_plural': 'Transacoes'}, ), ]
{"/contas/forms.py": ["/contas/models.py"], "/contas/views.py": ["/contas/models.py", "/contas/forms.py"]}
20,802
leovd100/Django-controle-de-gastos
refs/heads/master
/venv/Scripts/django-admin.py
#!c:\users\demetrio\desktop\projetos python\djagoudemy\venv\scripts\python.exe from django.core import management if __name__ == "__main__": management.execute_from_command_line()
{"/contas/forms.py": ["/contas/models.py"], "/contas/views.py": ["/contas/models.py", "/contas/forms.py"]}
20,806
yc19890920/flask-blog
refs/heads/master
/app/blog/models.py
# -*- coding: utf-8 -*- import os import re import datetime from flask import url_for from app import db, Config from app.libs.exceptions import ValidationError from app.libs.tools import smart_bytes PicP = re.compile(r'src="(\/static\/ckupload\/.*?)"') acrticle_tags_ref = db.Table( 'blog_article_tags', db.Column('id', db.Integer, primary_key=True), db.Column('tag_id', db.Integer, db.ForeignKey('blog_tag.id')), db.Column('article_id', db.Integer, db.ForeignKey('blog_article.id')) ) class Tag(db.Model): __tablename__ = 'blog_tag' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(20), unique=True, nullable=False, doc=u"标签名") created = db.Column(db.DATETIME, nullable=True, default=datetime.datetime.now(), doc=u"创建时间") updated = db.Column(db.DATETIME, nullable=True, default=datetime.datetime.now(), doc=u"修改时间") articles = db.relationship('Article', secondary=acrticle_tags_ref, backref=db.backref('tags_articles', lazy='dynamic')) def __str__(self): return smart_bytes(self.name) __repr__ = __str__ @property def get_blog_tag_uri(self): return url_for("blog.tag", tag_id=self.id) @staticmethod def get_choice_lists(): return [(row.id, row.name) for row in Tag.query.all()] @staticmethod def str_to_obj(tags): r = [] for tag in tags: tag_obj = Tag.query.filter_by(id=int(tag)).first() if tag_obj is None: continue r.append(tag_obj) return r @property def getRefArticleIDs(self): return [ d.id for d in self.articles ] class Category(db.Model): __tablename__ = 'blog_category' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(20), unique=True, nullable=False, doc=u"分类名") created = db.Column(db.DATETIME, nullable=True, default=datetime.datetime.now(), doc=u"创建时间") updated = db.Column(db.DATETIME, nullable=True, default=datetime.datetime.now(), doc=u"修改时间") def __str__(self): return smart_bytes(self.name) __repr__ = __str__ @staticmethod def get_choice_lists(): return [(row.id, row.name) for row in Category.query.all()] @staticmethod def get_obj(cat_id): return Category.query.filter_by(id=int(cat_id)).first() class Article(db.Model): __tablename__ = 'blog_article' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), index=True, nullable=False, doc=u"标题") content = db.Column(db.Text, nullable=False, doc=u"内容") abstract = db.Column(db.Text, nullable=False, doc=u"摘要") status = db.Column(db.String(1), nullable=False, doc=u"文章状态", default="d") views = db.Column(db.Integer, default=0, doc=u'阅读量') likes = db.Column(db.Integer, default=0, doc=u'点赞数') auth = db.Column(db.String(50), nullable=False, doc=u"作者") source = db.Column(db.String(100), nullable=True, doc=u"来源") category_id = db.Column(db.Integer, db.ForeignKey('blog_category.id')) category = db.relationship('Category', backref=db.backref('category_articles', lazy='dynamic')) # 而每个 tag 的页面列表( Tag.tags_article )是一个动态的反向引用。 正如上面提到的,这意味着你会得到一个可以发起 select 的查询对象。 tags = db.relationship('Tag', secondary=acrticle_tags_ref, backref=db.backref('tags_articles', lazy='dynamic')) created = db.Column(db.DATETIME, nullable=True, default=datetime.datetime.now(), doc=u"创建时间") updated = db.Column(db.DATETIME, nullable=True, default=datetime.datetime.now(), doc=u"修改时间") comments = db.relationship('BlogComment', backref='post', lazy='dynamic') def __str__(self): return smart_bytes(self.title) __repr__ = __str__ @property def show_status_display(self): if self.status == "p": return u"发布" return u"延迟发布" @property def get_modify_uri(self): return url_for("admin.article_modify", article_id=self.id) @property def get_detail_uri(self): return url_for("blog.detail", article_id=self.id) @property def get_tags_id(self): return [d.id for d in self.tags] @staticmethod def referPic(article_id, content, abstract): lists = PicP.findall(content) lists2 = PicP.findall(abstract) l = list( set(lists) | set(lists2) ) pics = [] for i in l: obj = CKPicture.query.filter_by(filepath=i).first() if not obj: continue obj.article_id = article_id pics.append(obj) db.session.add_all(pics) db.session.commit() @property def has_previous_obj(self): obj = Article.query.filter_by(status='p').filter(id<self.id).order_by(Article.id.desc()).first() return obj and obj.id or None @property def has_next_obj(self): obj = Article.query.filter_by(status='p').filter(id>self.id).order_by(Article.id.asc()).first() return obj and obj.id or None @property def blogcomments(self): return BlogComment.query.filter_by(article_id=self.id).order_by(BlogComment.id.desc()) def to_json(self): json_post = { 'url': url_for('api.get_post', id=self.id, _external=True), 'title': self.title, 'content': self.content, 'abstract': self.abstract, 'created': self.created, 'auth': self.auth, # 'auth': url_for('api.get_user', id=self.author_id, _external=True), 'comments': url_for('api.get_post_comments', id=self.id, _external=True), 'comment_count': self.comments.count() } return json_post @staticmethod def from_json(json_post): title = json_post.get('title') abstract = json_post.get('abstract') content = json_post.get('content') auth = json_post.get('auth') category_id = json_post.get('category_id') if title is None or title == '': raise ValidationError('post does not have a title') if abstract is None or abstract == '': raise ValidationError('post does not have a abstract') if content is None or content == '': raise ValidationError('post does not have a body') if auth is None or auth == '': raise ValidationError('post does not have a auth') if category_id is None or category_id == '': raise ValidationError('post does not have a category_id') return Article(title=title,abstract=abstract, content=content, auth=auth,category_id=category_id) # class BlogArticleTasg(db.Model): # __tablename__ = 'blog_article_tags' # # id = db.Column(db.Integer, primary_key=True,autoincrement=True) # tag_id = db.Column(db.Integer, db.ForeignKey('blog_tag.id')) # article_id = db.Column(db.Integer, db.ForeignKey('blog_article.id')) class CKPicture(db.Model): __tablename__ = 'blog_picture' id = db.Column(db.Integer, primary_key=True) article_id = db.Column(db.Integer, default=0, index=True) # db.ForeignKey('blog_article.id') filename = db.Column(db.String(100), index=True, nullable=False, doc=u"图片名") filetype = db.Column(db.String(100), index=True, nullable=False, doc=u"图片类型") filepath = db.Column(db.String(200), unique=True, index=True, nullable=False, doc=u"文件路径") filesize = db.Column(db.Integer, default=0, doc=u'文件大小') created = db.Column(db.DATETIME, nullable=True, default=datetime.datetime.now(), doc=u"创建时间") @staticmethod def str_to_obj(ids): r = [] for pid in ids: tag_obj = CKPicture.query.filter_by(id=int(pid), article_id=0).first() if tag_obj is None: continue r.append(tag_obj) return r @property def refarticle(self): obj = Article.query.filter_by(id=self.article_id).first() return obj and obj.title or "" def removepath(self): path = os.path.join(Config.BASE_DIR, self.filepath[1:]) if os.path.exists(path): os.remove( path ) class BlogComment(db.Model): __tablename__ = 'blog_comment' id = db.Column(db.Integer, primary_key=True) # article_id = db.Column(db.Integer, db.ForeignKey('blog_article.id'), default=0, index=True) # db.ForeignKey('blog_article.id') article_id = db.Column(db.Integer, db.ForeignKey('blog_article.id')) article = db.relationship('Article', backref=db.backref('article_coments', lazy='dynamic')) username = db.Column(db.String(100), index=True, nullable=False, doc=u"你的名称") email = db.Column(db.String(100), index=True, nullable=False, doc=u"你的邮箱") content = db.Column(db.Text, nullable=False, doc=u"评论内容") created = db.Column(db.DATETIME, nullable=True, default=datetime.datetime.now(), doc=u"创建时间") updated = db.Column(db.DATETIME, nullable=True, default=datetime.datetime.now(), doc=u"修改时间") @property def refarticle(self): obj = Article.query.filter_by(id=self.article_id).first() return obj and obj.title or "" def to_json(self): json_comment = { 'url': url_for('api.get_comment', id=self.id), 'post_url': url_for('api.get_post', id=self.post_id), 'content': self.content, 'created': self.created, # 'author_url': url_for('api.get_user', id=self.author_id), } return json_comment @staticmethod def from_json(json_comment): content = json_comment.get('content') if content is None or content == '': raise ValidationError('comment does not have a body') return BlogComment(content=content) class Suggest(db.Model): __tablename__ = 'blog_suggest' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(100), index=True, nullable=False, doc=u"你的名称") email = db.Column(db.String(100), index=True, nullable=False, doc=u"你的邮箱") content = db.Column(db.Text, nullable=False, doc=u"评论内容") created = db.Column(db.DATETIME, nullable=True, default=datetime.datetime.now(), doc=u"创建时间")
{"/app/blog/models.py": ["/app/__init__.py", "/app/libs/tools.py"], "/app/__init__.py": ["/app/api/jwt_auth.py", "/app/admin/__init__.py", "/app/blog/__init__.py"], "/app/api/jwt_auth.py": ["/app/auth/models.py"], "/app/blog/views.py": ["/app/__init__.py", "/app/blog/__init__.py", "/app/blog/forms.py", "/app/blog/models.py"], "/app/admin/forms.py": ["/app/blog/models.py"], "/app/admin/views.py": ["/app/__init__.py", "/app/admin/__init__.py", "/app/admin/forms.py", "/app/blog/models.py"], "/app/blog/caches.py": ["/app/__init__.py", "/app/blog/models.py"], "/app/auth/models.py": ["/app/__init__.py"], "/manage.py": ["/app/__init__.py", "/app/auth/models.py", "/app/blog/models.py"], "/app/auth/views.py": ["/app/auth/models.py", "/app/__init__.py"]}
20,807
yc19890920/flask-blog
refs/heads/master
/app/__init__.py
# -*- coding: utf-8 -*- from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_bootstrap import Bootstrap from flask_login import LoginManager from flask_wtf.csrf import CSRFProtect from flask_moment import Moment # from flask_seasurf import SeaSurf import redis from settings import Config db = SQLAlchemy() bootstrap = Bootstrap() moment = Moment() csrf = CSRFProtect() login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'auth.login' redis = redis.Redis(host="127.0.0.1", port=6379, db=0) app = Flask(__name__) app.config.from_object(Config) Config.init_app(app) db.init_app(app) from app.api.jwt_auth import authenticate, identity from flask_jwt import JWT, jwt_required, current_identity jwt = JWT(app, authenticate, identity) csrf.init_app(app) bootstrap.init_app(app) moment.init_app(app) login_manager.init_app(app) from app.auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') from app.admin import admin as admin_blueprint app.register_blueprint(admin_blueprint) from app.blog import blog as blog_blueprint app.register_blueprint(blog_blueprint) from app.api import api as api_blueprint app.register_blueprint(api_blueprint, url_prefix='/api/v1') import logging # rootLogger = logging.getLogger(__name__) # rootLogger.setLevel(logging.DEBUG) # socketHandler = logging.handlers.SocketHandler('localhost',logging.handlers.DEFAULT_TCP_LOGGING_PORT) # rootLogger.addHandler(socketHandler) # rootLogger.setLevel(logging.DEBUG) # logger = logging.getLogger(__name__) @app.before_request def xxxxxxxxxx1(): # logger.info('前1') print('前1') # return "不要再来烦我了" @app.before_request def xxxxxxxxxx2(): # logger.info('前2') print('前2') @app.after_request def oooooooo1(response): # logger.info('后1') print('后1') return response @app.after_request def oooooooo2(response): # logger.info('后2') print('后2') return response # def create_app(): # app = Flask(__name__) # # from app.api.jwt_auth import authenticate, identity # from flask_jwt import JWT, jwt_required, current_identity # jwt = JWT(app, authenticate, identity) # # app.config.from_object(Config) # Config.init_app(app) # # csrf.init_app(app) # # db.init_app(app) # bootstrap.init_app(app) # moment.init_app(app) # login_manager.init_app(app) # # from app.auth import auth as auth_blueprint # app.register_blueprint(auth_blueprint, url_prefix='/auth') # # from app.admin import admin as admin_blueprint # app.register_blueprint(admin_blueprint) # # from app.blog import blog as blog_blueprint # app.register_blueprint(blog_blueprint) # # from app.api import api as api_blueprint # app.register_blueprint(api_blueprint, url_prefix='/api/v1') # # return app
{"/app/blog/models.py": ["/app/__init__.py", "/app/libs/tools.py"], "/app/__init__.py": ["/app/api/jwt_auth.py", "/app/admin/__init__.py", "/app/blog/__init__.py"], "/app/api/jwt_auth.py": ["/app/auth/models.py"], "/app/blog/views.py": ["/app/__init__.py", "/app/blog/__init__.py", "/app/blog/forms.py", "/app/blog/models.py"], "/app/admin/forms.py": ["/app/blog/models.py"], "/app/admin/views.py": ["/app/__init__.py", "/app/admin/__init__.py", "/app/admin/forms.py", "/app/blog/models.py"], "/app/blog/caches.py": ["/app/__init__.py", "/app/blog/models.py"], "/app/auth/models.py": ["/app/__init__.py"], "/manage.py": ["/app/__init__.py", "/app/auth/models.py", "/app/blog/models.py"], "/app/auth/views.py": ["/app/auth/models.py", "/app/__init__.py"]}
20,808
yc19890920/flask-blog
refs/heads/master
/app/api/jwt_auth.py
# -*- coding: utf-8 -*- from flask_jwt import JWT, jwt_required, current_identity from werkzeug.security import safe_str_cmp from app.auth.models import User from . import api # JWT鉴权:默认参数为username/password,在数据库里查找并比较password_hash def authenticate(username, password): print ('JWT auth argvs:', username, password) user = User.query.filter_by(username=username).first() if user is not None and user.verify_password(password): return user # JWT检查user_id是否存在 def identity(payload): print ('JWT payload:', payload) user_id = payload['identity'] user = User.query.filter_by(id=user_id).first() return user_id if user is not None else None
{"/app/blog/models.py": ["/app/__init__.py", "/app/libs/tools.py"], "/app/__init__.py": ["/app/api/jwt_auth.py", "/app/admin/__init__.py", "/app/blog/__init__.py"], "/app/api/jwt_auth.py": ["/app/auth/models.py"], "/app/blog/views.py": ["/app/__init__.py", "/app/blog/__init__.py", "/app/blog/forms.py", "/app/blog/models.py"], "/app/admin/forms.py": ["/app/blog/models.py"], "/app/admin/views.py": ["/app/__init__.py", "/app/admin/__init__.py", "/app/admin/forms.py", "/app/blog/models.py"], "/app/blog/caches.py": ["/app/__init__.py", "/app/blog/models.py"], "/app/auth/models.py": ["/app/__init__.py"], "/manage.py": ["/app/__init__.py", "/app/auth/models.py", "/app/blog/models.py"], "/app/auth/views.py": ["/app/auth/models.py", "/app/__init__.py"]}
20,809
yc19890920/flask-blog
refs/heads/master
/app/blog/views.py
# -*- coding: utf-8 -*- import json from flask import Response from flask import flash, redirect, render_template, request, url_for, abort from app import db, csrf from app.blog import blog, caches from app.blog.forms import CommentForm, SuggestForm from app.blog.models import Tag, Article, BlogComment, Suggest from app.libs import tools @blog.route('/', methods=['GET']) def index(): length = 5 page = request.args.get('page', '1') page = page and int(page) or 1 pagination = Article.query.filter_by(status='p').paginate(page, per_page=length, error_out = False) tag_list = caches.getTaglist() hot_list = caches.getHotlist() newart_list = caches.getNewArticlelist() newcom_list = caches.getNewCommontlist() return render_template( 'blog/index.html', article_list=pagination, tag_list = tag_list, hot_list = hot_list, newart_list = newart_list, newcom_list = newcom_list, ) @blog.route('/p/<int:article_id>/', methods=['GET', "POST"]) def detail(article_id): article = Article.query.get_or_404(article_id) form = CommentForm() if request.method == "POST": if form.validate(): obj = BlogComment( username=form.username.data, email=form.email.data, content=form.content.data, article=article ) db.session.add(obj) db.session.commit() flash(u'您宝贵的意见已收到,谢谢!.', 'success') current_uri = "{}#list-talk".format( url_for('blog.detail', article_id=article_id) ) return redirect(current_uri) tag_list = caches.getTaglist() hot_list = caches.getHotlist() newart_list = caches.getNewArticlelist() # 相关文章 # refer_list = article.get_refer_articles() ip = tools.getClientIP() if caches.shouldIncrViews(ip, article_id): article.views += 1 db.session.add(article) db.session.commit() return render_template( 'blog/detail.html', article=article, form=form, tag_list = tag_list, hot_list = hot_list, newart_list = newart_list, ) @csrf.exempt @blog.route('/s/', methods=['POST']) def score(): if request.method == "POST": article_id = request.form.get("poid", "0") article = Article.query.get_or_404(article_id) article.likes += 1 db.session.add(article) db.session.commit() return Response(json.dumps({'status': "ok"}), content_type="application/json") @blog.route('/q/', methods=['GET']) def search(): search_for = request.args.get('search_for') if search_for: length = 5 page = request.args.get('page', '1') page = page and int(page) or 1 article_list = Article.query.filter_by(status='p').filter(Article.title.like(search_for)).paginate(page, per_page=length, error_out = False) tag_list = caches.getTaglist() hot_list = caches.getHotlist() newart_list = caches.getNewArticlelist() newcom_list = caches.getNewCommontlist() return render_template( 'blog/index.html', search_for=search_for, article_list=article_list, tag_list = tag_list, hot_list = hot_list, newart_list = newart_list, newcom_list = newcom_list, ) return redirect(url_for('blog.index')) @blog.route('/t/<int:tag_id>/', methods=['GET']) def tag(tag_id): length = 5 page = request.args.get('page', '1') page = page and int(page) or 1 tag_obj = Tag.query.get_or_404(tag_id) article_list = Article.query.filter_by(status='p').filter( Article.id.in_(tag_obj.getRefArticleIDs) ).paginate( page, per_page=length, error_out = False) tag_list = caches.getTaglist() hot_list = caches.getHotlist() newart_list = caches.getNewArticlelist() newcom_list = caches.getNewCommontlist() return render_template( 'blog/index.html', tag_name=tag_obj, article_list=article_list, tag_list = tag_list, hot_list = hot_list, newart_list = newart_list, newcom_list = newcom_list, ) @blog.route('/about', methods=['GET', 'POST']) def about(): form = SuggestForm() if request.method == "POST": if form.validate(): obj = Suggest( username=form.username.data, email=form.email.data, content=form.content.data ) db.session.add(obj) db.session.commit() flash(u'您宝贵的意见已收到,谢谢!.', 'success') return redirect(url_for('blog.about')) return render_template('blog/about.html', form=form)
{"/app/blog/models.py": ["/app/__init__.py", "/app/libs/tools.py"], "/app/__init__.py": ["/app/api/jwt_auth.py", "/app/admin/__init__.py", "/app/blog/__init__.py"], "/app/api/jwt_auth.py": ["/app/auth/models.py"], "/app/blog/views.py": ["/app/__init__.py", "/app/blog/__init__.py", "/app/blog/forms.py", "/app/blog/models.py"], "/app/admin/forms.py": ["/app/blog/models.py"], "/app/admin/views.py": ["/app/__init__.py", "/app/admin/__init__.py", "/app/admin/forms.py", "/app/blog/models.py"], "/app/blog/caches.py": ["/app/__init__.py", "/app/blog/models.py"], "/app/auth/models.py": ["/app/__init__.py"], "/manage.py": ["/app/__init__.py", "/app/auth/models.py", "/app/blog/models.py"], "/app/auth/views.py": ["/app/auth/models.py", "/app/__init__.py"]}
20,810
yc19890920/flask-blog
refs/heads/master
/gconf.py
# -*-coding:utf-8 -*- __author__ = "YC" import os import multiprocessing BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # chdir = BASE_DIR # 监听本机的5000端口 bind = '0.0.0.0:6060' # 开启进程 workers = multiprocessing.cpu_count() * 2 + 1 # 每个进程的开启线程 threads = multiprocessing.cpu_count() * 2 # 等待连接的最大数 backlog = 2048 #工作模式为meinheld worker_class = "egg:meinheld#gunicorn_worker" # 如果不使用supervisord之类的进程管理工具可以是进程成为守护进程,否则会出问题 daemon = False # 进程名称 # proc_name = 'gunicorn.pid' proc_name = os.path.join(BASE_DIR, 'log', 'gunicorn.pid') # 进程pid记录文件 pidfile = os.path.join(BASE_DIR, 'log', 'app.pid') logfile = os.path.join(BASE_DIR, 'log', 'debug.log') # 要写入的访问日志目录 accesslog = os.path.join(BASE_DIR, 'log', 'access.log') # 要写入错误日志的文件目录。 errorlog = os.path.join(BASE_DIR, 'log', 'error.log') # print(BASE_DIR) # 日志格式 # access_log_format = '%(h)s %(t)s %(U)s %(q)s' access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"' # 日志等级 loglevel = 'debug'
{"/app/blog/models.py": ["/app/__init__.py", "/app/libs/tools.py"], "/app/__init__.py": ["/app/api/jwt_auth.py", "/app/admin/__init__.py", "/app/blog/__init__.py"], "/app/api/jwt_auth.py": ["/app/auth/models.py"], "/app/blog/views.py": ["/app/__init__.py", "/app/blog/__init__.py", "/app/blog/forms.py", "/app/blog/models.py"], "/app/admin/forms.py": ["/app/blog/models.py"], "/app/admin/views.py": ["/app/__init__.py", "/app/admin/__init__.py", "/app/admin/forms.py", "/app/blog/models.py"], "/app/blog/caches.py": ["/app/__init__.py", "/app/blog/models.py"], "/app/auth/models.py": ["/app/__init__.py"], "/manage.py": ["/app/__init__.py", "/app/auth/models.py", "/app/blog/models.py"], "/app/auth/views.py": ["/app/auth/models.py", "/app/__init__.py"]}
20,811
yc19890920/flask-blog
refs/heads/master
/app/admin/forms.py
# -*- coding: utf-8 -*- from flask import url_for from flask_wtf import FlaskForm from wtforms import ValidationError from wtforms.fields import BooleanField, PasswordField, StringField, SubmitField, TextAreaField, SelectField, SelectMultipleField from wtforms.fields.html5 import EmailField from wtforms.validators import Email, EqualTo, InputRequired, Length from app.blog.models import Article, Category ARTICLE_STATUS = [('p', u'发布'), ('d', u'延迟发布')] class ArticleForm(FlaskForm): title = StringField(u'标题', validators=[InputRequired(), Length(1, 100)]) content = TextAreaField(u'内容', validators=[InputRequired()]) abstract = TextAreaField(u'摘要', validators=[InputRequired()]) auth = StringField(u'作者', validators=[InputRequired(), Length(1, 50)]) source = StringField(u'来源') status = SelectField(u"文章状态", validators=[InputRequired()], choices=ARTICLE_STATUS) category = SelectField(u"分类", coerce=int, validators=[InputRequired()]) tags = SelectMultipleField(u"标签", coerce=int, validators=[InputRequired()])
{"/app/blog/models.py": ["/app/__init__.py", "/app/libs/tools.py"], "/app/__init__.py": ["/app/api/jwt_auth.py", "/app/admin/__init__.py", "/app/blog/__init__.py"], "/app/api/jwt_auth.py": ["/app/auth/models.py"], "/app/blog/views.py": ["/app/__init__.py", "/app/blog/__init__.py", "/app/blog/forms.py", "/app/blog/models.py"], "/app/admin/forms.py": ["/app/blog/models.py"], "/app/admin/views.py": ["/app/__init__.py", "/app/admin/__init__.py", "/app/admin/forms.py", "/app/blog/models.py"], "/app/blog/caches.py": ["/app/__init__.py", "/app/blog/models.py"], "/app/auth/models.py": ["/app/__init__.py"], "/manage.py": ["/app/__init__.py", "/app/auth/models.py", "/app/blog/models.py"], "/app/auth/views.py": ["/app/auth/models.py", "/app/__init__.py"]}
20,812
yc19890920/flask-blog
refs/heads/master
/app/admin/views.py
# -*- coding: utf-8 -*- import os import re import json import uuid import random from flask import Response, make_response from flask_login import login_required from flask import flash, redirect, render_template, request, url_for, abort from jinja2.nativetypes import NativeEnvironment from app import db, csrf, Config from app.admin import admin from app.admin.forms import ArticleForm from app.blog.models import Tag, Category, Article, CKPicture, BlogComment, Suggest ############################################ @admin.route('/admin/home', methods=['GET']) @login_required def home(): return render_template('admin/home.html') ############################################ @admin.route('/admin/tag', methods=['GET', 'POST']) @login_required def tag(): if request.method == "POST": id = request.form.get('id', "") name = request.form.get('name', "").strip() status = request.form.get('status', "") if status == "delete": obj = Tag.query.filter_by(id=id).first() db.session.delete(obj) db.session.commit() flash(u'删除成功', 'success') if status == "add": if not name: flash(u'输入为空,操作失败', 'error') return redirect(url_for('admin.tag')) if Tag.query.filter_by(name=name).first(): flash(u'重复添加,添加失败', 'error') else: tag = Tag(name=name) db.session.add(tag) db.session.commit() flash(u'添加成功', 'success') return redirect(url_for('admin.tag')) tag_list = Tag.query.all() return render_template('admin/blog/tag.html', tag_list=tag_list) ############################################ @admin.route('/admin/category', methods=['GET', 'POST']) @login_required def category(): if request.method == "POST": id = request.form.get('id', "") name = request.form.get('name', "").strip() status = request.form.get('status', "") if status == "delete": obj = Category.query.filter_by(id=id).first() db.session.delete(obj) db.session.commit() flash(u'删除成功', 'success') if status == "add": if not name: flash(u'输入为空,操作失败', 'error') return redirect(url_for('admin.category')) if Category.query.filter_by(name=name).first(): flash(u'重复添加,添加失败', 'error') else: tag = Category(name=name) db.session.add(tag) db.session.commit() flash(u'添加成功', 'success') return redirect(url_for('admin.category')) tag_list = Category.query.all() return render_template('admin/blog/category.html', tag_list=tag_list) ############################################ @admin.route('/admin/article', methods=['GET', 'POST']) @login_required def article(): if request.method == "POST": id = request.form.get('id', "") status = request.form.get('status', "") if status == "delete": obj = Article.query.filter_by(id=id).first() if obj: Article.referPic(0, obj.content, obj.abstract) db.session.delete(obj) db.session.commit() flash(u'删除成功', 'success') return redirect(url_for('admin.article')) return render_template('admin/blog/article.html') @admin.route('/admin/article/ajax', methods=['GET', 'POST']) @login_required def article_ajax(): data = request.args order_column = data.get('order[0][column]', '') order_dir = data.get('order[0][dir]', '') search = data.get('search[value]', '') colums = ['id', 'title'] order_T = Article.id.desc() if order_column and int(order_column) < len(colums): if order_dir == 'desc': if int(order_column) == 0: order_T = Article.id.desc() else: order_T = Article.title.desc() else: if int(order_column) == 0: order_T = Article.id.asc() else: order_T = Article.title.asc() try: length = int(data.get('length', 1)) except ValueError: length = 1 try: start_num = int(data.get('start', '0')) page = start_num / length + 1 except ValueError: start_num = 0 page = 1 count = Article.query.count() if start_num >= count: page = 1 rs = {"sEcho": 0, "iTotalRecords": count, "iTotalDisplayRecords": count, "aaData": []} re_str = '<td.*?>(.*?)</td>' # if search: # pagination = Article.query.filter(Article.title.like("%%s%", search)).order_by(order_T).paginate(page, per_page=length, error_out = False) # else: # pass pagination = Article.query.order_by(order_T).paginate(page, per_page=length, error_out = False) lists = pagination.items number = length * (page-1) + 1 for d in lists: html = render_template('admin/blog/ajax_article.html', d=d, number=number) rs["aaData"].append(re.findall(re_str, html, re.DOTALL)) number += 1 return Response(json.dumps(rs), content_type="application/json") env = NativeEnvironment() from_string = u""" <td>{{ number }}</td> <td>{{ d.title|e }}</td> <td>{{ d.show_status_display }}</td> <td>{{ d.auth|e }}</td> <td>{{ d.source|e }}</td> <td>{{ d.views }}</td> <td>{{ d.likes }}</td> <td>{{ d.created }}</td> <td>{{ d.updated }}</td> <td>{{ d.category.name }}</td> <td> {% for t in d.tags %} <button type="button" class="btn btn-minier btn-primary "> {{ t.name }}</button> {% endfor %} </td> <td> <a type="button" class="btn btn-minier btn-primary" href="{{ d.get_modify_uri }}">修改</a> <a type="button" class="btn btn-minier btn-danger" href="Javascript: setStatus({{ d.id }}, 'delete')">删除</a> {% if d.status == 'p' %} <a class="btn btn-minier btn-primary" href="#" target="_blank">查看文章</a> {% endif %} </td> """ for d in lists: t = env.from_string(from_string) result = t.render(number=number, d=d) rs["aaData"].append(re.findall(re_str, result, re.DOTALL)) number += 1 return Response(json.dumps(rs), content_type="application/json") @admin.route('/admin/article/add', methods=['GET', 'POST']) @login_required def article_add(): if request.method == "POST": form = ArticleForm(request.form) form.category.choices = Category.get_choice_lists() form.tags.choices = Tag.get_choice_lists() # if form.validate_on_submit(): if form.validate(): article = Article( title=form.title.data, content=form.content.data, abstract=form.abstract.data, auth=form.auth.data, source=form.source.data, status=form.status.data, category=Category.get_obj(int(form.category.data)), tags=Tag.str_to_obj(form.tags.data)) db.session.add(article) db.session.commit() Article.referPic(article.id, form.content.data, form.abstract.data) flash(u'添加文章成功.', 'success') return redirect(url_for('admin.article')) else: form = ArticleForm(title="", content="", abstract="", auth="Y.c", source="", status="p", category_id=0, tags=[2,]) form.category.choices = Category.get_choice_lists() form.tags.choices = Tag.get_choice_lists() return render_template('admin/blog/article_add.html', form=form) @admin.route('/admin/article/<int:article_id>/', methods=['GET', 'POST']) @login_required def article_modify(article_id): article_obj = Article.query.filter_by(id=article_id).first_or_404() # article_obj = Article.query.get(article_id) # if article_obj is None: # abort(404) if request.method == "POST": form = ArticleForm(request.form) form.category.choices = Category.get_choice_lists() form.tags.choices = Tag.get_choice_lists() if form.validate(): article_obj.title = form.title.data article_obj.content = form.content.data article_obj.abstract = form.abstract.data article_obj.auth = form.auth.data article_obj.source = form.source.data article_obj.status = form.status.data article_obj.Category = Category.get_obj(int(form.category.data)) article_obj.tags = Tag.str_to_obj(form.tags.data) Article.referPic(0, form.content.data, form.abstract.data) db.session.add(article_obj) db.session.commit() Article.referPic(article_id, form.content.data, form.abstract.data) flash(u'修改文章成功.', 'success') return redirect(url_for('admin.article')) else: form = ArticleForm( title=article_obj.title, content=article_obj.content, abstract=article_obj.abstract, auth=article_obj.auth, source=article_obj.source, status=article_obj.status, category=article_obj.category_id, tags=article_obj.get_tags_id ) form.category.choices = Category.get_choice_lists() form.tags.choices = Tag.get_choice_lists() return render_template('admin/blog/article_add.html', form=form) @csrf.exempt @admin.route('/admin/ckupload', methods=['POST']) @login_required def ckupload(): """CKEditor file upload""" error = '' callback = request.args.get("CKEditorFuncNum") print (request.files['upload']) if request.method == 'POST' and 'upload' in request.files: fileobj = request.files['upload'] content_type = fileobj.content_type size = fileobj.content_length fname = fileobj.filename fext = os.path.splitext(fname)[-1] uuname = '{}{}{}'.format(str(uuid.uuid1()).replace("-", ""), random.randint(1, 100000), fext) url = url_for('static', filename='%s/%s' % ('ckupload', uuname)) try: fname = fname.encode("utf-8") except BaseException as e: fname = uuname print (e) path = os.path.join(Config.CKUPLOAD_DIR, uuname) fileobj.save(path) ck = CKPicture( filename=fname, filetype=content_type, filepath=url,filesize=size ) db.session.add(ck) db.session.commit() res = """ <script type="text/javascript"> window.parent.CKEDITOR.tools.callFunction(%s, '%s', '%s'); </script> """ % (callback, url, error) response = make_response(res) response.headers["Content-Type"] = "text/html" return response raise abort(403) ############################################ @admin.route('/admin/picture', methods=['GET', 'POST']) @login_required def picture(): if request.method == "POST": status = request.form.get('status', "") if status == "delete": id = request.form.get('id', "") obj = CKPicture.query.filter_by(id=int(id), article_id=0).first() if obj: obj.removepath() db.session.delete(obj) db.session.commit() flash(u'删除成功', 'success') if status == "deleteall": ids = ( request.form.get('ids', False) ).split(',') objs = CKPicture.str_to_obj(ids) for obj in objs: obj.removepath() db.session.delete(obj) db.session.commit() flash(u'批量删除成功', 'success') return redirect(url_for('admin.picture')) tag_list = CKPicture.query.all() return render_template('admin/blog/picture.html', tag_list=tag_list) ############################################ @admin.route('/admin/comment', methods=['GET', 'POST']) @login_required def comment(): if request.method == "POST": id = request.form.get('id', "") status = request.form.get('status', "") if status == "delete": obj = BlogComment.query.filter_by(id=id).first() if obj: db.session.delete(obj) db.session.commit() flash(u'删除成功', 'success') return redirect(url_for('admin.comment')) tag_list = BlogComment.query.all() return render_template('admin/blog/comment.html', tag_list=tag_list) ############################################ @admin.route('/admin/suggest', methods=['GET', 'POST']) @login_required def suggest(): if request.method == "POST": id = request.form.get('id', "") status = request.form.get('status', "") if status == "delete": obj = Suggest.query.filter_by(id=id).first() if obj: db.session.delete(obj) db.session.commit() flash(u'删除成功', 'success') return redirect(url_for('admin.suggest')) tag_list = Suggest.query.all() return render_template('admin/blog/suggest.html', tag_list=tag_list)
{"/app/blog/models.py": ["/app/__init__.py", "/app/libs/tools.py"], "/app/__init__.py": ["/app/api/jwt_auth.py", "/app/admin/__init__.py", "/app/blog/__init__.py"], "/app/api/jwt_auth.py": ["/app/auth/models.py"], "/app/blog/views.py": ["/app/__init__.py", "/app/blog/__init__.py", "/app/blog/forms.py", "/app/blog/models.py"], "/app/admin/forms.py": ["/app/blog/models.py"], "/app/admin/views.py": ["/app/__init__.py", "/app/admin/__init__.py", "/app/admin/forms.py", "/app/blog/models.py"], "/app/blog/caches.py": ["/app/__init__.py", "/app/blog/models.py"], "/app/auth/models.py": ["/app/__init__.py"], "/manage.py": ["/app/__init__.py", "/app/auth/models.py", "/app/blog/models.py"], "/app/auth/views.py": ["/app/auth/models.py", "/app/__init__.py"]}
20,813
yc19890920/flask-blog
refs/heads/master
/app/blog/caches.py
# -*- coding: utf-8 -*- import json from app import redis from app.blog.models import Tag, Article, BlogComment REDIS_KEY = "flask:cce7e4f11fc518f7fff230079ab0edc9" # 标签缓存 def getTaglist(): key = "{}:tag".format(REDIS_KEY) field = "tag" if redis.exists(key): vals = json.loads( redis.hget(key, field) ) else: vals = [] lists = Tag.query.order_by(Tag.name).all() for d in lists: vals.append( { "id": d.id, "name": d.name } ) if vals: p = redis.pipeline() p.hset(key, field, json.dumps(vals)) p.expire(key, 60*60) p.execute() return vals # 最热文章列表 def getHotlist(): key = "{}:article:hot".format(REDIS_KEY) field = "hot" if redis.exists(key): vals = json.loads( redis.hget(key, field) ) else: vals = [] lists = Article.query.filter_by(status='p').order_by(Article.views.desc()).limit(10) for d in lists: vals.append( { "id": d.id, "title": d.title } ) if vals: p = redis.pipeline() p.hset(key, field, json.dumps(vals)) p.expire(key, 15*60) p.execute() return vals # 最新文章列表 def getNewArticlelist(): key = "{}:article:new".format(REDIS_KEY) field = "new" if redis.exists(key): vals = json.loads( redis.hget(key, field) ) else: vals = [] lists = Article.query.filter_by(status='p').order_by(Article.id.desc()).limit(10) for d in lists: vals.append( { "id": d.id, "title": d.title } ) if vals: p = redis.pipeline() p.hset(key, field, json.dumps(vals)) p.expire(key, 15*60) p.execute() return vals # 最新评论 def getNewCommontlist(): key = "{}:comment:new".format(REDIS_KEY) field = "new" if redis.exists(key): vals = json.loads( redis.hget(key, field) ) else: vals = [] lists = BlogComment.query.order_by(BlogComment.id.desc()).limit(10).all() for d in lists: vals.append( { "id": d.id, "article_id": d.article_id, "content": d.content } ) if vals: p = redis.pipeline() p.hset(key, field, json.dumps(vals)) p.expire(key, 15*60) p.execute() return vals # 文章点击 缓存 def shouldIncrViews(ip, article_id): key = "{}:{}:{}:article:view".format(REDIS_KEY, ip, article_id) if redis.exists(key): return False p = redis.pipeline() p.set(key, "1") p.expire(key, 5*60) p.execute() return True def getLinks(ip, article_id): key = "{}:{}:{}:article:links".format(REDIS_KEY, ip, article_id) if redis.exists(key): return False return True
{"/app/blog/models.py": ["/app/__init__.py", "/app/libs/tools.py"], "/app/__init__.py": ["/app/api/jwt_auth.py", "/app/admin/__init__.py", "/app/blog/__init__.py"], "/app/api/jwt_auth.py": ["/app/auth/models.py"], "/app/blog/views.py": ["/app/__init__.py", "/app/blog/__init__.py", "/app/blog/forms.py", "/app/blog/models.py"], "/app/admin/forms.py": ["/app/blog/models.py"], "/app/admin/views.py": ["/app/__init__.py", "/app/admin/__init__.py", "/app/admin/forms.py", "/app/blog/models.py"], "/app/blog/caches.py": ["/app/__init__.py", "/app/blog/models.py"], "/app/auth/models.py": ["/app/__init__.py"], "/manage.py": ["/app/__init__.py", "/app/auth/models.py", "/app/blog/models.py"], "/app/auth/views.py": ["/app/auth/models.py", "/app/__init__.py"]}
20,814
yc19890920/flask-blog
refs/heads/master
/doc/api.py
# -*- coding: utf-8 -*- # import json import requests from urlparse import urljoin BASE_URL = 'http://192.168.1.24:5000/' AUTH = ('admin', '1qaz@WSX') def get_article_list(): url = urljoin(BASE_URL, '/api/v1/posts/') print(url) rsp = requests.get( url, auth=AUTH, headers={ 'Accept': 'application/json', 'Content-Type': 'application/json', }) # assert rsp.ok print('get_article_list: ', rsp.ok, rsp.status_code, rsp.text) def main(): get_article_list() if __name__ == "__main__": main()
{"/app/blog/models.py": ["/app/__init__.py", "/app/libs/tools.py"], "/app/__init__.py": ["/app/api/jwt_auth.py", "/app/admin/__init__.py", "/app/blog/__init__.py"], "/app/api/jwt_auth.py": ["/app/auth/models.py"], "/app/blog/views.py": ["/app/__init__.py", "/app/blog/__init__.py", "/app/blog/forms.py", "/app/blog/models.py"], "/app/admin/forms.py": ["/app/blog/models.py"], "/app/admin/views.py": ["/app/__init__.py", "/app/admin/__init__.py", "/app/admin/forms.py", "/app/blog/models.py"], "/app/blog/caches.py": ["/app/__init__.py", "/app/blog/models.py"], "/app/auth/models.py": ["/app/__init__.py"], "/manage.py": ["/app/__init__.py", "/app/auth/models.py", "/app/blog/models.py"], "/app/auth/views.py": ["/app/auth/models.py", "/app/__init__.py"]}
20,815
yc19890920/flask-blog
refs/heads/master
/app/auth/models.py
# -*- coding: utf-8 -*- import hashlib from datetime import datetime from flask import current_app from flask import url_for from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from itsdangerous import BadSignature, SignatureExpired from werkzeug.security import generate_password_hash, check_password_hash from flask_login import AnonymousUserMixin, UserMixin from app import db, login_manager class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True, nullable=False) email = db.Column(db.String(64), index=True, nullable=False) password_hash = db.Column(db.String(128), nullable=False) def __init__(self, **kwargs): super(User, self).__init__(**kwargs) def can(self, _): return True def is_admin(self): return True @property def password(self): raise AttributeError('`password` is not a readable attribute') @password.setter def password(self, password): self.password_hash = generate_password_hash(password) def verify_password(self, password): return check_password_hash(self.password_hash, password) def generate_confirmation_token(self, expiration=604800): """Generate a confirmation token to email a new user.""" s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'confirm': self.id}) def generate_email_change_token(self, new_email, expiration=3600): """Generate an email change token to email an existing user.""" s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'change_email': self.id, 'new_email': new_email}) def generate_password_reset_token(self, expiration=3600): """ Generate a password reset change token to email to an existing user. """ s = Serializer(current_app.config['SECRET_KEY'], expiration) return s.dumps({'reset': self.id}) def confirm_account(self, token): """Verify that the provided token is for this user's id.""" s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except (BadSignature, SignatureExpired): return False if data.get('confirm') != self.id: return False self.confirmed = True db.session.add(self) db.session.commit() return True def change_email(self, token): """Verify the new email for this user.""" s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except (BadSignature, SignatureExpired): return False if data.get('change_email') != self.id: return False new_email = data.get('new_email') if new_email is None: return False if self.query.filter_by(email=new_email).first() is not None: return False self.email = new_email db.session.add(self) db.session.commit() return True def reset_password(self, token, new_password): """Verify the new password for this user.""" s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except (BadSignature, SignatureExpired): return False if data.get('reset') != self.id: return False self.password = new_password db.session.add(self) db.session.commit() return True def __repr__(self): return '<User \'%s\'>' % self.username def to_json(self): json_user = { # 'url': url_for('api.get_user', id=self.id), 'username': self.username, 'email': self.email, # 'member_since': self.member_since, # 'last_seen': self.last_seen, # 'posts_url': url_for('api.get_user_posts', id=self.id), # 'followed_posts_url': url_for('api.get_user_followed_posts', id=self.id), # 'post_count': self.posts.count() } return json_user def generate_auth_token(self, expiration): s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({'id': self.id}).decode('utf-8') @staticmethod def verify_auth_token(token): s = Serializer(current_app.config['SECRET_KEY']) try: data = s.loads(token) except: return None return User.query.get(data['id']) class AnonymousUser(AnonymousUserMixin): def can(self, _): return False def is_admin(self): return False login_manager.anonymous_user = AnonymousUser @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id))
{"/app/blog/models.py": ["/app/__init__.py", "/app/libs/tools.py"], "/app/__init__.py": ["/app/api/jwt_auth.py", "/app/admin/__init__.py", "/app/blog/__init__.py"], "/app/api/jwt_auth.py": ["/app/auth/models.py"], "/app/blog/views.py": ["/app/__init__.py", "/app/blog/__init__.py", "/app/blog/forms.py", "/app/blog/models.py"], "/app/admin/forms.py": ["/app/blog/models.py"], "/app/admin/views.py": ["/app/__init__.py", "/app/admin/__init__.py", "/app/admin/forms.py", "/app/blog/models.py"], "/app/blog/caches.py": ["/app/__init__.py", "/app/blog/models.py"], "/app/auth/models.py": ["/app/__init__.py"], "/manage.py": ["/app/__init__.py", "/app/auth/models.py", "/app/blog/models.py"], "/app/auth/views.py": ["/app/auth/models.py", "/app/__init__.py"]}
20,816
yc19890920/flask-blog
refs/heads/master
/manage.py
# -*- coding: utf-8 -*- import os # import gevent # import gevent.monkey # gevent.monkey.patch_all() from flask_migrate import Migrate, MigrateCommand from flask_script import Manager, Shell, Server # from app import create_app, db from app import app, db from app.auth.models import User from app.blog.models import Tag, Category, Article, CKPicture, BlogComment, Suggest # app = create_app() manager = Manager(app) migrate = Migrate(app, db) # import sys # print >> sys.stderr, app.url_map def make_shell_context(): return dict( app=app, db=db, User=User,Tag=Tag, Category=Category, Article=Article, CKPicture=CKPicture, BlogComment=BlogComment, Suggest=Suggest ) manager.add_command('shell', Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) # manager.add_command( 'runserver', Server(host='localhost', port=8080, debug=True) ) manager.add_command( 'runserver', Server(host='0.0.0.0', port=6060 ) ) @manager.command def recreate_db(): """ Recreates a local database. You probably should not use this on production. """ db.drop_all() db.create_all() db.session.commit() if __name__ == '__main__': manager.run()
{"/app/blog/models.py": ["/app/__init__.py", "/app/libs/tools.py"], "/app/__init__.py": ["/app/api/jwt_auth.py", "/app/admin/__init__.py", "/app/blog/__init__.py"], "/app/api/jwt_auth.py": ["/app/auth/models.py"], "/app/blog/views.py": ["/app/__init__.py", "/app/blog/__init__.py", "/app/blog/forms.py", "/app/blog/models.py"], "/app/admin/forms.py": ["/app/blog/models.py"], "/app/admin/views.py": ["/app/__init__.py", "/app/admin/__init__.py", "/app/admin/forms.py", "/app/blog/models.py"], "/app/blog/caches.py": ["/app/__init__.py", "/app/blog/models.py"], "/app/auth/models.py": ["/app/__init__.py"], "/manage.py": ["/app/__init__.py", "/app/auth/models.py", "/app/blog/models.py"], "/app/auth/views.py": ["/app/auth/models.py", "/app/__init__.py"]}
20,817
yc19890920/flask-blog
refs/heads/master
/app/blog/forms.py
# -*- coding: utf-8 -*- from flask import url_for from flask_wtf import FlaskForm from wtforms import ValidationError from wtforms.fields import BooleanField, PasswordField, StringField, SubmitField, TextAreaField, SelectField, SelectMultipleField from wtforms.fields.html5 import EmailField from wtforms.validators import Email, EqualTo, InputRequired, Length class CommentForm(FlaskForm): username = StringField('Username', validators=[InputRequired(), Length(1, 64)]) email = EmailField('Email', validators=[InputRequired(), Length(1, 64), Email()]) content = TextAreaField(u'内容', validators=[InputRequired()]) class SuggestForm(FlaskForm): username = StringField('Username', validators=[InputRequired(), Length(1, 64)]) email = EmailField('Email', validators=[InputRequired(), Length(1, 64), Email()]) content = TextAreaField(u'内容', validators=[InputRequired()])
{"/app/blog/models.py": ["/app/__init__.py", "/app/libs/tools.py"], "/app/__init__.py": ["/app/api/jwt_auth.py", "/app/admin/__init__.py", "/app/blog/__init__.py"], "/app/api/jwt_auth.py": ["/app/auth/models.py"], "/app/blog/views.py": ["/app/__init__.py", "/app/blog/__init__.py", "/app/blog/forms.py", "/app/blog/models.py"], "/app/admin/forms.py": ["/app/blog/models.py"], "/app/admin/views.py": ["/app/__init__.py", "/app/admin/__init__.py", "/app/admin/forms.py", "/app/blog/models.py"], "/app/blog/caches.py": ["/app/__init__.py", "/app/blog/models.py"], "/app/auth/models.py": ["/app/__init__.py"], "/manage.py": ["/app/__init__.py", "/app/auth/models.py", "/app/blog/models.py"], "/app/auth/views.py": ["/app/auth/models.py", "/app/__init__.py"]}
20,818
yc19890920/flask-blog
refs/heads/master
/doc/jwt_token_api.py
# -*- coding: utf-8 -*- # import json import requests from urlparse import urljoin BASE_URL = 'http://192.168.1.24:6060/' AUTH = ('admin', '1qaz@WSX') """ curl -X POST -d '{"title":"a","code":"print a"}' http://django2blog.com/api/tag/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' # http -a admin:1qaz@WSX POST http://django2blog.com/api/tag/ name="tag1" # curl -d "user=admin&passwd=1qaz@WSX" "http://django2blog.com/api/tag/" """ from flask.views import MethodView def get_jwt_token(): # url = urljoin(BASE_URL, '/api/jwt-auth') url = urljoin(BASE_URL, '/jwt-auth') rsp = requests.post( url, headers={ 'Accept': 'application/json', 'Content-Type': 'application/json', }, data=json.dumps({ "username":"admin", "password":"1qaz@WSX"}) ) print(rsp.status_code) print(rsp.text) print(rsp.content) j = rsp.json() # print(j) return j["access_token"] def main(): token = get_jwt_token() print(token) if __name__ == "__main__": main()
{"/app/blog/models.py": ["/app/__init__.py", "/app/libs/tools.py"], "/app/__init__.py": ["/app/api/jwt_auth.py", "/app/admin/__init__.py", "/app/blog/__init__.py"], "/app/api/jwt_auth.py": ["/app/auth/models.py"], "/app/blog/views.py": ["/app/__init__.py", "/app/blog/__init__.py", "/app/blog/forms.py", "/app/blog/models.py"], "/app/admin/forms.py": ["/app/blog/models.py"], "/app/admin/views.py": ["/app/__init__.py", "/app/admin/__init__.py", "/app/admin/forms.py", "/app/blog/models.py"], "/app/blog/caches.py": ["/app/__init__.py", "/app/blog/models.py"], "/app/auth/models.py": ["/app/__init__.py"], "/manage.py": ["/app/__init__.py", "/app/auth/models.py", "/app/blog/models.py"], "/app/auth/views.py": ["/app/auth/models.py", "/app/__init__.py"]}
20,819
yc19890920/flask-blog
refs/heads/master
/configm.py
# -*-coding:utf-8 -*- __author__ = "YC" import os import multiprocessing BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 加载应用程序之前将chdir目录指定到指定目录 # gunicorn要切换到的目的工作目录 chdir = BASE_DIR # 监听本机的5000端口 # 绑定运行的主机加端口 -b --bind bind = '0.0.0.0:6060' # 开启进程 # 用于处理工作进程的数量,整数,默认为1 -w --workers # workers=4 workers = multiprocessing.cpu_count() * 2 + 1 # 处理请求的工作线程数,使用指定数量的线程运行每个worker。为正整数,默认为1 --threads INT # 每个进程的开启线程 threads = multiprocessing.cpu_count() * 2 # 要使用的工作模式,默认为sync异步,类型:sync, eventlet, gevent, tornado, gthread, gaiohttp -k STRTING, --worker-class STRTING # 工作模式为meinheld worker_class = "egg:meinheld#gunicorn_worker" # 最大客户端并发数量,默认1000 --worker-connections INT worker_connections = 2000 # 等待连接的最大数,默认2048 --backlog int backlog = 2048 # 重新启动之前,工作将处理的最大请求数。默认值为0。 # --max-requests INT max_requests = 0 # 要添加到max_requests的最大抖动。抖动将导致每个工作的重启被随机化,这是为了避免所有工作被重启。randint(0,max-requests-jitter) # --max-requests-jitter INT max_requests_jitter = 0 # 限制HTTP请求行的允许大小,默认4094。取值范围0~8190,此参数可以防止任何DDOS攻击 # --limit-request-line INT limit_request_line = 4094 # 限制HTTP请求头字段的数量以防止DDOS攻击,与limit-request-field-size一起使用可以提高安全性。默认100,最大值32768 # --limit-request-fields INT limit_request_fields = 100 # 限制HTTP请求中请求头的大小,默认8190。值是一个整数或者0,当该值为0时,表示将对请求头大小不做限制 # --limit-request-field-size INT limit_request_field_size = 8190 # debug=True # 进程名称 proc_name = os.path.join(BASE_DIR, 'gunicorn.pid') # 'gunicorn.pid' # 设置pid文件的文件名,如果不设置将不会创建pid文件 -p FILE, --pid FILE # 进程pid记录文件 pidfile = os.path.join(BASE_DIR, 'app.pid') # 日志文件路径 --access-logfile FILE logfile = os.path.join(BASE_DIR, 'debug.log') # 'debug.log' # 日志文件路径 --access-logfile FILE # 要写入的访问日志目录 accesslog = os.path.join(BASE_DIR, 'access.log') # 'access.log' # 错误日志文件路径 --error-logfile FILE, --log-file FILE # 要写入错误日志的文件目录。 errorlog = os.path.join(BASE_DIR, 'error.log') # 设置gunicorn访问日志格式,错误日志无法设置 # 日志格式,--access_log_format '%(h)s %(l)s %(u)s %(t)s' access_log_format = '%(h)s %(t)s %(U)s %(q)s' # access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"' # 日志输出等级 --log-level LEVEL loglevel = 'debug' # loglevel = 'info' # 在代码改变时自动重启,默认False --reload # 代码更新时将重启工作,默认为False。此设置用于开发,每当应用程序发生更改时,都会导致工作重新启动。 reload = False # 选择重载的引擎,支持的有三种: auto pull inotity:需要下载 # --reload-engine STRTING reload_engine = "auto" # 如果不使用supervisord之类的进程管理工具可以是进程成为守护进程,否则会出问题 # 守护Gunicorn进程,默认False --daemon daemon = False # 超过设置后工作将被杀掉并重新启动,默认30s,nginx默认60s -t INT, --timeout INT timeout = 30 # 默认30,在超时(从接收到重启信号开始)之后仍然活着的工作将被强行杀死;一般默认 # 优雅的人工超时时间,默认情况下,这个值为30。收到重启信号后,工作人员有那么多时间来完成服务请求。在超时(从接收到重启信号开始)之后仍然活着的工作将被强行杀死。 # --graceful-timeout INT graceful_timeout = 30 # 在keep-alive连接上等待请求的秒数,默认情况下值为2。一般设定在1~5秒之间 # --keep-alive INT keepalive = 2 # 打印服务器执行过的每一条语句,默认False。此选择为原子性的,即要么全部打印,要么全部不打印 # --spew spew = False # 显示当前的配置,默认False,即显示 --check-config check_config = False # 在工作进程被复制(派生)之前加载应用程序代码,默认为False。通过预加载应用程序,你可以节省RAM资源,并且加快服务器启动时间。 # --preload preload_app = False # 设置环境变量 -e ENV, --env ENV # 设置环境变量(key=value),将变量传递给执行环境,如: # gunicorin -b 127.0.0.1:8000 -e abc=123 manager:app # 在配置文件中写法: raw_env=["abc=123"] raw_env = ["abc=123"]
{"/app/blog/models.py": ["/app/__init__.py", "/app/libs/tools.py"], "/app/__init__.py": ["/app/api/jwt_auth.py", "/app/admin/__init__.py", "/app/blog/__init__.py"], "/app/api/jwt_auth.py": ["/app/auth/models.py"], "/app/blog/views.py": ["/app/__init__.py", "/app/blog/__init__.py", "/app/blog/forms.py", "/app/blog/models.py"], "/app/admin/forms.py": ["/app/blog/models.py"], "/app/admin/views.py": ["/app/__init__.py", "/app/admin/__init__.py", "/app/admin/forms.py", "/app/blog/models.py"], "/app/blog/caches.py": ["/app/__init__.py", "/app/blog/models.py"], "/app/auth/models.py": ["/app/__init__.py"], "/manage.py": ["/app/__init__.py", "/app/auth/models.py", "/app/blog/models.py"], "/app/auth/views.py": ["/app/auth/models.py", "/app/__init__.py"]}
20,820
yc19890920/flask-blog
refs/heads/master
/app/admin/__init__.py
# -*- coding: utf-8 -*- from flask import Blueprint admin = Blueprint('admin', __name__) from app.admin import views
{"/app/blog/models.py": ["/app/__init__.py", "/app/libs/tools.py"], "/app/__init__.py": ["/app/api/jwt_auth.py", "/app/admin/__init__.py", "/app/blog/__init__.py"], "/app/api/jwt_auth.py": ["/app/auth/models.py"], "/app/blog/views.py": ["/app/__init__.py", "/app/blog/__init__.py", "/app/blog/forms.py", "/app/blog/models.py"], "/app/admin/forms.py": ["/app/blog/models.py"], "/app/admin/views.py": ["/app/__init__.py", "/app/admin/__init__.py", "/app/admin/forms.py", "/app/blog/models.py"], "/app/blog/caches.py": ["/app/__init__.py", "/app/blog/models.py"], "/app/auth/models.py": ["/app/__init__.py"], "/manage.py": ["/app/__init__.py", "/app/auth/models.py", "/app/blog/models.py"], "/app/auth/views.py": ["/app/auth/models.py", "/app/__init__.py"]}
20,821
yc19890920/flask-blog
refs/heads/master
/app/blog/__init__.py
# -*- coding: utf-8 -*- from flask import Blueprint blog = Blueprint('blog', __name__) from app.blog import views
{"/app/blog/models.py": ["/app/__init__.py", "/app/libs/tools.py"], "/app/__init__.py": ["/app/api/jwt_auth.py", "/app/admin/__init__.py", "/app/blog/__init__.py"], "/app/api/jwt_auth.py": ["/app/auth/models.py"], "/app/blog/views.py": ["/app/__init__.py", "/app/blog/__init__.py", "/app/blog/forms.py", "/app/blog/models.py"], "/app/admin/forms.py": ["/app/blog/models.py"], "/app/admin/views.py": ["/app/__init__.py", "/app/admin/__init__.py", "/app/admin/forms.py", "/app/blog/models.py"], "/app/blog/caches.py": ["/app/__init__.py", "/app/blog/models.py"], "/app/auth/models.py": ["/app/__init__.py"], "/manage.py": ["/app/__init__.py", "/app/auth/models.py", "/app/blog/models.py"], "/app/auth/views.py": ["/app/auth/models.py", "/app/__init__.py"]}
20,822
yc19890920/flask-blog
refs/heads/master
/app/libs/tools.py
# -*- coding: utf-8 -*- from flask import request def getClientIP(): # x_forwarded_for = request.headers['X-Forwarded-For'] x_forwarded_for = request.headers.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: return x_forwarded_for.split(',')[0] _ip = request.headers.get("X-Real-IP") if _ip: return _ip return request.remote_addr import sys import six import datetime from decimal import Decimal _PROTECTED_TYPES = six.integer_types + ( type(None), float, Decimal, datetime.datetime, datetime.date, datetime.time ) # Useful for very coarse version differentiation. PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 PY34 = sys.version_info[0:2] >= (3, 4) if PY3: memoryview = memoryview buffer_types = (bytes, bytearray, memoryview) else: # memoryview and buffer are not strictly equivalent, but should be fine for # django core usage (mainly BinaryField). However, Jython doesn't support # buffer (see http://bugs.jython.org/issue1521), so we have to be careful. if sys.platform.startswith('java'): memoryview = memoryview else: memoryview = buffer buffer_types = (bytearray, memoryview) class Promise(object): """ This is just a base class for the proxy class created in the closure of the lazy function. It can be used to recognize promises in code. """ pass def is_protected_type(obj): """Determine if the object instance is of a protected type. Objects of protected types are preserved as-is when passed to force_text(strings_only=True). """ return isinstance(obj, _PROTECTED_TYPES) def smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict'): """ Returns a bytestring version of 's', encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, Promise): # The input is the result of a gettext_lazy() call. return s return force_bytes(s, encoding, strings_only, errors) def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_bytes, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first for performance reasons. if isinstance(s, bytes): if encoding == 'utf-8': return s else: return s.decode('utf-8', errors).encode(encoding, errors) if strings_only and is_protected_type(s): return s if isinstance(s, memoryview): return bytes(s) if isinstance(s, Promise): return six.text_type(s).encode(encoding, errors) if not isinstance(s, six.string_types): try: if six.PY3: return six.text_type(s).encode(encoding) else: return bytes(s) except UnicodeEncodeError: if isinstance(s, Exception): # An Exception subclass containing non-ASCII data that doesn't # know how to print itself properly. We shouldn't raise a # further exception. return b' '.join(force_bytes(arg, encoding, strings_only, errors) for arg in s) return six.text_type(s).encode(encoding, errors) else: return s.encode(encoding, errors)
{"/app/blog/models.py": ["/app/__init__.py", "/app/libs/tools.py"], "/app/__init__.py": ["/app/api/jwt_auth.py", "/app/admin/__init__.py", "/app/blog/__init__.py"], "/app/api/jwt_auth.py": ["/app/auth/models.py"], "/app/blog/views.py": ["/app/__init__.py", "/app/blog/__init__.py", "/app/blog/forms.py", "/app/blog/models.py"], "/app/admin/forms.py": ["/app/blog/models.py"], "/app/admin/views.py": ["/app/__init__.py", "/app/admin/__init__.py", "/app/admin/forms.py", "/app/blog/models.py"], "/app/blog/caches.py": ["/app/__init__.py", "/app/blog/models.py"], "/app/auth/models.py": ["/app/__init__.py"], "/manage.py": ["/app/__init__.py", "/app/auth/models.py", "/app/blog/models.py"], "/app/auth/views.py": ["/app/auth/models.py", "/app/__init__.py"]}
20,823
yc19890920/flask-blog
refs/heads/master
/app/auth/views.py
# -*- coding: utf-8 -*- from flask import flash, redirect, render_template, request, url_for from flask_login import current_user, login_required, login_user, logout_user from app.auth import auth from app.auth.models import User from app.auth.forms import LoginForm, RegistrationForm from app import db @auth.route('/login', methods=['GET', 'POST']) def login(): """Log in an existing user.""" form = LoginForm() if request.method == 'POST': # print '-------------------', request.form.get("username", "") if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is not None and user.password_hash is not None and user.verify_password(form.password.data): login_user(user, form.remember_me.data) flash('You are now logged in. Welcome back!', 'success') return redirect(request.args.get('next') or url_for('admin.home')) else: flash('Invalid username or password.', 'error') return render_template('auth/login.html', form=form) @auth.route('/register', methods=['GET', 'POST']) def register(): """ Register a new user, and send them a confirmation email.""" form = RegistrationForm(request.form) if request.method == 'POST': if form.validate_on_submit(): user = User( username=form.username.data, email=form.email.data, password=form.password.data) db.session.add(user) db.session.commit() token = user.generate_confirmation_token() # confirm_link = url_for('account.confirm', token=token, _external=True) # get_queue().enqueue( # send_email, # recipient=user.email, # subject='Confirm Your Account', # template='account/email/confirm', # user=user, # confirm_link=confirm_link) # flash('A confirmation link has been sent to {}.'.format(user.email), 'warning') flash(u'注册成功.', 'success') return redirect(url_for('auth.login')) return render_template('auth/register.html', form=form) @auth.route('/logout') @login_required def logout(): logout_user() flash('You have been logged out.', 'info') return redirect(url_for('auth.login'))
{"/app/blog/models.py": ["/app/__init__.py", "/app/libs/tools.py"], "/app/__init__.py": ["/app/api/jwt_auth.py", "/app/admin/__init__.py", "/app/blog/__init__.py"], "/app/api/jwt_auth.py": ["/app/auth/models.py"], "/app/blog/views.py": ["/app/__init__.py", "/app/blog/__init__.py", "/app/blog/forms.py", "/app/blog/models.py"], "/app/admin/forms.py": ["/app/blog/models.py"], "/app/admin/views.py": ["/app/__init__.py", "/app/admin/__init__.py", "/app/admin/forms.py", "/app/blog/models.py"], "/app/blog/caches.py": ["/app/__init__.py", "/app/blog/models.py"], "/app/auth/models.py": ["/app/__init__.py"], "/manage.py": ["/app/__init__.py", "/app/auth/models.py", "/app/blog/models.py"], "/app/auth/views.py": ["/app/auth/models.py", "/app/__init__.py"]}
20,858
chshaiiith/PySimulator
refs/heads/master
/request_stream.py
from distribution import Distribution from arrival import Arrival from request import Request from request_handler import Requesthandler import json import simulator class RequestStream(): def __init__(self, type = None): self.type = None if type: self.type = type else: # Just to verify if the with open("properties.json") as fp: config = json.load(fp) self.type = config["request"]["type"] self.arrival = Arrival() self.request = Request(type) self.req_handler = Requesthandler.get_handler() self.add_arrival_event() def update_type(self, type): self.type = None if type and type != "default": self.type = type else: # Just to verify if the with open("properties.json") as fp: config = json.load(fp) self.type = config["request"]["type"] # Re-assigning the request based on the variable self.request = Request(type) self.add_arrival_event() def add_arrival_event(self): request = self.request.next_request() request["start_time"] = self.arrival.next_arrival() event = { "request" : request, "time": request["start_time"], "callback" : callback, "stream": self, "type": "arrival" } simulator.schedule(event) return def callback(event): event["stream"].req_handler.add_request(event["request"]) if simulator.required_request_count > 0: simulator.required_request_count -= 1 event["stream"].add_arrival_event() return
{"/request_stream.py": ["/distribution.py", "/arrival.py", "/request.py", "/request_handler.py", "/simulator.py"], "/request_handler.py": ["/request_handler_fifo.py", "/request_handler_priority.py"], "/distribution.py": ["/deterministic.py", "/possion.py"], "/simulator.py": ["/stats.py", "/request_handler_fifo.py"], "/shortest_job_first_policy.py": ["/request_handler_fifo.py"], "/arrival.py": ["/distribution.py", "/simulator.py"], "/request_handler_fifo.py": ["/simulator.py", "/allocation_policy.py", "/stats.py", "/distribution.py"]}
20,859
chshaiiith/PySimulator
refs/heads/master
/mean_percentile.py
import numpy as np import matplotlib.pyplot as plt arr_3 = [] arr_6 = [] arr_24 = [] arr_48 = [] m_arr_3 = [] m_arr_6 = [] m_arr_24 = [] m_arr_48 = [] # ========3 ================ k = np.loadtxt("3_point51") d = np.sort(k) arr_3.append(np.percentile(d, 90)) print "with (3,1) and mean arrival rate = 1 , percentile = " + str(np.percentile(d, 90)) m_arr_3.append(np.mean(d)) k = np.loadtxt("3_11") d = np.sort(k) arr_3.append(np.percentile(d, 90)) m_arr_3.append(np.mean(d)) print "with (3,1) and mean arrival rate = 2 , percentile = " + str(np.percentile(d, 90)) k = np.loadtxt("3_21") d = np.sort(k) arr_3.append(np.percentile(d, 90)) m_arr_3.append(np.mean(d)) k = np.loadtxt("3_41") d = np.sort(k) arr_3.append(np.percentile(d, 90)) m_arr_3.append(np.mean(d)) k = np.loadtxt("3_81") d = np.sort(k) arr_3.append(np.percentile(d, 90)) m_arr_3.append(np.mean(d)) k = np.loadtxt("3_121") d = np.sort(k) arr_3.append(np.percentile(d, 90)) m_arr_3.append(np.mean(d)) k = np.loadtxt("3_141") d = np.sort(k) arr_3.append(np.percentile(d, 90)) m_arr_3.append(np.mean(d)) k = np.loadtxt("3_161") d = np.sort(k) arr_3.append(np.percentile(d, 90)) m_arr_3.append(np.mean(d)) # ==========6 ================= k = np.loadtxt("6_point51") d = np.sort(k) arr_6.append(np.percentile(d, 90)) m_arr_6.append(np.mean(d)) print "with (6,2) and mean arrival rate = 1 , percentile = " + str(np.percentile(d, 90)) k = np.loadtxt("6_11") d = np.sort(k) arr_6.append(np.percentile(d, 90)) m_arr_6.append(np.mean(d)) print "with (6,2) and mean arrival rate = 2 , percentile = " + str(np.percentile(d, 90)) k = np.loadtxt("6_21") d = np.sort(k) arr_6.append(np.percentile(d, 90)) m_arr_6.append(np.mean(d)) k = np.loadtxt("6_41") d = np.sort(k) arr_6.append(np.percentile(d, 90)) m_arr_6.append(np.mean(d)) k = np.loadtxt("6_81") d = np.sort(k) arr_6.append(np.percentile(d, 90)) m_arr_6.append(np.mean(d)) k = np.loadtxt("6_121") d = np.sort(k) arr_6.append(np.percentile(d, 90)) m_arr_6.append(np.mean(d)) k = np.loadtxt("6_141") d = np.sort(k) arr_6.append(np.percentile(d, 90)) m_arr_6.append(np.mean(d)) k = np.loadtxt("6_161") d = np.sort(k) arr_6.append(np.percentile(d, 90)) m_arr_6.append(np.mean(d)) #==========================24 ============= k = np.loadtxt("24_point51") d = np.sort(k) arr_24.append(np.percentile(d, 90)) m_arr_24.append(np.mean(d)) print "with (24,8) and mean arrival rate = 1 , percentile = " + str(np.percentile(d, 90)) k = np.loadtxt("24_11") d = np.sort(k) arr_24.append(np.percentile(d, 90)) m_arr_24.append(np.mean(d)) k = np.loadtxt("24_21") d = np.sort(k) arr_24.append(np.percentile(d, 90)) m_arr_24.append(np.mean(d)) k = np.loadtxt("24_41") d = np.sort(k) arr_24.append(np.percentile(d, 90)) m_arr_24.append(np.mean(d)) k = np.loadtxt("24_81") d = np.sort(k) arr_24.append(np.percentile(d, 90)) m_arr_24.append(np.mean(d)) k = np.loadtxt("24_121") d = np.sort(k) arr_24.append(np.percentile(d, 90)) m_arr_24.append(np.mean(d)) k = np.loadtxt("24_141") d = np.sort(k) arr_24.append(np.percentile(d, 90)) m_arr_24.append(np.mean(d)) k = np.loadtxt("24_161") d = np.sort(k) arr_24.append(np.percentile(d, 90)) m_arr_24.append(np.mean(d)) x_axis = [1,2,4,8,16,24,28,32] plt.plot(x_axis, arr_3, label="3,1") plt.plot(x_axis, arr_6, label = "6,2") plt.plot(x_axis, arr_24, label = "24,8") plt.legend(['(3,1)', '(6,2)', '(24,8)'], loc='upper left') plt.grid(which="minor", axis="y") plt.minorticks_on() plt.xlabel("Mean Arrival rate") plt.ylabel("90th percentile") plt.tight_layout() plt.show() # ========================== 48 ========= # # # # k = np.loadtxt("6_11") # d = np.sort(k) # # print np.percentile(d, 90) # # # k = np.loadtxt("24_11") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # # k = np.loadtxt("48_11") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # # k = np.loadtxt("3_21") # d = np.sort(k) # # print np.percentile(d, 90) # # k = np.loadtxt("6_21") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # k = np.loadtxt("24_21") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # k = np.loadtxt("48_21") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # k = np.loadtxt("3_41") # d = np.sort(k) # # print np.percentile(d, 90) # # # # k = np.loadtxt("6_41") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # k = np.loadtxt("24_41") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # # k = np.loadtxt("48_41") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # # k = np.loadtxt("8_81") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # k = np.loadtxt("24_81") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # # k = np.loadtxt("48_81") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # k = np.loadtxt("6_121") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # k = np.loadtxt("24_121") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # k = np.loadtxt("48_121") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # # k = np.loadtxt("6_141") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # k = np.loadtxt("24_141") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # k = np.loadtxt("48_141") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # k = np.loadtxt("6_161") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # # k = np.loadtxt("24_161") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # k = np.loadtxt("48_161") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # k = np.loadtxt("3_161") # d = np.sort(k) # # #print np.mean(d) # print np.percentile(d, 90) # # # # # # # k = np.loadtxt("experiement_point_2/M_6_2_point_200001") # # d = np.sort(k) # # # # #print np.mean(d) # # print np.percentile(d, 99) # # # # k = np.loadtxt("experiement_point_2/M_24_8_point_200001") # # d = np.sort(k) # # # # print np.mean(d) # # print np.percentile(d, 99) # # # # k = np.loadtxt("experiement_point_2/24_8_point10001") # # d = np.sort(k) # # # # print np.mean(d) # print np.percentile(d, 80)
{"/request_stream.py": ["/distribution.py", "/arrival.py", "/request.py", "/request_handler.py", "/simulator.py"], "/request_handler.py": ["/request_handler_fifo.py", "/request_handler_priority.py"], "/distribution.py": ["/deterministic.py", "/possion.py"], "/simulator.py": ["/stats.py", "/request_handler_fifo.py"], "/shortest_job_first_policy.py": ["/request_handler_fifo.py"], "/arrival.py": ["/distribution.py", "/simulator.py"], "/request_handler_fifo.py": ["/simulator.py", "/allocation_policy.py", "/stats.py", "/distribution.py"]}
20,860
chshaiiith/PySimulator
refs/heads/master
/possion.py
from numpy.random import exponential import time class Possion(): def __init__(self, **kwargs): self.rate = kwargs["rate"] def next(self): data = exponential(1.0/self.rate) return data
{"/request_stream.py": ["/distribution.py", "/arrival.py", "/request.py", "/request_handler.py", "/simulator.py"], "/request_handler.py": ["/request_handler_fifo.py", "/request_handler_priority.py"], "/distribution.py": ["/deterministic.py", "/possion.py"], "/simulator.py": ["/stats.py", "/request_handler_fifo.py"], "/shortest_job_first_policy.py": ["/request_handler_fifo.py"], "/arrival.py": ["/distribution.py", "/simulator.py"], "/request_handler_fifo.py": ["/simulator.py", "/allocation_policy.py", "/stats.py", "/distribution.py"]}
20,861
chshaiiith/PySimulator
refs/heads/master
/request_handler.py
from request_handler_fifo import RequesthandlerFiFo from request_handler_priority import RequesthandlerPriority import json class Requesthandler: @classmethod def get_handler(self): with open("properties.json") as fp: config = json.load(fp) allowed = config["request"]["cancellation"] if not allowed: return RequesthandlerFiFo() else: return RequesthandlerPriority()
{"/request_stream.py": ["/distribution.py", "/arrival.py", "/request.py", "/request_handler.py", "/simulator.py"], "/request_handler.py": ["/request_handler_fifo.py", "/request_handler_priority.py"], "/distribution.py": ["/deterministic.py", "/possion.py"], "/simulator.py": ["/stats.py", "/request_handler_fifo.py"], "/shortest_job_first_policy.py": ["/request_handler_fifo.py"], "/arrival.py": ["/distribution.py", "/simulator.py"], "/request_handler_fifo.py": ["/simulator.py", "/allocation_policy.py", "/stats.py", "/distribution.py"]}
20,862
chshaiiith/PySimulator
refs/heads/master
/distribution.py
from deterministic import Deterministic from possion import Possion class Distribution: @classmethod def get_distribution(cls, type, **kwargs): if type == "deterministic": return Deterministic(**kwargs) if type == "poisson": return Possion(**kwargs) # XXX: add more types as per requirements here
{"/request_stream.py": ["/distribution.py", "/arrival.py", "/request.py", "/request_handler.py", "/simulator.py"], "/request_handler.py": ["/request_handler_fifo.py", "/request_handler_priority.py"], "/distribution.py": ["/deterministic.py", "/possion.py"], "/simulator.py": ["/stats.py", "/request_handler_fifo.py"], "/shortest_job_first_policy.py": ["/request_handler_fifo.py"], "/arrival.py": ["/distribution.py", "/simulator.py"], "/request_handler_fifo.py": ["/simulator.py", "/allocation_policy.py", "/stats.py", "/distribution.py"]}
20,863
chshaiiith/PySimulator
refs/heads/master
/stats.py
import json total_request = 0 total_time = 0 # Used for file numbering total_files = 0 import os class Stats: def __init__(self): global f global file_name with open("properties.json") as fp: config = json.load(fp) file_name = config["stats"]["fileName"] self.no_of_request = config["stats"]["noOfRequest"] if os.path.exists(file_name + str(total_files)): os.remove(file_name + str(total_files)) f = open(file_name + str(total_files), "a+") def collect_stats(self, event): global total_time global total_request total_time += event["time"] - event["request"]["start_time"] f.write(str(event["time"] - event["request"]["start_time"]) + " ") # print "stats: total_time " + str(event["time"] - event["request"]["start_time"]) # print "stats: request time " + str(event["request"]["request_size"]) # f.write(str(event["request"]["request_size"]) + " ") total_request += 1 if total_request == self.no_of_request: print_stat() def reset(): global total_time global total_request total_time = 0 total_request = 0 def global_reset(): global total_files global f reset() f.close() total_files += 1 if os.path.exists(file_name + str(total_files)): os.remove(file_name + str(total_files)) f = open(file_name + str(total_files), "a+") def print_stat(): global total_request global total_request print total_time/total_request reset()
{"/request_stream.py": ["/distribution.py", "/arrival.py", "/request.py", "/request_handler.py", "/simulator.py"], "/request_handler.py": ["/request_handler_fifo.py", "/request_handler_priority.py"], "/distribution.py": ["/deterministic.py", "/possion.py"], "/simulator.py": ["/stats.py", "/request_handler_fifo.py"], "/shortest_job_first_policy.py": ["/request_handler_fifo.py"], "/arrival.py": ["/distribution.py", "/simulator.py"], "/request_handler_fifo.py": ["/simulator.py", "/allocation_policy.py", "/stats.py", "/distribution.py"]}
20,864
chshaiiith/PySimulator
refs/heads/master
/request.py
import json import uuid import simulator import numpy as np import random from distribution import Distribution current_request_id = 0 class Request: def __init__(self, type): # To store ids of write request, will be used for read # All possible types self.types = ["read", "write"] with open("properties.json") as fp: config = json.load(fp) rate = config["job"]["rate"] self.distribution = Distribution.get_distribution(config["job"]["distribution"], rate = rate) #In case of mixed workload these variables represent the % of read and writes in workload self.type = type self.read_percentage = config["request"]["readPercentage"] self.write_percentage = config["request"]["writePercentage"] # Probability percentage self.probability_percentage = [self.read_percentage*1.0/100, self.write_percentage*1.0/100] # To store the sample request distribution based on type and probability self.request_distribution = [] def next_request(self): request = None # In case of mixed workload if self.type == "mixed": if len(self.request_distribution) > 0: current_request_type = self.types[self.request_distribution[-1]] self.request_distribution = self.request_distribution[:-1] else: self.request_distribution = np.random.choice(2, 10000, p=self.probability_percentage) current_request_type = self.types[self.request_distribution[-1]] self.request_distribution = self.request_distribution[:-1] if current_request_type == "read": return self.get_read_request() else: return self.get_write_request() # In case of read workload elif self.type == "read": return self.get_read_request() # In case of write workload elif self.type == "write": return self.get_write_request() #Only return when request type is not read or write print "Not supported type is mentioned : Only {read, write} is supported" return request def get_read_request(self): global current_request_id id = random.randint(0 , current_request_id - 1) request = {"request_size": self.distribution.next(), "type": "read", "id": id} return request def get_write_request(self): global current_request_id request = {"request_size": self.distribution.next(), "type": "write", "id": current_request_id} current_request_id += 1 return request
{"/request_stream.py": ["/distribution.py", "/arrival.py", "/request.py", "/request_handler.py", "/simulator.py"], "/request_handler.py": ["/request_handler_fifo.py", "/request_handler_priority.py"], "/distribution.py": ["/deterministic.py", "/possion.py"], "/simulator.py": ["/stats.py", "/request_handler_fifo.py"], "/shortest_job_first_policy.py": ["/request_handler_fifo.py"], "/arrival.py": ["/distribution.py", "/simulator.py"], "/request_handler_fifo.py": ["/simulator.py", "/allocation_policy.py", "/stats.py", "/distribution.py"]}
20,865
chshaiiith/PySimulator
refs/heads/master
/new_plot_2.py
import matplotlib matplotlib.use('Agg') import numpy as np import matplotlib.pyplot as plt import seaborn as sns clear_bkgd = {'axes.facecolor':'none', 'figure.facecolor':'none'} sns.set(style='ticks', context='notebook', palette="muted", rc=clear_bkgd) x = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] k = np.loadtxt("without_queueing_3_lambda") d = np.sort(k) t1 = [] for i in x: t1.append(np.percentile(d, i)) y = np.array(t1) k1 = np.loadtxt("without_queueing_6_lambda") d1 = np.sort(k1) t2 = [] for i in x: t2.append(np.percentile(d1, i)) y1 = np.array(t2) k2 = np.loadtxt("without_queueing_24_lambda") d2 = np.sort(k2) t3 = [] for i in x: t3.append(np.percentile(d2, i)) y2 = np.array(t3) # k3 = np.loadtxt("result_sjf/without_queue_effect24_8_R") # d3 = np.sort(k3) # t4 = [] # for i in x: # t4.append(np.percentile(d3, i)) # y3 = np.array(t4) # Number of intervals to display. # Later calculations add 2 to this number to pad it to align with the reversed axis num_intervals = 3 x_values = 1.0 - 1.0/10**np.arange(0,num_intervals+2) # Start with hard-coded lengths for 0,90,99 # Rest of array generated to display correct number of decimal places as precision increases lengths = [1,2,2] + [int(v)+1 for v in list(np.arange(3,num_intervals+2))] # Build the label string by trimming on the calculated lengths and appending % labels = [str(100*v)[0:l] + "%" for v,l in zip(x_values, lengths)] fig, ax = plt.subplots(figsize=(8, 4)) ax.set_xscale('log') plt.gca().invert_xaxis() # Labels have to be reversed because axis is reversed ax.xaxis.set_ticklabels( labels[::-1] ) ax.plot(y, [100.0 - v for v in x]) ax.plot(y, [100.0 - v for v in x]) ax.plot(y, [100.0 - v for v in x]) #ax.plot([100.0 - v for v in x], y3) ax.grid(True, linewidth=0.5, zorder=5) ax.grid(True, which='minor', linewidth=0.5, linestyle=':') ax.set_ylabel("Percentile") ax.set_xlabel("request service time (without queueing)") sns.despine(fig=fig) plt.tight_layout() plt.legend(['(3,1)', '(6,2)', '(24,8)'], loc='upper left') plt.savefig("new_graph_1.png", dpi=300, format='png')
{"/request_stream.py": ["/distribution.py", "/arrival.py", "/request.py", "/request_handler.py", "/simulator.py"], "/request_handler.py": ["/request_handler_fifo.py", "/request_handler_priority.py"], "/distribution.py": ["/deterministic.py", "/possion.py"], "/simulator.py": ["/stats.py", "/request_handler_fifo.py"], "/shortest_job_first_policy.py": ["/request_handler_fifo.py"], "/arrival.py": ["/distribution.py", "/simulator.py"], "/request_handler_fifo.py": ["/simulator.py", "/allocation_policy.py", "/stats.py", "/distribution.py"]}
20,866
chshaiiith/PySimulator
refs/heads/master
/random_policy.py
import random import json class RandomPolicy: def __init__(self): with open("properties.json") as fp: config = json.load(fp) self.number_of_servers = config["server"]["numberOfServers"] self.read_server = config["server"]["readServer"] self.write_server = config["server"]["writeServer"] self.serverlist = [x for x in range(0, self.number_of_servers)] def get_server(self, type_of_request, possible_servers=None): if type_of_request == "read": count = self.read_server return random.sample(possible_servers, count) else: count = self.write_server return random.sample(self.serverlist, count)
{"/request_stream.py": ["/distribution.py", "/arrival.py", "/request.py", "/request_handler.py", "/simulator.py"], "/request_handler.py": ["/request_handler_fifo.py", "/request_handler_priority.py"], "/distribution.py": ["/deterministic.py", "/possion.py"], "/simulator.py": ["/stats.py", "/request_handler_fifo.py"], "/shortest_job_first_policy.py": ["/request_handler_fifo.py"], "/arrival.py": ["/distribution.py", "/simulator.py"], "/request_handler_fifo.py": ["/simulator.py", "/allocation_policy.py", "/stats.py", "/distribution.py"]}
20,867
chshaiiith/PySimulator
refs/heads/master
/deterministic.py
class Deterministic: def __init__(self, **kwargs): self.length = kwargs["rate"] def next(self): return self.length
{"/request_stream.py": ["/distribution.py", "/arrival.py", "/request.py", "/request_handler.py", "/simulator.py"], "/request_handler.py": ["/request_handler_fifo.py", "/request_handler_priority.py"], "/distribution.py": ["/deterministic.py", "/possion.py"], "/simulator.py": ["/stats.py", "/request_handler_fifo.py"], "/shortest_job_first_policy.py": ["/request_handler_fifo.py"], "/arrival.py": ["/distribution.py", "/simulator.py"], "/request_handler_fifo.py": ["/simulator.py", "/allocation_policy.py", "/stats.py", "/distribution.py"]}
20,868
chshaiiith/PySimulator
refs/heads/master
/hashing_policy.py
import hashlib import json class HashingPolicy: def __init__(self): with open("properties.json") as fp: config = json.load(fp) self.number_of_servers = config["server"]["numberOfServers"] self.read_server = config["readServer"] self.write_server = config["writeServer"] def get_server(self, request): #XXX: Todo: Hashing based on some policy return []
{"/request_stream.py": ["/distribution.py", "/arrival.py", "/request.py", "/request_handler.py", "/simulator.py"], "/request_handler.py": ["/request_handler_fifo.py", "/request_handler_priority.py"], "/distribution.py": ["/deterministic.py", "/possion.py"], "/simulator.py": ["/stats.py", "/request_handler_fifo.py"], "/shortest_job_first_policy.py": ["/request_handler_fifo.py"], "/arrival.py": ["/distribution.py", "/simulator.py"], "/request_handler_fifo.py": ["/simulator.py", "/allocation_policy.py", "/stats.py", "/distribution.py"]}
20,869
chshaiiith/PySimulator
refs/heads/master
/new_plot.py
import matplotlib matplotlib.use('Agg') import numpy as np import matplotlib.pyplot as plt import seaborn as sns def plot(fileName): clear_bkgd = {'axes.facecolor':'none', 'figure.facecolor':'none'} sns.set(style='ticks', context='notebook', palette="muted", rc=clear_bkgd) x = [30, 60, 80, 90, 95, 97, 98, 98.5, 98.9, 99.1, 99.2, 99.3, 99.4, 100] k = np.loadtxt("6_2_1_4_R") d = np.sort(k) t1 = [] for i in x: t1.append(np.percentile(d, i)) y = np.array(t1) print np.mean(d) print np.percentile(y , 99) print np.mean(d) print np.percentile(y , 99) k = np.loadtxt("6_2_1_4_R") d = np.sort(k) # k3 = np.loadtxt("results/24_8_l_W") # d3 = np.sort(k3) # t4 = [] # for i in x: # t4.append(np.percentile(d3, i)) # y3 = np.array(t4) # Number of intervals to display. # Later calculations add 2 to this number to pad it to align with the reversed axis num_intervals = 3 x_values = 1.0 - 1.0/10**np.arange(0,num_intervals+2) # Start with hard-coded lengths for 0,90,99 # Rest of array generated to display correct number of decimal places as precision increases lengths = [1,2,2] + [int(v)+1 for v in list(np.arange(3,num_intervals+2))] # Build the label string by trimming on the calculated lengths and appending % labels = [str(100*v)[0:l] + "%" for v,l in zip(x_values, lengths)] fig, ax = plt.subplots(figsize=(8, 4)) ax.set_xscale('log') plt.gca().invert_xaxis() # Labels have to be reversed because axis is reversed ax.xaxis.set_ticklabels( labels[::-1] ) ax.plot([100.0 - v for v in x], y) # ax.plot([100.0 - v for v in x], y1) # ax.plot([100.0 - v for v in x], y2) #ax.plot([100.0 - v for v in x], y3) ax.grid(True, linewidth=0.5, zorder=5) ax.grid(True, which='minor', linewidth=0.5, linestyle=':') ax.set_xlabel("Percentile") ax.set_ylabel("request service time") sns.despine(fig=fig) plt.tight_layout() # plt.legend(['(3,1)', '(6,2)', '(12,4)', '(24,8)'], loc='upper left') plt.savefig("test.png", dpi=300, format='png')
{"/request_stream.py": ["/distribution.py", "/arrival.py", "/request.py", "/request_handler.py", "/simulator.py"], "/request_handler.py": ["/request_handler_fifo.py", "/request_handler_priority.py"], "/distribution.py": ["/deterministic.py", "/possion.py"], "/simulator.py": ["/stats.py", "/request_handler_fifo.py"], "/shortest_job_first_policy.py": ["/request_handler_fifo.py"], "/arrival.py": ["/distribution.py", "/simulator.py"], "/request_handler_fifo.py": ["/simulator.py", "/allocation_policy.py", "/stats.py", "/distribution.py"]}
20,870
chshaiiith/PySimulator
refs/heads/master
/allocation_policy.py
from hashing_policy import HashingPolicy from random_policy import RandomPolicy from shortest_job_first_policy import SJF class AllocationPolicy: @classmethod def get_policy(cls, type): if type == "random": return RandomPolicy() if type == "hash": return HashingPolicy() if type == "sjf": return SJF() print "No such type of policy defined" return
{"/request_stream.py": ["/distribution.py", "/arrival.py", "/request.py", "/request_handler.py", "/simulator.py"], "/request_handler.py": ["/request_handler_fifo.py", "/request_handler_priority.py"], "/distribution.py": ["/deterministic.py", "/possion.py"], "/simulator.py": ["/stats.py", "/request_handler_fifo.py"], "/shortest_job_first_policy.py": ["/request_handler_fifo.py"], "/arrival.py": ["/distribution.py", "/simulator.py"], "/request_handler_fifo.py": ["/simulator.py", "/allocation_policy.py", "/stats.py", "/distribution.py"]}
20,871
chshaiiith/PySimulator
refs/heads/master
/part_3_plots.py
import numpy as np x_axis = [] y_axis = [] x1 = [] x2 = [] file_names = ["11", "21", "41", "81", "121", "141", "161"] x_axiz = [1,2,4,8,12,14,16] file_data = ["3","6","24", "48"] for d1 in file_data: for f1 in file_names: k = np.loadtxt(d1 + "_" + f1) d = np.sort(k) np.percentile(d, 90) for i in range(1, 100): x_axis.append(np.percentile(d, i)) y_axis.append((i*1.0)/100) for i in range(1, 100): x1.append(np.percentile(d1, i)) x2.append((i*1.0)/100) plt.plot(x_axis, y_axis) plt.plot(x1, y_axis) plt.show()
{"/request_stream.py": ["/distribution.py", "/arrival.py", "/request.py", "/request_handler.py", "/simulator.py"], "/request_handler.py": ["/request_handler_fifo.py", "/request_handler_priority.py"], "/distribution.py": ["/deterministic.py", "/possion.py"], "/simulator.py": ["/stats.py", "/request_handler_fifo.py"], "/shortest_job_first_policy.py": ["/request_handler_fifo.py"], "/arrival.py": ["/distribution.py", "/simulator.py"], "/request_handler_fifo.py": ["/simulator.py", "/allocation_policy.py", "/stats.py", "/distribution.py"]}
20,872
chshaiiith/PySimulator
refs/heads/master
/test.py
from request_stream import RequestStream import simulator import request_handler_fifo req_stream = RequestStream("write") simulator.run(100000) #print simulator.time #print simulator.required_request_count print "#######################\n" print "Done with insertions. Now will perform required operations" print "#######################\n" req_stream.update_type("mixed") simulator.run(100000)
{"/request_stream.py": ["/distribution.py", "/arrival.py", "/request.py", "/request_handler.py", "/simulator.py"], "/request_handler.py": ["/request_handler_fifo.py", "/request_handler_priority.py"], "/distribution.py": ["/deterministic.py", "/possion.py"], "/simulator.py": ["/stats.py", "/request_handler_fifo.py"], "/shortest_job_first_policy.py": ["/request_handler_fifo.py"], "/arrival.py": ["/distribution.py", "/simulator.py"], "/request_handler_fifo.py": ["/simulator.py", "/allocation_policy.py", "/stats.py", "/distribution.py"]}