\\r\\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_content_right(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n def content_right():\n return render_content_right(context)\n __M_writer = context.writer()\n __M_writer('\\r\\n
\\r\\n Do you have any locations on the East Coast?
\\r\\n\")\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n\"\"\"\n__M_BEGIN_METADATA\n{\"filename\": \"C:/Users/mayaroney/desktop/fomo/homepage/templates/faq.html\", \"uri\": \"faq.html\", \"source_encoding\": \"utf-8\", \"line_map\": {\"29\": 0, \"42\": 1, \"47\": 6, \"52\": 11, \"57\": 15, \"62\": 28, \"68\": 4, \"74\": 4, \"80\": 8, \"86\": 8, \"92\": 13, \"98\": 13, \"104\": 18, \"110\": 18, \"116\": 110}}\n__M_END_METADATA\n\"\"\"\n","sub_path":"homepage/templates/.cached_templates/faq.html.py","file_name":"faq.html.py","file_ext":"py","file_size_in_byte":5010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"275065441","text":"# Победители Мировой серии.\n\ndef main():\n filename = 'WorldSeriesWinners.txt'\n\n # Сохраняю в переменую прочитаный файл.\n rf = read_file(filename)\n # Словарь с годами и победителями.\n yw = years_winners(rf)\n # Словарь с командами и кол-вом побед.\n cw = count_winners(yw)\n\n print('Введите год в диапазоне 1903 и 2009 годами.')\n year = input('Год: ')\n if year == '1904' or year == '1994':\n print('В', year, 'г. не проводили чемпионат.')\n elif year in yw:\n print('В этом году побеждала команда:', yw[year])\n comand = yw[year]\n print('У которой за сезон с 1903 - 2009 год -', cw[comand], 'побед(а/ы).')\n\ndef read_file(filename):\n \"\"\"Читаю данные из файла\"\"\"\n\n with open(filename, 'r', encoding='utf-8') as rfile:\n\n winner = rfile.read().split('\\n')\n\n rfile.close()\n\n return winner\n\ndef years_winners(filename):\n \"\"\"Годы и команды побеждающие в них\"\"\"\n\n # Пустой словарь.\n com_win_year = {}\n\n # Перебираю список.\n for f in filename:\n # Если в списке есть значение: 1904\n # 1994 пропускаем их.\n if f[0:4] == '1904' or f[0:4] == '1994':\n continue\n else:\n # Записываем ключ(год):значение(команда)\n com_win_year[f[0:4]] = f[5:]\n\n # Возвращаю словарь.\n return com_win_year\n\ndef count_winners(dict_winner):\n \"\"\"Команды и их победы с 1903 - 2009 г.\"\"\"\n\n # Пустой словарь.\n com_win = {}\n\n # Перебираю словарь.\n for v in dict_winner.values():\n # Если в словаре нет значение, то записываю.\n if v not in com_win:\n # Записываю значение ключ(команда):значение(кол-во побед)\n com_win[v] = list(dict_winner.values()).count(v)\n\n # Возвращаю словарь.\n return com_win\n\nmain()","sub_path":"9/tasks/9.7.py","file_name":"9.7.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"299432121","text":"# -*- coding: utf-8 -*-\n# @Time : 2017/10/11\n# @Author : ywh\n# @Email : yipwinghong@outlook.com\n# @File : Stack\n# @Software: PyCharm\n\nfrom data_structure.LinearList import *\n\nfrom array import array\nimport string\nimport random\n\nMAXSIZE = 10\n\n\nclass SqStack(object):\n \"\"\" 顺序栈 \"\"\"\n\n def __init__(self, elem=None, stack_size=MAXSIZE):\n \"\"\" 初始化 \"\"\"\n\n self.base = 0\n self.top = 0\n self.stack_size = stack_size\n if elem and len(elem) <= self.stack_size:\n self.top += len(elem)\n self.elem = elem\n else:\n self.elem = []\n\n def __len__(self):\n return self.top\n\n @property\n def is_full(self):\n return self.top - self.base == self.stack_size\n\n @property\n def is_empty(self):\n \"\"\" 判断是否空栈 \"\"\"\n return self.top == self.base\n\n @property\n def values(self):\n \"\"\" 取所有元素\"\"\"\n\n return self.elem\n\n def init_stack(self):\n \"\"\" 创建顺序栈 \"\"\"\n\n def push(self, value):\n \"\"\" 入栈 \"\"\"\n\n if self.is_full:\n return False\n\n self.top += 1\n self.elem.append(value)\n\n return True\n\n def pop(self):\n \"\"\" 出栈 \"\"\"\n\n if self.is_empty:\n return False\n\n self.top -= 1\n value = self.elem.pop()\n\n return value\n\n def get_top(self):\n \"\"\" 取栈顶元素 \"\"\"\n\n if self.top == self.base:\n return False\n\n return self.elem[-1]\n\n\nclass StackNode(object):\n \"\"\" 链栈节点 \"\"\"\n\n def __init__(self, elem=None, next=None):\n \"\"\" 初始化 \"\"\"\n\n self.elem = elem\n self.next = next\n\n\nclass LinkStack(object):\n \"\"\" 链栈 \"\"\"\n\n def __init__(self, elem=None):\n \"\"\" 初始化 \"\"\"\n\n self.top = StackNode() # 栈顶指针\n\n if elem:\n for value in elem:\n self.push(value)\n\n @property\n def values(self):\n \"\"\" 取所有元素 \"\"\"\n\n elem_list = []\n p = self.top.next\n while p:\n elem_list.insert(0, p.elem)\n p = p.next\n\n return elem_list\n\n def push(self, value):\n \"\"\" 入栈 \"\"\"\n\n # 新建节点,其next域置为栈顶指针next域,并把栈顶指针next域置为该节点\n self.top.next = StackNode(value, self.top.next)\n\n return True\n\n def pop(self):\n \"\"\" 出栈 \"\"\"\n\n # 取栈顶指针next域所指节点后弹出\n value = self.top.next.elem\n self.top.next = self.top.next.next\n\n return value\n\n\nclass DblStack(object):\n\n def __init__(self):\n self.top_0 = -1\n self.top_1 = MAXSIZE\n self.elem = [None] * MAXSIZE\n\n @property\n def is_empty(self):\n return self.top_0 == -1 and self.top_1 == MAXSIZE\n\n @property\n def is_full(self):\n return self.top_0 + 1 == self.top_1\n\n def push(self, stack_no, elem):\n if self.is_full:\n return False\n if stack_no == 0:\n self.top_0 += 1\n self.elem[self.top_0] = elem\n else:\n self.top_1 -= 1\n self.elem[self.top_1] = elem\n return True\n\n def pop(self, stack_no):\n if (stack_no == 0 and self.top_0 == -1) or (stack_no == 1 and self.top_1 == MAXSIZE):\n return False\n elif stack_no == 0:\n elem = self.elem[self.top_0]\n self.elem[self.top_0] = None\n self.top_0 -= 1\n else:\n elem = self.elem[self.top_1]\n self.elem[self.top_1] = None\n self.top_1 += 1\n\n return elem\n\n\n# 栈应用:数制转换\ndef coversion(num, system):\n \"\"\" 数制转换 \"\"\"\n\n remainder_stack = SqStack()\n while num:\n value = num % system\n remainder_stack.push(value)\n num //= system\n\n value = \"\"\n while not remainder_stack.is_empty:\n value += str(remainder_stack.pop())\n\n return value\n\n\n# 栈应用:符号匹配\ndef maching(symbol_list):\n \"\"\" 符号匹配 \"\"\"\n\n symbol_stack = SqStack()\n\n for item in list(symbol_list):\n if item in [\"(\", \"[\", \"{\"]:\n symbol_stack.push(item)\n elif (item == \")\" and symbol_stack.get_top() == \"(\") \\\n or (item == \"]\" and symbol_stack.get_top() == \"[\") \\\n or (item == \"}\" and symbol_stack.get_top() == \"{\"):\n symbol_stack.pop()\n else:\n break\n\n return True if symbol_stack.is_empty else False\n\n\n# 栈应用:表达式求值\ndef eval_expr(expr):\n \"\"\" 表达式求值 \"\"\"\n\n expr = list(expr)\n\n # 栈底元素\n if expr[0] != \"#\":\n return False\n\n # 算术符优先级\n precede_map = {\n (\"+\", \"+\"): \">\", (\"+\", \"-\"): \">\", (\"+\", \"*\"): \"<\", (\"+\", \"/\"): \"<\",\n (\"+\", \"(\"): \"<\", (\"+\", \")\"): \">\", (\"+\", \"#\"): \">\",\n (\"-\", \"+\"): \">\", (\"-\", \"-\"): \">\", (\"-\", \"*\"): \"<\", (\"-\", \"/\"): \"<\",\n (\"-\", \"(\"): \"<\", (\"-\", \")\"): \">\", (\"-\", \"#\"): \">\",\n (\"*\", \"+\"): \">\", (\"*\", \"-\"): \">\", (\"*\", \"*\"): \">\", (\"*\", \"/\"): \">\",\n (\"*\", \"(\"): \"<\", (\"*\", \")\"): \">\", (\"*\", \"#\"): \">\",\n (\"/\", \"+\"): \">\", (\"/\", \"-\"): \">\", (\"/\", \"*\"): \">\", (\"/\", \"/\"): \">\",\n (\"/\", \"(\"): \"<\", (\"/\", \")\"): \">\", (\"/\", \"#\"): \">\",\n (\"(\", \"+\"): \"<\", (\"(\", \"-\"): \"<\", (\"(\", \"*\"): \"<\", (\"(\", \"/\"): \"<\",\n (\"(\", \"(\"): \"<\", (\"(\", \")\"): \"=\", (\"(\", \"#\"): \"\",\n (\")\", \"+\"): \">\", (\")\", \"-\"): \">\", (\")\", \"*\"): \">\", (\")\", \"/\"): \">\",\n (\")\", \"(\"): \" \", (\")\", \")\"): \">\", (\")\", \"#\"): \">\",\n (\"#\", \"+\"): \"<\", (\"#\", \"-\"): \"<\", (\"#\", \"*\"): \"<\", (\"#\", \"/\"): \"<\",\n (\"#\", \"(\"): \"<\", (\"#\", \")\"): \" \", (\"#\", \"#\"): \"=\",\n }\n\n num_stack = SqStack() # 操作数栈\n op_stack = SqStack() # 操作符栈\n op_stack.push(expr.pop(0)) # 操作栈底置入“#”\n\n # 表达式未结束或符栈非空时执行循环\n ch = expr.pop(0)\n while ch != \"#\" or op_stack.get_top() != \"#\":\n\n # 表达式字符为数字则直接入数栈\n if ch in string.digits:\n num_stack.push(ch)\n ch = expr.pop(0)\n\n # 表达式字符为符\n else:\n # 取符栈顶元素与表达式符比较\n precede = precede_map.get((op_stack.get_top(), ch))\n\n # 栈顶符比表达式符优先级高\n # 弹出栈顶符、弹出数栈顶两个数字,计算结果后置入数栈\n if precede == \">\":\n op = op_stack.pop()\n num2 = num_stack.pop()\n num1 = num_stack.pop()\n res = str(eval(\"{0}{1}{2}\".format(num1, op, num2)))\n num_stack.push(res)\n\n # 栈顶符比表达式符优先级低\n # 表达式符入栈\n elif precede == \"<\":\n op_stack.push(ch)\n ch = expr.pop(0)\n\n # 栈顶符与表达式符优先级相等:左右括号相遇,弹出\n elif precede == \"=\":\n op_stack.pop()\n ch = expr.pop()\n\n else:\n return False\n\n # 数栈顶即为计算结果\n return num_stack.pop()\n\n\ndef eval_expr2(expr):\n \"\"\" 使用逆波兰式计算表达式 \"\"\"\n\n operators = list(\"+-*/()\")\n priority = {\"(\": 1, \"+\": 3, \"-\": 3, \"*\": 5, \"/\": 5, \"%\": 5}\n\n \"\"\" tokenizer:切分中序表达式为字符列表 \"\"\"\n expr = expr.strip()\n index, length = 0, len(expr)\n tokens = []\n\n while index < length:\n\n # 处理操作符\n if expr[index] in operators:\n tokens.append(expr[index])\n index += 1\n\n # 处理整数\n elif expr[index].isdigit():\n val = \"\"\n while index < length and expr[index].isdigit():\n val += expr[index]\n index += 1\n tokens.append(val)\n\n # 处理小数\n elif expr[index] == \".\":\n val = tokens.pop() + expr[index]\n index += 1\n\n while expr[index] not in operators:\n val += expr[index]\n index += 1\n\n tokens.append(val)\n\n # 处理空格(多个空格只保留一个)\n elif expr[index] == \" \":\n tokens.append(\" \")\n while index < length and expr[index] == \" \":\n index += 1\n\n else:\n break\n\n # TODO 处理负指数\n # j = index + 1\n #\n # while j < len(expr) and not expr[j].isspace() and expr[j] not in operators:\n # if (expr[j] == \"e\" or expr[j] == \"E\") and j + 1 < len(expr) and expr[j+1] == \"-\":\n # j += 1\n # j += 1\n #\n # res.append(expr[index:j])\n # index = j\n\n \"\"\" 转换中序表达式为后序表达式 \"\"\"\n op_stack = SqStack()\n suffix_expr = \"\"\n\n for token in tokens:\n # print(op_stack.values)\n\n # 当前字符数字直接加入到结果串\n if token not in operators:\n suffix_expr += \" \" + token\n\n # 左括号无视优先级直���入栈\n elif op_stack.is_empty or token == \"(\":\n op_stack.push(token)\n\n # 当前字符为右括号,把栈中、括号内的所有符号依次加入到结果串\n elif token == \")\":\n while not op_stack.is_empty and op_stack.get_top() != \"(\":\n suffix_expr += \" \" + op_stack.pop()\n\n # 找不到左括号\n if op_stack.is_empty:\n return False\n\n op_stack.pop()\n\n # 当前字符为+、-、*、/\n else:\n # 栈非空且栈顶元素的符号优先级高于等于当前字符,加入到结果串\n while not op_stack.is_empty \\\n and priority[op_stack.get_top()] >= priority[token]:\n\n suffix_expr += \" \" + op_stack.pop()\n\n # 直到栈为空或栈顶元素优先级低于当前字符,把当前字符入栈\n op_stack.push(token)\n\n # 取栈中剩余的元素加入到结果串\n while not op_stack.is_empty:\n\n if op_stack.get_top() == \"(\":\n return False\n\n suffix_expr += \" \" + op_stack.pop()\n\n \"\"\" 计算后序表达式 \"\"\"\n stack = SqStack()\n for char in suffix_expr.strip().split(\" \"):\n\n if char in operators:\n right, left = float(stack.pop()), float(stack.pop())\n if char == \"+\":\n stack.push(left + right)\n elif char == \"-\":\n stack.push(left - right)\n elif char == \"*\":\n stack.push(left * right)\n elif char == \"/\":\n stack.push(left / right)\n elif char == \"%\":\n stack.push(left % right)\n else:\n return False\n\n if char.isdigit():\n stack.push(char)\n\n return round(stack.pop(), 2)\n\n\n\"\"\" 栈与递归:任何一个递归函数都可以通过引入一个栈来保存中间信息、转化为非递归形式 \"\"\"\n\n\ndef hanoi(n, a=\"A\", b=\"B\", c=\"C\"):\n \"\"\" 汉诺塔 \"\"\"\n\n def move(a_, n_, b_):\n print(a_ + \" \" + str(n_) + \" -> \", b_)\n\n if n == 1:\n move(a, n, c)\n else:\n hanoi(n-1, a, c, b)\n move(a, n, c)\n hanoi(n-1, b, a, c)\n\n\ndef norec_fact(n):\n \"\"\" 阶乘函数的非递归形式 \"\"\"\n\n res = 1\n stack = SqStack()\n while n > 0:\n stack.push(n)\n n -= 1\n while not stack.is_empty:\n res *= stack.pop()\n\n return res\n\n\ndef knap_rec(weight, wlist, n):\n \"\"\" \n 背包问题:\n 一个背包可以放入重量为weight的物品,现有n件物品,重量分别为w0, w1, ...wn-1\n 问题是否能从中取出若干件物品,其重量之和正好等于weight\n \"\"\"\n\n # 当物品数量减为0的同时物品总重量也被减为0,表示有解\n if weight == 0:\n return True\n\n if weight < 0:\n return False\n\n if weight > 0 and n < 1:\n return False\n\n # 不计算最后一件物品、总重量减去最后一件物品的重量时有解,即加入最后一件物品时有解\n if knap_rec(weight - wlist[n-1], wlist, n-1):\n print(\"Item \" + str(n) + \":\", wlist[n-1])\n return True\n else:\n return False\n\ndef a_3_1_1(push_order, pop_order):\n # stack_order\n # print(a_3_1_1([1, 2, 3, 4, 5], [2, 3, 5, 4, 1]))\n\n stack = SqStack()\n\n p_pop = 0\n\n for push_v in push_order:\n\n while stack.get_top() == pop_order[p_pop]:\n stack.pop()\n p_pop += 1\n if push_v != pop_order[p_pop]:\n stack.push(push_v)\n else:\n p_pop += 1\n\n while not stack.is_empty:\n if stack.pop() != pop_order[p_pop]:\n return False\n p_pop += 1\n\n return True\n\n\ndef a_3_2_2(string):\n\n stack = SqStack()\n length = len(string)\n\n for i in range(length // 2):\n stack.push(string[i])\n\n for i in range(length // 2 + length % 2, length):\n if stack.pop() != string[i]:\n return False\n\n return True\n\n\ndef a_3_2_3(list_a):\n\n stack = SqStack()\n\n for elem in list_a:\n if elem != -1:\n if stack.is_full:\n print(\"Full!\")\n else:\n stack.push(elem)\n else:\n if stack.is_empty:\n print(\"Empty!\")\n else:\n print(stack.pop())\n\n\ndef a_3_2_4(expr):\n\n num_stack = SqStack()\n digit = \"\"\n for char in expr:\n if char == \"$\":\n break\n if char in string.digits + [\".\"]:\n digit += char\n else:\n s, e = 0, 0\n\n # 小數、整數部分分別處理\n # 如果不存在小數部分,則補上\".0\"\n digit += \".0\" if \".\" not in digit else \"\"\n for i in range(digit.find(\".\") - 1, -1, -1):\n s += int(digit[i]) * 10 ** e\n e += 1\n if \".\" in digit:\n for i in range(len(digit) - 1, digit.find(\".\"), -1):\n s += int(digit[i]) * 10 ** -e\n e -= 1\n\n num_stack.push(s)\n digit = \"\"\n\n if char in [\"+\", \"-\", \"*\", \"/\"]:\n num_2 = num_stack.pop()\n num_1 = num_stack.pop()\n if char == \"+\":\n num_stack.push(num_1 + num_2)\n if char == \"-\":\n num_stack.push(num_1 - num_2)\n if char == \"*\":\n num_stack.push(num_1 * num_2)\n if char == \"/\":\n num_stack.push(num_1 / num_2)\n return num_stack.pop()\n\n\ndef a_3_2_5(list_a):\n\n count = 0\n\n for i in list_a:\n\n if i == \"I\":\n count += 1\n else:\n count -= 1\n\n if count < 0:\n return False\n\n return count == 0\n\n\ndef a_3_2_6():\n\n class LNode(object):\n\n def __init__(self, elem=None, next=None):\n self.elem = elem\n self.next = next\n\n class Queue(object):\n\n def __init__(self, elem=None):\n self.rear = LNode()\n self.rear.next = self.rear\n\n if elem:\n p = first = LNode(elem[0])\n for i in elem[1:]:\n p.next = LNode(i, p.next)\n p = p.next\n self.rear.next = first\n p.next = self.rear\n\n @property\n def is_empty(self):\n return self.rear.next == self.rear\n\n def get(self):\n if self.is_empty:\n return False\n node = self.rear.next\n\n if self.rear.next == self.rear:\n self.rear = None\n else:\n self.rear.next = self.rear.next.next\n\n return node\n\n def put(self, elem):\n self.rear.next = LNode(None, self.rear.next)\n self.rear.elem = elem\n self.rear = self.rear.next\n\n def empty(self):\n self.rear.next = self.rear\n\n\n def print_all(self):\n p = self.rear.next\n\n while p.elem:\n print(p.elem)\n p = p.next\n\n list_1 = Queue([1, 2, 3, 4, 5])\n list_1.put(6)\n list_1.put(7)\n list_1.empty()\n\n list_1.print_all()\n\n\ndef a_3_2_7():\n\n class Queue(object):\n\n def __init__(self):\n self.queue_size = MAXSIZE\n self.tag = self.front = self.rear = 0\n self.elem = [None for _ in range(self.queue_size)]\n\n @property\n def is_empty(self):\n return self.front == self.rear and self.tag == 0\n\n @property\n def is_full(self):\n return self.front == self.rear and self.tag == 1\n\n def put(self, elem):\n if self.is_full:\n return False\n self.rear = (self.rear + 1) % self.queue_size\n self.elem[self.rear] = elem\n if self.tag == 0:\n self.tag = 1\n\n def get(self):\n if self.is_empty:\n return False\n\n self.front = (self.front + 1) % self.queue_size\n elem = self.elem[self.front]\n if self.tag == 1:\n self.tag = 0\n return elem\n\n\ndef a_3_2_8():\n\n class Deque(object):\n\n def __init__(self):\n self.queue_size = MAXSIZE\n self.elem = [None for _ in range(self.queue_size)]\n self.front = self.rear = 0\n\n @property\n def is_empty(self):\n return self.rear == self.front\n\n @property\n def is_full(self):\n return (self.rear + 1) % self.queue_size == self.front\n\n def delqueue(self):\n if self.is_empty:\n return False\n self.rear = (self.rear - 1 + self.queue_size) % self.queue_size\n return self.elem[(self.rear + 1 + self.queue_size) % self.queue_size]\n\n def enqueue(self, elem):\n if self.is_full:\n return False\n\n self.elem[self.front] = elem\n self.front = (self.front - 1 + self.queue_size) % self.queue_size\n\n\ndef a_3_2_9():\n\n def Ackerman(m, n):\n\n if m == 0:\n return n + 1\n\n if m != 0 and n == 0:\n return Ackerman(m - 1, 1)\n\n if m != 0 and n != 0:\n return Ackerman(m - 1, Ackerman(m, n - 1))\n\n def AckermanStack(m, n):\n\n res = [[None for _ in range(n)] for _ in range(m)]\n\n for i in range(n):\n res[0][i] = i\n\n for i in range(1, m):\n res[i][0] = res[i - 1][1]\n\n for i in range(1, m):\n for j in range(1, n):\n res[i][j] = res[i - 1][res[i][j - 1]]\n\n return res[m][n]\n\n\ndef a_3_2_10(list_a):\n\n def max_num(p):\n\n if not p.next:\n return p.elem\n\n max = max_num(p.next)\n return p.elem if p.elem > max else max\n\n def num_count_1(p):\n\n if not p:\n return 0\n return num_count_1(p.next) + 1\n\n def num_count_2(p, count):\n\n if not p:\n return count\n\n return num_count_2(p.next, count + 1)\n\n def avg(p, n, s):\n\n if not p:\n return s / n\n\n return avg(p.next, n + 1, s + p.elem)\n\n print(avg(list_a.head.next, 0, 0))\n\n\nif __name__ == \"__main__\":\n\n # print(coversion(6, 2))\n # print(maching(\"({]})\"))\n # print(evaluate_expression(\"#3*(5-2)#\"))\n # hanoi(3)\n\n # s1 = SqStack([1, 2, 3, 4, 5])\n # v1 = s1.pop()\n # print(v1)\n\n # print(eval_expr2(\"(3-5)*(6+17*4)/3\"))\n\n # a_3_2_4(\"234 34+2*$\")\n\n # print(a_3_2_5(\"IIIOOIOO\"))\n\n # a_3_2_6()\n\n a_3_2_10(LinkList([1, 5, 2, 7, 3]))\n\n print(eval_expr2(\"(3-5)*(6+17*4)/3\"))\n\n # pass\n\"\"\"\nAnswer:\n\n1-1 C 1-2 C 1-3 D 1-4 A 1-5 A\n1-6 D 1-7 A 1-8 B 1-9 D 1-10 D\n1-11 D 1-12 D 1-13 B 1-14 C 1-15 B\n\n\"\"\"\n # s1 = SqStack([1, 2, 3, 4, 5])\n # v1 = s1.pop()\n # print(v1)\n\n\n\n\n","sub_path":"data_structure/Stack.py","file_name":"Stack.py","file_ext":"py","file_size_in_byte":19758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"252798331","text":"#!/usr/bin/env python\n\nfrom rospy_message_converter import message_converter\nimport rospy\nimport smach\nimport threading\nfrom std_msgs.msg import String\nfrom dialogflow_ros.msg import *\n\nclass WaitForMsgState(smach.State):\n \"\"\"\n Waits for a message and routes the contents to next State.\n \"\"\"\n\n def __init__(self, topic, msg_type, msg_cb=None, output_keys=[], input_keys=[], latch=False, timeout=None,\n state_name=None):\n smach.State.__init__(self, outcomes=['succeeded', 'aborted'], output_keys=output_keys, input_keys=input_keys)\n self.latch = latch\n self.timeout = timeout\n self.mutex = threading.Lock()\n self.msg = None\n self.message_callback = msg_cb\n self.subscriber = rospy.Subscriber(topic, msg_type, self._callback, queue_size=1)\n self.state_name = state_name\n\n def _callback(self, msg):\n self.mutex.acquire()\n self.msg = msg\n self.mutex.release()\n\n def wait_for_msg(self):\n rospy.loginfo(self.state_name + ' is waiting for message...')\n if self.timeout is not None:\n timeout_time = rospy.Time.now() + rospy.Duration.from_sec(self.timeout)\n while self.timeout is None or rospy.Time.now() < timeout_time:\n self.mutex.acquire()\n if self.msg is not None:\n rospy.loginfo(self.state_name + ' got message.')\n message = self.msg\n\n if not self.latch:\n self.msg = None\n\n self.mutex.release()\n return message\n self.mutex.release()\n\n #TODO: Do we need a preempted out?\n\n # if self.preempt_requested():\n # self.service_preempt()\n # rospy.loginfo('waitForMsg is preempted!')\n # return 'preempted'\n\n rospy.sleep(.1) # TODO: InterruptException? Discuss with Anas\n\n rospy.loginfo(self.state_name + ' experienced a Timeout on waiting for message.')\n return None\n\n def execute(self, ud):\n msg = self.wait_for_msg()\n if msg is not None:\n if msg == 'preempted':\n return 'preempted'\n if self.message_callback is not None:\n ud.publish_msg = self.msg\n cb_result = self.message_callback(msg, ud)\n if cb_result is not None:\n if cb_result:\n return 'succeeded'\n else:\n return 'aborted'\n return 'succeeded'\n else:\n return 'aborted'\n\n\nclass PublishMsgState(smach.State):\n def __init__(self, publisher_name, node_name=None, message_type=String, output_keys=[], input_keys=[],\n state_name=None):\n smach.State.__init__(self, outcomes=['succeeded', 'aborted'], output_keys=output_keys, input_keys=input_keys)\n self.pub = rospy.Publisher(publisher_name, message_type, queue_size=1)\n if node_name is not None:\n rospy.init_node(node_name, anonymous=True)\n self.state_name = state_name\n\n def execute(self, ud):\n rospy.loginfo(\"Publishing \" + self.state_name)\n self.pub.publish(ud.publish_msg)\n return 'succeeded'\n\n\ndef dialogflowresult_format(msg, ud):\n ud.action = msg.action\n ud.parameters = msg.parameters\n ud.publish_msg = msg.action\n rospy.loginfo(ud.action)\n return True\n\n\ndef main():\n rospy.init_node('integration')\n\n sm_top = smach.StateMachine(outcomes=['success'])\n sm_top.userdata.parameters = []\n sm_top.userdata.action = \"\"\n sm_top.userdata.pcl = \"\"\n sm_top.userdata.xyz = \"\"\n sm_top.userdata.publish_msg = {}\n\n with sm_top:\n\n smach.StateMachine.add('NLPsub', WaitForMsgState('/dialogflow_client/results', DialogflowResult,\n msg_cb=dialogflowresult_format, state_name=\"NLPsub\",\n output_keys=['publish_msg', 'action', 'parameters'],\n input_keys=['publish_msg', 'action', 'parameters']),\n transitions={'succeeded': 'NLPpub',\n 'aborted': 'NLPsub'})\n\n smach.StateMachine.add('NLPpub', PublishMsgState('/nlp', state_name='NLPpub',\n output_keys=['publish_msg', 'action', 'parameters'],\n input_keys=['publish_msg', 'action', 'parameters']),\n transitions={'succeeded': 'AMBERsub',\n 'aborted': 'NLPpub'})\n smach.StateMachine.add('AMBERsub', WaitForMsgState('/nlp', String, state_name=\"AMBERsub\",\n output_keys=['publish_msg', 'action', 'parameters'],\n input_keys=['publish_msg', 'action', 'parameters']),\n transitions={'succeeded': 'AMBERpub',\n 'aborted': 'AMBERsub'})\n smach.StateMachine.add('AMBERpub', PublishMsgState('/amber', state_name='AMBERpub',\n output_keys=['publish_msg', 'action', 'parameters'],\n input_keys=['publish_msg', 'action', 'parameters']),\n transitions={'succeeded': 'JAKEsub',\n 'aborted': 'AMBERsub'})\n smach.StateMachine.add('JAKEsub', WaitForMsgState('/amber', String, state_name='JAKEsub',\n output_keys=['publish_msg', 'action', 'parameters'],\n input_keys=['publish_msg', 'action', 'parameters']),\n transitions={'succeeded': 'JAKEpub',\n 'aborted': 'JAKEsub'})\n smach.StateMachine.add('JAKEpub', PublishMsgState('/jake', state_name='JAKEpub',\n output_keys=['publish_msg', 'action', 'parameters'],\n input_keys=['publish_msg', 'action', 'parameters']),\n transitions={'succeeded': 'ANASpub',\n 'aborted': 'JAKEpub'})\n smach.StateMachine.add('ANASsub', WaitForMsgState('/jake', String, state_name='ANASsub',\n output_keys=['publish_msg', 'action', 'parameters'],\n input_keys=['publish_msg', 'action', 'parameters']),\n transitions={'succeeded': 'ANASpub',\n 'aborted': 'ANASsub'})\n smach.StateMachine.add('ANASpub', PublishMsgState('/anas', state_name='ANASpub',\n output_keys=['publish_msg', 'action', 'parameters'],\n input_keys=['publish_msg', 'action', 'parameters']),\n transitions={'succeeded': 'success',\n 'aborted': 'ANASpub'})\n\n\n\n\n\n\n # Execute SMACH plan\n outcome = sm_top.execute()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"cap_integration/scripts/state_machines.py","file_name":"state_machines.py","file_ext":"py","file_size_in_byte":7529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"129760388","text":"def value(r):\r\n if (r=='I'):\r\n return 1\r\n if(r=='V'):\r\n return 5\r\n if(r=='X'):\r\n return 10\r\n if(r=='C'):\r\n return 100\r\n if(r=='L'):\r\n return 50\r\n if(r=='D'):\r\n return 500\r\n if(r=='M'):\r\n return 1000\r\n\r\ndef romanToDecimal(str):\r\n res=0\r\n i=0\r\n while(i= s2):\r\n res= res+s1\r\n i=i+1\r\n else:\r\n res = res +s2 -s1\r\n i=i+2\r\n else:\r\n res = res+s1\r\n i=i+1\r\n return res\r\nif __name__=='__main__':\r\n input_string = input()\r\n print(romanToDecimal(input_string))","sub_path":"venv/LeetCode/RomanToDecimal.py","file_name":"RomanToDecimal.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"563802420","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\ndef parsedata(data):\n return float(data[6:14].replace(' ', ''))\n\n# def run(nodeinfo, logger):\n# logger.info('hello, this is a scales mod')\n# # opened serial port and test\n# try:\n# ser = serial.Serial(nodeinfo['devname'],nodeinfo['baudrate'])\n# # flush input\n# ser.flushInput()\n# ser.close()\n# # ingore bad line\n# #ser.readline()\n# except:\n# logger.exception('failed to open or init serial port')\n# exit(1)\n# try:\n# timeinterval = nodeinfo['interval']\n# srvaddr = nodeinfo['srvaddr']\n# scalesid = nodeinfo['scalesid']\n# except:\n# logger.exception('missing config para')\n# exit(1)\n# num = 0\n# while True:\n# num = num + 1\n# #listen and grab data\n# try:\n# time.sleep(timeinterval)\n# ser = serial.Serial(nodeinfo['devname'],nodeinfo['baudrate'])\n# #flush input\n# ser.flushInput()\n# #ingore bad line\n# data = ser.readline()\n# #re_read\n# data = ser.readline()\n# ser.close()\n# data = data.decode('utf-8')\n# except Exception as e:\n# logger.exception('failed to read data from serial port')\n# exit(1)\n# logger.info('#{} data received'.format(num))\n# #parse data\n# try:\n# weight = parsedata(data)\n# except Exception as e:\n# logger.exception('failed to parse data')\n# continue\n# #fork a new thread to post data\n# try:\n# pid = os.fork()\n# except:\n# logger.exception('failed to first fork')\n# if pid == 0:\n# # the child process/the second parent process\n# # do #2 fork\n# try:\n# pid = os.fork()\n# except:\n# logger.exception('failed to do #2 fork')\n# exit(1)#no one cares exit code here\n# if pid == 0:\n# #the second child process\n# try:\n# postdata(srvaddr, scalesid, weight)\n# except:\n# logger.exception('#{} failed to post'.format(num))\n# exit(1)\n# logger.info('#{} data posted'.format(num))\n# exit(0)\n# # the second parent process\n# exit(0)\n# # the parent process\n# ## wait for the second parent process exit\n# os.wait()\n# #end while\n# #shouldn't come here if everything is ok\n# logger.error('unexcept error: fun run in mod scales should not return')\n# return 0\n\n\nimport logging\nimport os\nimport time\nfrom postdata import postdata\nimport serial\n\n\ndef run(nodeinfo, logger, cnt):\n logger.info('hello, this is a scales mod')\n try:\n devname = nodeinfo['devname']\n baudrate = nodeinfo['baudrate']\n srvaddr = nodeinfo['srvaddr']\n scalesid = nodeinfo['scalesid']\n except:\n logger.exception('not enough config parameters')\n exit(1)\n\n # listen and grab data\n try:\n ser = serial.Serial(devname, baudrate)\n # flush input\n ser.flushInput()\n # ingore bad line\n data = ser.readline()\n # re_read\n data = ser.readline()\n ser.close()\n except:\n logger.exception('failed to open or read from serial port')\n exit(1)\n logger.info('#{} data received'.format(cnt))\n\n # parse data\n try:\n data = data.decode('utf-8')\n weight = parsedata(data)\n except Exception as e:\n logger.exception('failed to decode or parse data')\n exit(1)\n # fork a new thread to post data\n try:\n result = postdata(srvaddr, scalesid, weight)\n except:\n logger.exception('#{} failed to post'.format(cnt))\n exit(1)\n logger.info('#{} data posted, result: {}'.format(cnt, str(result)))\n exit(0)\n return 0\n\nimport os\nimport os.path\n\n\ndef fix(nodeinfo, logger, exitcode):\n logger.info('this is func fix of scales mod')\n # get config\n try:\n devname = nodeinfo['devname']\n baudrate = nodeinfo['baudrate']\n srvaddr = nodeinfo['srvaddr']\n scalesid = nodeinfo['scalesid']\n except:\n logger.exception('not enough config parameters')\n exit(1)\n if not os.path.exists(devname):\n logger.error('not such device, failed to fix')\n exit(1)\n exit(0)\n return 0\n\nimport logging\nimport sys\nif __name__ == '__main__':\n logger = logging.getLogger(__name__)\n ch = logging.StreamHandler()\n logger.addHandler(ch)\n logger.setLevel(logging.INFO)\n logger.info('this is test for mod_scales')\n cnt = 9526\n config = {\"devname\": sys.argv[1],\n \"baudrate\": 9600,\n \"scalesid\": 2,\n \"srvaddr\": \"http://211.83.111.245/biaoben/receive.php\"}\n print('try to run it')\n try:\n run(config, logger, cnt)\n except:\n logger.exception('failed to run')\n print('try to fix it')\n fix(config, logger, 1)\n print('finished!')\n","sub_path":"newhub/mods/mod_scales.py","file_name":"mod_scales.py","file_ext":"py","file_size_in_byte":5049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"481574739","text":"# Given a list of numbers and a number k, return whether any two numbers from the list add up to k\n# Example: Given and k of 17, return true since 10 + 7 is 17\n\ndef pairSumToK(nums, k):\n\tcompliments = set()\n\tfor num in nums:\n\t\tif num in compliments:\n\t\t\treturn True\n\t\tcompliments.add(k - num)\n\treturn False\n\nex_nums_true = [10, 15, 3, 7]\nex_nums_false = [10, 15, 3, 8]\nex_k = 17\n\nprint(pairSumToK(ex_nums_true, ex_k))\nprint(pairSumToK(ex_nums_false, ex_k))\n","sub_path":"1_pairSumToK.py","file_name":"1_pairSumToK.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"345194982","text":"mod = 1e9+7\n\nn1 = {2:2,3:1,5:4,23:1}\nn2 = {2:1,5:1,7:2}\n\ndef comb(n1,n2):\n n3 = {}\n for key in n2:\n if key in n1: n3[key] = n2[key]+n1[key]\n else: n3[key] = n2[key]\n for key in n1:\n if key not in n2: n3[key] = n1[key]\n\n return n3\n\ndef nf(n):\n ans = 1\n for key in n:\n ans*=(n[key]+1)\n ans%=mod\n return int(ans)\n\nprint(comb(n1,n2))\nprint(nf(comb(n1, n2)))\n","sub_path":"AprLong/testfctre.py","file_name":"testfctre.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"315201204","text":"#\n# 티켓 객체에 대한 코드\n#\n# @author Seongeun Yu (s3ich4n@gmail.com)\n# @date 2021/06/03 23:55 created.\n#\n\n\nfrom typing import Optional\n\n\nclass Ticket:\n \"\"\" 공연을 관람하려는 사람이 소지해야하는 티켓에 대한 객체\n\n \"\"\"\n def __init__(\n self,\n fee: Optional[int] = None\n ):\n self._fee = fee\n\n @property\n def fee(self):\n return self._fee\n","sub_path":"pt01_object,design/cpt01/ticket.py","file_name":"ticket.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"40541962","text":"def D(a,b,c):\r\n\treturn b ** 2 - 4 * a * c\r\ndef check(x):\r\n\ttry:\r\n\t\tx=float(x)\r\n\t\tglobal i\r\n\t\ti+=1\r\n\t\treturn x\r\n\texcept:\r\n\t\tprint(\" Неверный ввод или вызов помощи. Программа предназначена для решения уравнений вида: ax^2±bx±c=0. \")\r\n\t\tprint(\" Для получения корней уравнения, введите поочередно коэфиценты a,b,c. \")\r\n\t\tprint(\" Коэфиценты необходиы вводить как вещественные числа:\\n Верно: 5; 1; -1; -3.14; 2.16\\n Неверно: 6.23.54; --3; two;\")\r\nfrom math import sqrt\r\nprint(\" Welcom to the programm!\\n Это программа для решения квадратных уравнений. \")\r\nprint(\" Введите коэфиценты уравнения.\\n Для помощи в любом месте введите help \")\r\nwhile True:\r\n\ti = 0\r\n\twhile i<1: value = check(input(\" Press coefficient a: \"));\r\n\ti = 0\r\n\twhile i<1: data = check(input(\" Press coefficient b: \"));\r\n\ti = 0\r\n\twhile i<1: date = check(input(\" Press coefficient c: \"));\r\n\tdate = check( D(value,data,date) )\r\n\tif date == 0:\r\n\t\tx = -data / (2 * value )\r\n\t\tprint(\"Root your equation: \"+str(x))\r\n\telif date > 0:\r\n\t x1 = ( -data + sqrt(date) ) / ( 2 * value )\r\n\t x2 = ( -data - sqrt(date) ) / ( 2 * value )\r\n\t print(\" Roots your equation: \"+str(x1)+\", \"+str(x2))\r\n\telse:\r\n\t print(\"Корней нет.\")\r\n\tinput(\" Press any to continue \")","sub_path":"Quadratic equationInfiniti.py","file_name":"Quadratic equationInfiniti.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"377832966","text":"import os\nimport time\nfrom subprocess import Popen as execute\nfrom twisted.internet.defer import Deferred\n\n#---------------------------------------------------------------------------# \n# configure the client logging\n#---------------------------------------------------------------------------# \nimport logging\nlog = logging.getLogger(__name__)\n\nclass Runner(object):\n '''\n This is the base runner class for all the integration tests\n '''\n\n def initialize(self, service):\n ''' Initializes the test environment '''\n self.fnull = open(os.devnull, 'w')\n self.server = execute(service, stdout=self.fnull, stderr=self.fnull)\n log.debug(\"%s service started: %s\", service, self.server.pid)\n time.sleep(0.2)\n\n def shutdown(self):\n ''' Cleans up the test environment '''\n self.server.kill()\n self.fnull.close()\n log.debug(\"service stopped\")\n\n def testReadWriteCoil(self):\n rq = self.client.write_coil(1, True)\n rr = self.client.read_coils(1,1)\n self.__validate(rq, lambda r: r.function_code < 0x80)\n self.__validate(rr, lambda r: r.bits[0] == True)\n \n def testReadWriteCoils(self):\n rq = self.client.write_coils(1, [True]*8)\n rr = self.client.read_coils(1,8)\n self.__validate(rq, lambda r: r.function_code < 0x80)\n self.__validate(rr, lambda r: r.bits == [True]*8)\n \n def testReadWriteDiscreteRegisters(self):\n rq = self.client.write_coils(1, [False]*8)\n rr = self.client.read_discrete_inputs(1,8)\n self.__validate(rq, lambda r: r.function_code < 0x80)\n self.__validate(rr, lambda r: r.bits == [False]*8)\n \n def testReadWriteHoldingRegisters(self):\n rq = self.client.write_register(1, 10)\n rr = self.client.read_holding_registers(1,1)\n self.__validate(rq, lambda r: r.function_code < 0x80)\n self.__validate(rr, lambda r: r.registers[0] == 10)\n \n def testReadWriteInputRegisters(self):\n rq = self.client.write_registers(1, [10]*8)\n rr = self.client.read_input_registers(1,8)\n self.__validate(rq, lambda r: r.function_code < 0x80)\n self.__validate(rr, lambda r: r.registers == [10]*8)\n \n def testReadWriteRegistersTogether(self):\n arguments = {\n 'read_address': 1,\n 'read_count': 8,\n 'write_address': 1,\n 'write_registers': [20]*8,\n }\n rq = self.client.readwrite_registers(**arguments)\n rr = self.client.read_input_registers(1,8)\n self.__validate(rq, lambda r: r.function_code < 0x80)\n self.__validate(rr, lambda r: r.registers == [20]*8)\n\n def __validate(self, result, test):\n ''' Validate the result whether it is a result or a deferred.\n\n :param result: The result to __validate\n :param callback: The test to __validate\n '''\n if isinstance(result, Deferred):\n deferred.callback(lambda : self.assertTrue(test(result)))\n deferred.errback(lambda _: self.assertTrue(False))\n else: self.assertTrue(test(result))\n\n","sub_path":"examples/functional/base_runner.py","file_name":"base_runner.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"19291771","text":"import os\nimport json\nimport base64\nfrom flask import Flask, request, jsonify\nfrom firebase_admin import credentials, firestore, initialize_app\nfrom munch import Munch\n\n# Initialize Flask app\napp = Flask(__name__)\n\n# Initialize Firestore DB\ncred = credentials.Certificate('blazorapp1-50c53-firebase-adminsdk-ucwtd-2117b9c719.json')\ndefault_app = initialize_app(cred)\ndb = firestore.client()\n\n# Utility method for getting a document\ndef document(collName, docName):\n return db.collection(collName).document(docName)\n\n@app.route('/')\ndef index():\n return \"Audio Flashcards Ptyhon API\"\n\n# Get the user data structure\n@app.route('/user/', methods=['GET'])\ndef user(uid):\n try:\n doc = document('users', uid).get()\n if doc and doc.exists:\n return doc.to_dict(), 200\n else:\n return '', 200\n except Exception as e:\n return f\"An Error occurred: {e}\"\n\n# Update or create a user\n@app.route('/saveuser/', methods=['POST'])\ndef saveUser(uid):\n try:\n document('users', uid).set(json.loads(request.data))\n return \"ok\"\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n# For playback, get the list of active recordings (active means both prompt and\n# response have been recorded)\n@app.route('/currentpairs//', methods=['GET'])\ndef currentPairs(uid, currentTopicId):\n try:\n query = db.collection('prpairs')\\\n .where('uid', '==', uid)\\\n .where('topicId', '==', int(currentTopicId))\\\n .where('isActive', '==', True)\\\n .order_by('nextDate')\\\n .limit(20)\n docs = query.get()\n list = []\n if docs:\n for doc in docs:\n list.append(doc.to_dict())\n return json.dumps(list) , 200\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n# Get a recording\n@app.route('/blob//', methods=['GET'])\ndef blob(uid, promptid):\n try:\n key = f'{uid}_{promptid}'\n doc = document('blobs', key).get()\n if doc and doc.exists:\n return doc.to_dict(), 200\n else:\n return 'error', 200\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n# Save a recording\n@app.route('/saveblob//', methods=['POST'])\ndef saveblob(uid, promptid):\n try:\n blob = json.loads(request.data)\n key = f'{uid}_{promptid}'\n document('blobs', key).set(blob)\n return \"ok\"\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n# Delete a recording\n@app.route('/deleteblob//', methods=['DELETE'])\ndef deleteBlob(uid, promptid):\n try:\n key = f'{uid}_{promptid}'\n document('blobs', key).delete()\n return \"ok\"\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n# Get the user's topic structure\n@app.route('/gettopics/', methods=['GET'])\ndef getTopics(uid):\n try:\n docs = db.collection('topics').where('uid', '==', uid).get()\n list = []\n if docs:\n for doc in docs:\n list.append(doc.to_dict())\n return json.dumps(list) , 200\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n# Save the user's topic structure\n@app.route('/savetopic//', methods=['POST'])\ndef saveTopic(uid, topicid):\n try:\n data = json.loads(request.data)\n key = f'{uid}_{topicid}'\n document('topics', key).set(data)\n return \"ok\"\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n# Get the prompt-reponse pairs for a deck \n@app.route('/getpairs//', methods=['GET'])\ndef getPairs(uid, deckId):\n try:\n query = db.collection('prpairs')\\\n .where('uid', '==', uid)\\\n .where('deckId', '==', int(deckId))\\\n .order_by('order')\n docs = query.get()\n list = []\n if docs:\n for doc in docs:\n list.append(doc.to_dict())\n return json.dumps(list) , 200\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n# Save a prompt-response pair\n@app.route('/savepromptpair//', methods=['POST'])\ndef savepromptpair(uid, pairid):\n try:\n data = json.loads(request.data)\n key = f'{uid}_{pairid}'\n document('prpairs', key).set(data)\n return \"ok\"\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n# Delete a prompt-response pair\n@app.route('/deletepair//', methods=['DELETE'])\ndef deletePair(uid, pairid):\n try:\n key = f'{uid}_{pairid}'\n document('prpairs', key).delete()\n return \"ok\"\n except Exception as e:\n print(\"An error occurred: \", e)\n return f\"An error occurred: {e}\"\n\n\nif __name__ == \"__main__\":\n app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"326117413","text":"\nimport argparse\nimport sys\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='A Hello World program with arguments.')\n\n parser.add_argument('-m', '--message', type=str, default=\"Hello \",\n help='message to be written')\n\n parser.add_argument('-o', '--outfile', nargs='?', type=argparse.FileType('w'),\n default=sys.stdout,\n help=\"output file\")\n\n parser.add_argument('-c', '--capitals', action=\"store_true\",\n help='write capitals')\n\n parser.add_argument('name', type=str, nargs='+',\n help='name(s) of the user')\n\n args = parser.parse_args()\n\n message = args.message\n if args.name:\n message = message + ' '.join(args.name)\n if args.capitals: \n message = message.upper()\n args.outfile.write(message + '\\n')\n","sub_path":"structure/argparse/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"63829620","text":"from characters.base import Character\n\nclass Medic(Character):\n def __init__(self): \n self.name = \"Medic\"\n self.health = 10\n self.power = 3\n self.prize = 5\n \n def receive_damage(self, points):\n super(Medic, self).receive_damage(points)\n h_boost = random.random() > 0.8\n if h_boost:\n self.health += 2\n print(\"Medic got health boost and gained 2 health!\")","sub_path":"characters/medic.py","file_name":"medic.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"184653872","text":"'''num = [2,5,6,9]\nnum[2] = 3\nnum.append(70)\nnum.sort(reverse=True)\nnum.insert(2, 2)\nnum.pop(1)\nif 5 in num:\n num.remove(5)\nelse:\n print('não há número 4 ')\nprint(num)\nprint(f'Essa lista tem {len(num)} elementos')'''\n\n'''valores = []\nvalores.append(5)\nvalores.append(10)\nvalores.append(4)\nfor c,v in enumerate(valores):\n print(f'Naposição {c} encontrei o valor {v}!')\nprint('Cheguei ao final da lista')'''\n\n'''valores = list()\nfor cont in range(0, 5):\n valores.append(int(input('Digite um valor:')))\nfor c, v in enumerate( valores ):\n print( f'Naposição {c} encontrei o valor {v}!' )\nprint( 'Cheguei ao final da lista' )'''\n\na = [2, 3, 4, 7]\nb = a[:] #copia para edição\nb[2] = 8\nprint(f'Lista A: {a}')\nprint(f'Lista B: {b}')\n","sub_path":"PYTHON/pythonTeste/aula16.py","file_name":"aula16.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"41396875","text":"# -*- coding: utf-8 -*-\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nfrom datetime import datetime\nimport sqlite3\nimport os\nimport pandas as pd\nimport logging\nimport multiprocessing as mp\n\n__parent_dir__ = os.path.dirname(os.path.dirname(__file__))\n\n\ndef make_page_content(url):\n page = requests.get(url)\n return page.content\n\n\ndef make_soup(url):\n page = requests.get(url)\n return BeautifulSoup(page.content, 'html.parser')\n\n\ndef set_logger(log_file):\n logging.basicConfig(level=logging.DEBUG,\n format=\"%(asctime)s:%(levelname)s:%(message)s\",\n handlers=[logging.StreamHandler(),\n logging.FileHandler('{}.log'.format(log_file))]\n )\n\n\nclass NationalTeams:\n def __init__(self, url, multiprocessor=False):\n self.url = url\n self.page = requests.get(self.url)\n if not os.path.exists(os.path.join(__parent_dir__, 'national_football_teams.db')):\n sqlite3.connect(os.path.join(__parent_dir__, 'national_football_teams.db'))\n self.database = os.path.join(__parent_dir__, 'national_football_teams.db')\n self.multiprocessor = multiprocessor\n\n def fetch_continent_links(self):\n feds = dict()\n pattern = re.compile(r'.*/continent/\\d/(.*)\\.html')\n soup = make_soup(self.url).findAll('a', attrs={'href': pattern})\n for link in soup:\n href = link.get('href')\n feds[re.sub(pattern, r'\\1', href)] = '{}{}'.format(self.url, href)\n return feds\n\n def fetch_country_links(self, continent):\n feds = self.fetch_continent_links()\n countries = dict()\n pattern = re.compile(r'.*/country/\\d*/(.*)\\.html')\n soup = make_soup(feds[continent]).find_all('a', attrs={'href': pattern})\n for link in soup:\n href = link.get('href')\n countries[re.sub(pattern, r'\\1', href)] = '{}{}'.format(self.url, href)\n return countries\n\n def categorize_countries_by_continent(self):\n ref = dict()\n for continent in self.fetch_continent_links().keys():\n for country, link in self.fetch_country_links(continent).items():\n ref[country] = [continent, link]\n print('{} added as a county in {}'.format(country, continent))\n df = pd.DataFrame.from_dict(ref, orient='index', columns=['continent', 'link'])\n df.index.name = 'country'\n conn = sqlite3.connect(self.database)\n df.to_sql('countries_links', con=conn, if_exists='replace')\n conn.commit()\n conn.close()\n return ref\n\n @staticmethod\n def make_link_by_year(country_link, year):\n pattern = re.compile(r'(.*/country/\\d*/)(.*\\.html)')\n return re.sub(pattern, r'\\1[year]/\\2', country_link).replace('[year]', str(year))\n\n def fetch_match_table_content(self, country_link, year=datetime.now().year):\n matches = list()\n while year >= 2000:\n print('collecting data from year {}'.format(year))\n link = self.make_link_by_year(country_link, year)\n print(link)\n soup = make_soup(link).find_all('tr', attrs={'class': re.compile(r'(win|defeat|draw)')})\n pattern = re.compile(r'(teams home|date|teams away|result|event)')\n for tr in soup:\n req_data = filter(lambda x: re.search(pattern, x['class'][0]), tr.find_all('td'))\n req_data = list(map(lambda x: x.text.strip(), req_data))\n req_data.append(tr['class'][0])\n matches.append(req_data)\n year -= 1\n return matches\n\n def extract_results(self, args):\n link = args[0]\n country = args[1]\n logging.info(link)\n logging.debug('collecting data from {}'.format(country))\n matches = self.fetch_match_table_content(link)\n logging.info('{}\\'s Results are being stored in database!'.format(country))\n\n try:\n logging.debug('creating dataframe for {}'.format(country))\n df = pd.DataFrame(\n matches,\n columns=['Date', 'result', 'match_type', 'outcome'],\n index=False\n )\n logging.info('parsing the columns')\n df[['score', 'info', 'home_away']] = df['result'].str.split('\\n\\n', expand=True)\n df[['home', 'away']] = df['home_away'].str.split(' vs. ', expand=True)\n df[['HG', 'AG', 'PR']] = df['score'].str.extract(r'(\\d*):(\\d*)?(\\(\\d*:\\d*\\)|.*)', expand=True)\n df.drop(columns=['result', 'home_away', 'score'], inplace=True)\n\n conn = sqlite3.connect(self.database)\n df.to_sql(str(country), con=conn, index=False)\n logging.info('results have been successfully stored in database for {}!'.format(country))\n conn.commit()\n conn.close()\n\n except Exception as e:\n logging.exception(e)\n pass\n\n def main(self):\n set_logger(os.path.join(__parent_dir__,\n 'scraper_{}.log'.format(datetime.now().strftime('%Y%m%d%H%M'))))\n categories = list()\n for key, val in self.categorize_countries_by_continent().items():\n # making the categories dict iterable in multiprocessing mapping\n data = [val[1], key]\n categories.append(data)\n\n if self.multiprocessor:\n pool = mp.Pool(os.cpu_count() - 2)\n pool.map(\n self.extract_results,\n categories\n )\n else:\n for data in categories:\n self.extract_results(data)","sub_path":"FootballScraper/national_temas_scraper.py","file_name":"national_temas_scraper.py","file_ext":"py","file_size_in_byte":5650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"72976008","text":"\t#!/usr/bin/env python3\n\n\"\"\"\npaperparse.py\n\tA set of functions to deal with pubcrawl data\n\n\"\"\"\n\nimport nltk\nimport os\nfrom segtok.segmenter import split_single as ssplit\ntry:\n\tfrom modules import sent_tokenize as st\nexcept:\n\timport sent_tokenize as st\nimport re\n\n\"\"\"\ngetNames(filePath):\n\tGiven a pubcrawl/pubdip output file, returns the two species terms encoded in the file name, as well as their \n\tabbreviated forms\n\n\tSample pubcrawl output file:\n\t\tEscherichia_coli#Pseudomonas_aeruginosa.compiled\n\t\tEscherichia_coli#Pseudomonas_aeruginosa.sp\n\n\tResultant getNames output:\n\t\t[['escherichia coli', 'e. coli', 'escherichia'], ['pseudomonas aeruginosa', 'p. aeruginosa', 'pseudomonas']]\n\"\"\"\n\n\ndef getNames(filePath):\n\tdef shorten(tup):\n\t\treturn tup[0][0] + '. ' + tup[1]\n\tfilePath = os.path.basename(filePath)\n\tname = os.path.splitext(filePath)[0]\n\t\n\t# print(name)\n\tname = [i.split('_') for i in name.split('#')]\n\tname = [[i.lower() for i in j] for j in name]\n\n\t#check if genus only\n\t# print(name)\n\tif len(name[0]) ==1:\n\t\t\treturn [[i[0]] for i in name]\n\n\treturn [[\" \".join(i), shorten(i), i[0]] for i in name] \n\n\"\"\"\nloadFile(filepath):\n\tgeneric file input. Takes in the file as raw data and returns a list of stripped and lowered lines.\n\"\"\"\n\ndef loadFile(filePath):\n\tholder = []\n\twith open(filePath) as f:\n\t\tfor i in f:\n\t\t\tholder.append(i.strip().lower())\n\treturn holder\n\n\"\"\"\ntagStrip(line):\n\tremoves the medline tag from the line\n\n\"\"\"\n\ndef tagStrip(line):\n\treturn line[6:]\n\n\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n#####################\n# .sp Files #\n#####################\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n\"\"\"\nspFile():\n\tClass representation of a single .sp file. Contains the title, abstract, and their respective stemmed and tokenized forms\n\n\tloadSection(section):\n\t\tLoads a .sp section into split {TERM: DATA} dicitonaries.)\n\t\n\treadSpFile(spFIlePath):\n\t\treads a SP file\n\n\tNOTE: Use as base class for all the other paper derivatives\n\tNOTE: For all future pubcrawl outputs, pmid is NECESSARY\n\"\"\"\nclass spFile():\n\tdef __init__(self, spFilePath, purge = False):\n\t\tself.fileName = os.path.basename(spFilePath)\n\t\n\t\tloaded = self.readSpFile(spFilePath)\n\t\t#print(loaded)\n\t\tself.summary = self.loadSection(loaded[\"SUMMARY\"])\n\t\tif purge:\n\t\t\tfor i in self.summary:\n\t\t\t\tself.summary[i] = '0'\n\t\tpapers = loaded['PAPERS'].split('\\n\\n')\n\t\tself.papers = [self.loadSection(i) for i in papers]\n\t\t#print(self.papers)\n\t\tif purge:\n\t\t\tfor i in self.papers:\n\t\t\t\tif i == {}:\n\t\t\t\t\tcontinue\n\t\t\t\ti[\"TIHT\"] = ''\n\t\t\t\ti[\"ABHT\"] = \"\"\n\t\tself.papers = [i for i in self.papers if i != {}]\n\n\n\n\n\tdef loadSection(self, section):\n\t\t#holder = [i.split(\"==\") for i in section.split('\\n') if i != '' and i != '\\n']\n\t\t#HARDCODING \n\t\tholder = []\n\t\tfor i in section.split('\\n'):\n\t\t\tif i == '' or i == '\\n':\n\t\t\t\tcontinue\n\t\t\tholder.append((i[:4], i[6:].strip()))\n\t\ttry:\n\t\t\tresult = {i:j.strip() for i,j in holder}\n\t\texcept ValueError:\n\t\t\tprint(\"ERROR\")\n\t\t\tprint(holder)\n\t\t\tprint(section)\n\t\t\traise\n\t\treturn result\n\n\n\tdef readSpFile(self, spFilePath):\n\n\t\tholder = {}\n\t\ttry:\n\t\t\twith open(spFilePath) as f:\n\t\t\t\tfor i in f:\n\t\t\t\t\t#find the first section\n\t\t\t\t\tif i[0] == '#':\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif i[0] == '@':\n\t\t\t\t\t\tcurrent = i[1:].strip()\n\t\t\t\t\t\tholder[current] = ''\n\t\t\t\t\telse:\n\t\t\t\t\t\t#account for empty lines\n\t\t\t\t\t\tif i == '':\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tholder[current] += i\n\t\texcept:\n\t\t\tprint(spFilePath)\n\t\treturn holder\n\n\t#reads the list of papers, converts them into paper tuples\n\tdef loadPapers(self, rawAbstractList):\n\t\tholder = []\n\t\tres = []\n\t\tfor i in rawAbstractList:\n\t\t\tif i[0] == \">\":\n\t\t\t\tif holder == []:\n\t\t\t\t\tholder = [i[2:]]\n\t\t\t\telse:\n\t\t\t\t\tres.append(holder)\n\t\t\t\t\tholder = [i[2:]]\n\t\t\telse:\n\t\t\t\tholder.append(i)\n\t\treturn res\n\tdef writeSpFile(self, filePath):\n\t\twith open(filePath, 'w') as f:\n\t\t\t#handle the summary\n\t\t\tf.write(\"@SUMMARY\\n\")\n\t\t\tfor i in self.summary:\n\t\t\t\tf.write('== '.join([i, self.summary[i]]) + '\\n')\n\t\t\tf.write(\"@PAPERS\\n\")\n\t\t\tfor paperDict in self.papers:\n\t\t\t\tf.write(\"== \".join([\"PMID\", paperDict[\"PMID\"]]) + \"\\n\")\n\t\t\t\tf.write(\"== \".join([\"TI \", paperDict[\"TI \"]]) + \"\\n\")\n\t\t\t\tf.write(\"== \".join([\"AB \", paperDict[\"AB \"]]) + \"\\n\")\n\t\t\t\tf.write(\"== \".join([\"TIHT\", paperDict[\"TIHT\"]]) + \"\\n\")\n\t\t\t\tf.write(\"== \".join([\"ABHT\", paperDict[\"ABHT\"]]) + \"\\n\\n\")\n\tdef writeSpFileHits(self, filePath):\n\t\twith open(filePath, 'w') as f:\n\t\t\t#handle the summary\n\t\t\tf.write(\"@SUMMARY\\n\")\n\t\t\tfor i in self.summary:\n\t\t\t\tf.write('== '.join([i, self.summary[i]]) + '\\n')\n\t\t\tf.write(\"@PAPERS\\n\")\n\t\t\tfor paperDict in self.papers:\n\t\t\t\tif not (paperDict[\"TIHT\"] or paperDict[\"ABHT\"]):\n\t\t\t\t\tcontinue\n\t\t\t\tf.write(\"== \".join([\"PMID\", paperDict[\"PMID\"]]) + \"\\n\")\n\t\t\t\tf.write(\"== \".join([\"TI \", paperDict[\"TI \"]]) + \"\\n\")\n\t\t\t\tf.write(\"== \".join([\"AB \", paperDict[\"AB \"]]) + \"\\n\")\n\t\t\t\tf.write(\"== \".join([\"TIHT\", paperDict[\"TIHT\"]]) + \"\\n\")\n\t\t\t\tf.write(\"== \".join([\"ABHT\", paperDict[\"ABHT\"]]) + \"\\n\\n\")\n\n\n\n\n\nif __name__ == \"__main__\":\n\t#target = '../input/pattern/smalltestann/Actinomyces_sp.#Bacteroides_sp..sp'\n\ttarget = '../input/pattern/smalltestann/Actinomyces_sp.#Bacteroides_coprosuis.sp'\n\toutPath = '../formats_and_standards/tester/tester.sp'\n\ttemp = spFile(target)\n\ttemp.writeSpFile(outPath)","sub_path":"modules/paperparse.py","file_name":"paperparse.py","file_ext":"py","file_size_in_byte":5139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"463110035","text":"# Script to clean pre-process BIOMASS INVENTORY and make spatial\n\n####################################################################\n# First, load packages\nimport pandas as pd\nimport os\nimport geopandas as gpd\nfrom fxns import epsg_meters\nimport shapely as shp\n\ndef MergeInventoryAndCounty(gross_inventory, technical_inventory, county_shapefile, counties_popcen):\n \"\"\"\n Cleans biomass inventory data and merges with county shapefiles\n gross_inventory - gross estimate of biomass inventory\n technical_inventory - technical estimate of biomass inventory\n county_shapefile - shapefile of county polygons\n counties_popcen - csv population-weighted county centroids\n\n Returns: cleaned, spatial biomass data (assigned to pop-weighted \n county centroids and county polygons)\n \"\"\"\n\n ##################################################################\n #read in biomass inventory\n # GROSS inventory\n gbm = pd.read_csv(gross_inventory)\n\n # TECHNIcounty_shapeL inventory\n tbm = pd.read_csv(technical_inventory)\n\n\n gbm.rename(columns={\"biomass.feedstock\":\"feedstock\",\n 'biomass.category':'category',\n 'disposal.yields':'disposal_BDT'}, \n inplace=True)\n\n tbm.rename(columns={\"biomass.feedstock\":\"feedstock\",\n 'biomass.category':'category',\n 'disposal.yields':'disposal_BDT'}, \n inplace=True) \n\n\n # check that all counties in there\n assert len(gbm.COUNTY.unique())==59\n #yup, plus one \"other\"\n\n # gbm[gbm['disposal.yields'] == gbm['disposal.yields'].max()]\n\n # #look at just manure (if feedstock, needs to be capitalized), if category, lower case -- should be equivalent!\n # gbm[(gbm['biomass.feedstock'] == \"MANURE\") & (gbm['year'] == 2014)].head()\n\n # #start grouping by: biomass category\n # gbm.groupby(['biomass.category'])['disposal.yields'].sum()\n # gbm[gbm['biomass.category'] == \"manure\"].groupby(['COUNTY'])['disposal.yields'].sum().head()\n\n fw_mc = 0.7\n gw_mc = 0.5\n manure_mc = 0.85\n\n def bdt_to_wettons(df):\n df['wettons'] = 0.0\n n = len(df.index)\n for i in range(n):\n if df.feedstock[i] == \"FOOD\":\n df.at[i, 'wettons'] = df.disposal_BDT[i] * (1 + fw_mc)\n if df.feedstock[i] == \"GREEN\":\n df.at[i, 'wettons'] = df.disposal_BDT[i] * (1 + gw_mc)\n if df.feedstock[i] == \"MANURE\":\n df.at[i, 'wettons'] = df.disposal_BDT[i] * (1 + manure_mc)\n\n bdt_to_wettons(gbm)\n bdt_to_wettons(tbm)\n\n # turn from wet tons to wet m3\n gbm['disposal_wm3'] = gbm['wettons'] / (1.30795*(1/2.24))\n tbm['disposal_wm3'] = tbm['wettons'] / (1.30795*(1/2.24))\n\n\n # # now load SHAPEFILE for all county_shape COUNTIES to merge this\n # print(\"p Read in county_shape COUNTIES shapefile and reproject\")\n county_shape = gpd.read_file(county_shapefile)\n county_shape.rename(columns = {'NAME': 'COUNTY'}, inplace=True)\n county_shape= county_shape.to_crs(epsg=4326)\n county_shape['county_centroid'] = county_shape['geometry'].centroid \n\n # ALSO LOAD IN CSV of population-weighted county centroids - use this not geographic centroid!!\n counties_popcen = pd.read_csv(counties_popcen) # NEW - population weighted means!\n counties_popcen.rename(columns = {'LATITUDE': 'lat', 'LONGITUDE': 'lon', 'COUNAME': 'COUNTY'}, inplace=True)\n counties_popcen['county_centroid'] = [shp.geometry.Point(xy) for xy in \n zip(counties_popcen.lon, counties_popcen.lat)]\n\n #COUNTY POLYGONS with BIOMASS DATA(mostly for plotting)\n gbm_shp = pd.merge(county_shape, gbm, on = 'COUNTY')\n # Do same for technical biomass\n tbm_shp = pd.merge(county_shape, tbm, on = 'COUNTY')\n\n\n # POPULATION-WEIGHTED COUNTY CENTROIDS with BIOMASS DATA\n gbm_pts = pd.merge(counties_popcen, gbm, on = 'COUNTY')\n tbm_pts = pd.merge(counties_popcen, tbm, on = 'COUNTY')\n\n print(\"p BIOMASS PRE_PROCESSING DONE RUNNING\")\n\n return gbm_pts, tbm_pts\n","sub_path":"scripts/biomass_preprocessing.py","file_name":"biomass_preprocessing.py","file_ext":"py","file_size_in_byte":4106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"206993296","text":"import numpy as np\nimport random\nimport math\nimport copy\n\nboard = np.array([\n [0, 0, 2, 0, 8, 0, 5, 0, 0],\n [8, 0, 1, 2, 5, 7, 0, 4, 9],\n [0, 4, 0, 0, 0, 3, 8, 2, 7],\n [0, 8, 4, 1, 9, 0, 0, 0, 3],\n [3, 0, 0, 7, 0, 5, 2, 0, 0],\n [1, 0, 7, 0, 3, 2, 0, 0, 0],\n [0, 0, 0, 0, 7, 8, 0, 0, 0],\n [0, 6, 0, 0, 0, 9, 1, 0, 0],\n [0, 2, 8, 5, 0, 0, 0, 7, 4]], np.int32)\n\ndef verify(board):\n if (np.where(board == 0)[0]).size == 0:\n return True\n return False\n\ndef getNote(board):\n possible = np.ones((9,9,9))\n occ = np.where(board == 0)\n for i in range(0, occ[0].size):\n bad_values = []\n r = occ[0][i]\n c = occ[1][i]\n for j in range(0, 9):\n if(board[r][j] != 0):\n bad_values.append((board[r][j]))\n if(board[j][c] != 0):\n bad_values.append((board[j][c]))\n\n for m in range(0, 9):\n for n in range(0,9):\n if (math.floor(m/3) == math.floor(r/3) and math.floor(n/3) == math.floor(c/3)):\n if(board[m][n] != 0):\n bad_values.append(board[m][n])\n for value in bad_values:\n possible[value-1][r][c] = 0\n\n return possible\ndef getThrough(p, i, j):\n l = []\n for k in range(0,9):\n l.append(p[k][i][j])\n return l\n\ndef getMax(possible, b):\n max = 0\n x, y = None, None\n for i in range(0,9):\n for j in range(0,9):\n if (getThrough(possible, i,j).count(0) > max and getThrough(possible, i,j).count(0) < 9):\n if (b[i][j] == 0):\n x = i\n y = j\n max = getThrough(possible, i, j).count(0)\n return (max, x, y)\n\n\n\ntrial = 1\npossible = getNote(board)\nboard_static = copy.deepcopy(board)\nboard_sol = np.zeros([9,9])\n\nwhile(not verify(board_sol)):\n\n board_sol, possible_sol = copy.deepcopy(board), copy.deepcopy(possible)\n\n while True:\n max, x, y = getMax(possible_sol, board_sol)[0], getMax(possible_sol, board_sol)[1], getMax(possible_sol, board_sol)[2]\n if (x != None and y != None):\n l = [i for i, pns in enumerate(getThrough(possible_sol, x, y)) if pns == 1]\n occ = np.where(possible_sol[getMax(possible_sol, board_sol)[1]][getMax(possible_sol, board_sol)[2]] == 1)[0].tolist()\n board_sol[x][y] = random.choice(l) + 1\n possible_sol = getNote(board_sol)\n\n if (len(l) == 1):\n board[x][y] = random.choice(l) + 1\n else:\n print(\"Testing trial #\" + str(trial))\n print(board_sol)\n if (verify(board_sol)):\n print(\"Solution found:\")\n print(board_sol)\n break\n\n else:\n board = copy.deepcopy(board_static)\n board_sol = copy.deepcopy(board_static)\n possible_sol = getNote(board_sol)\n\n trial += 1\n\n break","sub_path":"sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":2999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"247707378","text":"from nose.tools import eq_\n\nfrom django.contrib.auth.models import User\nfrom django.test import TestCase\n\nfrom us_ignite.apps.models import Application\nfrom us_ignite.apps.tests.fixtures import get_application\nfrom us_ignite.challenges.managers import AppEntry\nfrom us_ignite.challenges.models import Challenge, Question, Entry\nfrom us_ignite.challenges.tests import fixtures\nfrom us_ignite.profiles.tests.fixtures import get_user\n\n\nclass TestActiveChallengesManager(TestCase):\n\n def tearDown(self):\n for model in [Challenge, User]:\n model.objects.all().delete()\n\n def test_active_chalenge_is_returned(self):\n user = get_user('us-ignite')\n instance = fixtures.get_challenge(\n user=user, status=Challenge.PUBLISHED)\n eq_(list(Challenge.active.all()), [instance])\n\n def test_removed_challenge_is_not_returned(self):\n user = get_user('us-ignite')\n fixtures.get_challenge(user=user, status=Challenge.REMOVED)\n eq_(list(Challenge.active.all()), [])\n\n\nclass TestQuestionManager(TestCase):\n\n def tearDown(self):\n for model in [Challenge, Question, User]:\n model.objects.all().delete()\n\n def test_questions_are_returned_from_keys(self):\n challenge = fixtures.get_challenge()\n question = fixtures.get_question(challenge, id=3)\n question_list = Question.objects.get_from_keys(['question_3'])\n eq_(list(question_list), [question])\n\n\nclass TestEntryManager(TestCase):\n\n def tearDown(self):\n for model in [Entry, Challenge, Application, User]:\n model.objects.all().delete()\n\n def test_missing_entry_returns_none(self):\n user = get_user('us-ignite')\n challenge = fixtures.get_challenge(user=user)\n application = get_application(owner=user)\n eq_(Entry.objects.get_entry_or_none(challenge, application), None)\n\n def test_existing_entry_is_returned(self):\n user = get_user('us-ignite')\n challenge = fixtures.get_challenge(user=user)\n application = get_application(owner=user)\n entry = fixtures.get_entry(\n application, challenge=challenge, status=Entry.SUBMITTED)\n eq_(Entry.objects.get_entry_or_none(challenge, application), entry)\n\n def test_get_entries_for_apps_returns_empty_entries(self):\n user = get_user('us-ignite')\n challenge = fixtures.get_challenge(user=user)\n application = get_application(owner=user)\n result = Entry.objects.get_entries_for_apps(challenge, [application])\n eq_(result, [AppEntry(application=application, entry=None)])\n\n def test_get_entries_for_apps_returns_entry(self):\n user = get_user('us-ignite')\n challenge = fixtures.get_challenge(user=user)\n application = get_application(owner=user)\n entry = fixtures.get_entry(application, challenge=challenge)\n result = Entry.objects.get_entries_for_apps(challenge, [application])\n eq_(result, [AppEntry(application=application, entry=entry)])\n","sub_path":"us_ignite/challenges/tests/managers_tests.py","file_name":"managers_tests.py","file_ext":"py","file_size_in_byte":3015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"52013433","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('mysite', '0001_initial'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='profile',\n old_name='birth_date',\n new_name='birthdate',\n ),\n migrations.RemoveField(\n model_name='profile',\n name='bio',\n ),\n migrations.AddField(\n model_name='profile',\n name='role',\n field=models.PositiveSmallIntegerField(blank=True, null=True, choices=[(1, b'Student'), (2, b'Teacher'), (3, b'Supervisor')]),\n ),\n ]\n","sub_path":"mysite/contributed_by_all/mysite/migrations/0002_auto_20180407_1208.py","file_name":"0002_auto_20180407_1208.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"48473384","text":"\"\"\"\nThis script scrapes the digitalocean.com site and stores the content in a generator\nwith namedtuples for easy handling.\n\"\"\"\n\nfrom collections import namedtuple\nfrom bs4 import BeautifulSoup\nfrom requests import get\nfrom utils import prettify_docean_price, prettify_string\n\n\nURL = \"https://www.digitalocean.com/pricing/\"\nsite = get(URL)\nsoup = BeautifulSoup(site.text, \"lxml\")\n\ntable = soup.find('table', {'class': 'PricingTable'})\nrows = table.find_all('tr')\n\ncomputers = namedtuple(\"PC\", \"memory vCPUs ssd transfer price\")\n\ndef get_data_digital_ocean(rows) -> namedtuple:\n \"\"\"\n Namedtuple generator function.\n Scrapes the digitalocean.com table rows and stores the content in a generator.\n param:\n - rows: Receives table rows from digitalocean.com.\n yield:\n - Generator with namedtuples of computers.\n \"\"\"\n for row in rows[1:]:\n cells = row.find_all('td')\n memory = prettify_string(cells[0].text)\n vcpus = prettify_string(cells[1].text)\n ssd = prettify_string(cells[2].text)\n transfer = prettify_string(cells[3].text)\n price = prettify_docean_price(cells[4].text)\n yield computers(memory, vcpus, ssd, transfer, price)\n\ngenerator_docean_data = get_data_digital_ocean(rows)\n","sub_path":"crawler/digital_ocean.py","file_name":"digital_ocean.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"231483305","text":"import re\nimport glob\nimport os\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndef read_dataset_folder(folder_path):\n \"\"\"\n Read the dataset folder and returns a list of datasets.\n Each dataset is a dict of the following format:\n {\n 'stats': a pandas Dataframe containing the simulations statistics,\n 'params': a dict containing the simulation parameters\n }\n :param string folder_path:\n :return: the list of datasets\n :rtype: list\n \"\"\"\n\n # init results\n dataset_list = []\n\n for subfolder in os.listdir(folder_path):\n file_path_list = glob.glob(os.path.join(folder_path, subfolder, '*.dat'))\n merged_params = None\n dataframe_list = []\n\n # read files and concatenate results\n for file_path in file_path_list:\n # read dataset file\n stats, params = read_dataset_file(file_path)\n\n # add cpuId column\n stats['cpuId'] = params['cpuID']\n\n # concatenate stats\n dataframe_list.append(stats)\n\n # merge simulation parameters\n del params['cpuID']\n if merged_params is None:\n merged_params = params\n else:\n assert merged_params == params\n\n merged_stats = pd.concat(dataframe_list)\n merged_stats.sort_values([\"cycle\"], inplace=True)\n dataset_list.append({\n \"stats\": merged_stats,\n \"params\": merged_params,\n \"name\": subfolder\n })\n return dataset_list\n\ndef read_dataset_file(file_path):\n \"\"\"\n Read the dataset and returns the simulation stats and parameters\n :param string file_path:\n :return: A Pandas Dataframe containing the stats and a dict containing the parameters\n :rtype: pandas.Dataframe & dict\n \"\"\"\n\n column_names = None\n parameters = {}\n\n # read column names\n with open(file_path, 'r') as f:\n for line in f:\n # get stats\n if line.startswith('## '):\n key, val = get_parameter_from_line(line)\n if key is not None:\n parameters.update({key: val})\n\n # get columns header\n if line.startswith('# '):\n column_names = line.strip().split(\" \")[1:]\n break\n\n if column_names is None:\n raise Exception(\"Could not read column names from file {0}\".format(file_path))\n\n # read stats (ignoring comment lines)\n stats = pd.read_csv(file_path, sep='[ ^]+', comment='#', names=column_names,\n engine='python')\n\n return stats, parameters\n\ndef get_parameter_from_line(line):\n \"\"\"Split line and return the parameter key and value\"\"\"\n stat_name = None\n stat_value = None\n\n # extract key and value from line\n m = re.findall(r'\\w+\\s+=\\s+.+', line)\n if len(m) > 0:\n m = m[0].replace(\" \", \"\").split(\"=\")\n if len(m) == 2:\n stat_name = m[0]\n stat_value = m[1]\n\n # try to convert the parameter value\n if stat_value.isdigit():\n stat_value = int(stat_value)\n elif isfloat(stat_value):\n stat_value = float(stat_value)\n elif islist(stat_value):\n stat_value = stat_value[1:-1].replace(\"'\", \"\").split(\",\")\n\n return stat_name, stat_value\n\ndef isfloat(str):\n \"\"\"check if the string can be converted to a float\"\"\"\n try:\n float(str)\n return True\n except ValueError:\n return False\n\ndef islist(str):\n \"\"\"check if the string can be converted to a list\"\"\"\n if str[0] == '[' and str[-1] == ']':\n return True\n else:\n return False\n\ndef savefig(output_folder, output_name, output_format=\"png\"):\n # check if output folder exists and create it if not\n if not os.path.isdir(output_folder):\n os.makedirs(output_folder)\n\n # save the figure\n plt.savefig(os.path.join(output_folder, output_name + \".\" + output_format),\n bbox_inches='tight',\n pad_inches=0,\n format=output_format)\n","sub_path":"simulator/bin/datasethelper.py","file_name":"datasethelper.py","file_ext":"py","file_size_in_byte":4022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"236370348","text":"import simpy as si\nimport time as ti\nimport numpy as np\n\nl_np = np.array([0,0,0])\nl = {}\nkey_M = []\n\n'''하나의 드론은 일반 배터리 내장 다른 드론은 지속적인 충전을 구현 '''\n\n#드론 객체 ###################################################################\n\ndef dron_1(env) :\n global battery_1,hight_1,inertia_1,dron_gps_1,restricted_area_1\n battery_1 = 620 * 5 #드론 배터리 용량\n dron_gps_1 = [0,0] #드론 위치(GPS)\n use_b_1 = 2300 * 5 # 배터리 사용량\n timer_1 = battery_1/use_b_1 * 60 #운행시간(분단위)\n\n \"\"\"\n 1번 드론 일반적인 베터리 충전 방식\n \"\"\"\n while timer_1 > 1 :\n timer_1 = timer_1 -1\n dron_gps_1[0] = dron_gps_1[0] + 10\n # print('드론 1이 간 거리' + str(dron_gps_1))\n # print('남은 운행시간 :' + str(timer_1))\n yield env.timeout(1)\n\n\ndef dron_2(env) :\n global battery_2,hight_2,inertia_2,dron_gps_2,restricted_area_2\n battery_2 = 620 * 5 #드론 배터리 용량 mAh\n dron_gps_2 = [0,0] #드론 위치(GPS)\n use_b_2 = 2300 * 5 # 배터리 사용량\n timer_2 = battery_2/use_b_2 * 60 #운행시간(분단위)\n charge_t_1 = 45/use_b_2 * 60 #충전 구현\n\n \"\"\"\n 2번 드론 지속적인 레이져 충전 방식\n \"\"\"\n while timer_2 > 1 :\n timer_2 = timer_2 -1\n timer_2 = timer_2 + charge_t_1\n dron_gps_2[0] = dron_gps_2[0] + 10\n # print('드론 2가 간 거리' + str(dron_gps_2))\n # print('남은 운행 시간 :' + str(timer_2))\n yield env.timeout(1)\n\n\ndef dron_3(env) :\n global battery_3,hight_3,inertia_3,dron_gps_3,restricted_area_3\n battery_3 = 600 * 5 #드론 배터리 용량\n use_b_3 = 2300 * 5 # 배터리 사용량\n charge_t_3 = np.random.randint(3,7)/10 * 0.5#충전 구현(태양광)\n timer_3 = (battery_3 + charge_t_3)/use_b_3 * 60 #운행시간(분단위)\n dron_gps_3 = [0,0] #드론 위치(GPS)\n \"\"\"\n 3번 드론 태양광 충전 방식\n \"\"\"\n while timer_3 > 1 :\n timer_3 = timer_3 - 1\n timer_3 = timer_3 + charge_t_3\n dron_gps_3[0] = dron_gps_3[0] + 10\n # print('드론 3가 간 거리' + str(dron_gps_3))\n # print('남은 배터리 :' + str(timer_3))\n yield env.timeout(1)\n\n#일반 객체 ###################################################################\ndef dic(x):\n return l[x]\n\n#시작 ###################################################################\n\nprint('''\n상황 : 일반적인 배터리를 사용하는 드론과 지속적인 래이져 충전을 사용하는 드론과 태양광 충전을 사용하는 드론 비교\n\n태양광 사용이 불가능한 날은 날씨가 좋지 않아 드론또한 운행이 불가능하므로 제외\n(3초 후 시뮬레이션 시작)\n''')\n\nti.sleep(3)\n\n#시뮬래이션 ###################################################################\n\ni = int(input('반복횟수 입력 >>>'))\n\n","sub_path":"simmulate_going.py","file_name":"simmulate_going.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"604719797","text":"# coding:latin-1\nimport os\nSITE_ROOT = os.path.dirname(os.path.realpath(__file__))\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n # ('Your Name', 'your_email@example.com'),\n)\n\nMANAGERS = ADMINS\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(SITE_ROOT, '../twitalarm.db'),\n },\n}\n\nTIME_ZONE = 'America/Chicago'\n\nLANGUAGE_CODE = 'es'\n\nugettext = lambda s: s\n\nLANGUAGES = (\n ('en', ugettext('English')),\n)\n\n\nSITE_ID = 1\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nMEDIA_ROOT = os.path.join(SITE_ROOT,'../../media')\n\nMEDIA_URL = '/media/'\n\nSTATIC_ROOT = ''\n\nSTATIC_URL = '/static/'\n\nADMIN_MEDIA_PREFIX = os.path.join(STATIC_URL, 'admin/')\n\nSTATICFILES_DIRS = (\n os.path.join(SITE_ROOT,'static'),\n)\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n# 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\nSECRET_KEY = 'w5np!7v*q(^)-4lcma#!ny&au(qh&syitom#et=jc(ns4h9zta'\n\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n 'django.template.loaders.eggs.Loader',\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n \"django.contrib.auth.context_processors.auth\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.static\",\n \"django.core.context_processors.request\",\n \"django.contrib.messages.context_processors.messages\",\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n)\n\nROOT_URLCONF = 'twitalarm.urls'\n\nTEMPLATE_DIRS = (\n os.path.join(SITE_ROOT, 'templates'),\n)\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.admin',\n # Contrib\n 'tastypie',\n # Custom\n 'events',\n # Contrib\n 'south',\n)\n\n# Search\nHAYSTACK_CONNECTIONS = {\n 'default': {\n 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',\n 'PATH': os.path.join(SITE_ROOT, '../whoosh_index'),\n },\n}\n\n# LOGGERS\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'standard': {\n 'format' : \"[%(asctime)s] %(levelname)s [%(name)s:%(pathname)s:%(lineno)s] %(message)s\",\n 'datefmt' : \"%d/%b/%Y %H:%M:%S\"\n },\n },\n 'handlers': {\n 'heartbeat_logfile': {\n 'level':'DEBUG',\n 'class':'logging.handlers.RotatingFileHandler',\n 'filename': os.path.join(SITE_ROOT, '../log', 'heartbeat.log'),\n 'maxBytes': 50000,\n 'backupCount': 2,\n 'formatter': 'standard',\n },\n },\n 'loggers': {\n 'heartbeat': {\n 'handlers': ['heartbeat_logfile'],\n 'level': 'DEBUG',\n },\n }\n}\n","sub_path":"twitalarm/twitalarm/settings_default.py","file_name":"settings_default.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"341477643","text":"import json\nimport jsonschema\nimport os\nimport six\nimport numpy as np\nimport tempfile\nimport tensorflow as tf\nimport zipfile\nfrom six.moves import zip # pylint: disable=redefined-builtin\nfrom utils import ckpts\nfrom collections import OrderedDict, defaultdict\nfrom utils import ckpts\nfrom tensorio_bundler import bundler\nimport time\nimport requests\nimport wget\nfrom tensorflow.python.saved_model import loader\nimport logging\nimport copy\n\n\nCHECKPOINT_BASENAME = \"checkpoint\"\nCHECKPOINT_PB_BASENAME = \"variables\"\nBUNDLE_CHECKPOINT_DIRECTORY = \"checkpoints\"\nRESULT_JSON_BASENAME = \"result.json\"\nSAVED_MODEL_BASENAME = \"saved_model.pb\"\nMODEL_JSON_BASENAME = \"model.json\"\nTIO_PREFIX = \"tio://\"\n\n\nclass AggregatorNotFoundException(Exception):\n pass\n\n\nclass SchemaFailedException(Exception):\n pass\n\n\nclass TensorIOModelsRepositoryException(Exception):\n pass\n\n\nclass Aggregator(object):\n\n def __init__(\n self,\n resource_path,\n output_resource_path,\n repository,\n token,\n export_type,\n aggregator_type,\n temp_dir=\"/tmp/\",\n schema_path=\"./schemas/schema.json\"\n ):\n self.resource_path = resource_path\n self.output_resource_path = output_resource_path\n self.repository = repository\n self.token = token\n self.checkpoint_basename = CHECKPOINT_BASENAME if export_type == 'checkpoint' else CHECKPOINT_PB_BASENAME\n self.temp_dir = temp_dir\n\n # Initialize logger\n self.logger = logging.getLogger('aggregator')\n self.logger.setLevel(logging.DEBUG) # TODO: env var or cli to set this\n self.main_handler = logging.StreamHandler()\n self.main_formatter = logging.Formatter('%(levelname)s - %(asctime)s - %(name)s: %(message)s')\n self.main_handler.setFormatter(self.main_formatter)\n self.logger.addHandler(self.main_handler)\n\n self.logger.info(\"Configured to talk to repository: {0}\".format(repository))\n self.logger.info(\"Checkpoint will be READ from: {0}\".format(resource_path))\n self.logger.info(\"Checkpoint will be WRITTEN to: {0}\".format(output_resource_path))\n self.logger.debug(\"Using temporary directory: {0}\".format(temp_dir))\n self.logger.debug(\"Using schema: {0}\".format(schema_path))\n\n # Cumulative Moving Average, Weighted Cumulative Moving Average\n self.aggregator_step_functions = {\n \"CumulativeMovingAverage\": self._cumulative_moving_average_steps,\n \"WeightedCumulativeMovingAverage\": self._weighted_cumulative_moving_average_steps\n }\n # Aggregated model export type functions\n self.aggregator_export_functions = {\n \"checkpoint\": self._output_checkpoint,\n \"saved_model\": self._output_saved_model,\n \"bundle\": self._output_bundle,\n }\n\n # Get canonical checkpoint and set canonical variables\n self._get_cannonical()\n\n if aggregator_type not in self.aggregator_step_functions.keys():\n raise AggregatorNotFoundException(\"Aggregator of type \\\"{0}\\\" not found.\".format(aggregator_type))\n else:\n self.aggregator_step_fn = self.aggregator_step_functions[aggregator_type]\n\n if export_type not in self.aggregator_export_functions.keys():\n raise AggregatorNotFoundException(\"Aggregator export type \\\"{0}\\\" not found.\".format(export_type))\n else:\n self.export_fn = self.aggregator_export_functions[export_type]\n\n with tf.gfile.Open(schema_path, 'r') as schema_fp:\n self.schema = json.load(schema_fp)\n\n\n def aggregate(self, bundle_paths, output_path):\n update_var_values, update_var_dtypes = self._aggregate_ckpts(bundle_paths)\n self._apply_aggregation(output_path, update_var_values, update_var_dtypes)\n\n\n @staticmethod\n def validate_json_schema(result, schema):\n try:\n jsonschema.validate(instance=result, schema=schema)\n except Exception as e:\n raise SchemaFailedException(str(e))\n\n\n @staticmethod\n def _cumulative_moving_average_steps(steps):\n return 1\n\n\n @staticmethod\n def _weighted_cumulative_moving_average_steps(steps):\n return steps\n\n\n @staticmethod\n def _update_function(current, next_, current_steps, steps):\n if current_steps == 0:\n return next_\n update = ((current * current_steps) + (next_ * steps)) / (current_steps + steps)\n return update\n\n\n def _get_cannonical(self):\n # Initialize: Read canonical json, saved_model, respective variables names/shape, set values to zero\n # Opening in temporary directory, and storing relevant files in memory\n # This way we only need to get canonical files once instead of twice,\n # without changing class structure\n self.canonical_var_values, self.canonical_var_dtypes = {}, {}\n self.canonical_var_set = set([])\n\n with tempfile.TemporaryDirectory(dir=self.temp_dir) as canonical_temp:\n self.canonical_bundle_temppath = self._get_cannonical_bunde(canonical_temp)\n model_json_temppath = os.path.join(self.canonical_bundle_temppath, MODEL_JSON_BASENAME)\n\n # TODO: validate model.json\n with tf.gfile.Open(model_json_temppath, 'r') as model_json_input:\n self.model_json = json.load(model_json_input)\n model_json_spec = self.model_json.get('model', {})\n self.model_json_mode = model_json_spec.get('file')\n\n saved_model_pb_temppath = os.path.join(self.canonical_bundle_temppath, self.model_json_mode, SAVED_MODEL_BASENAME)\n with tf.gfile.Open(saved_model_pb_temppath, 'rb') as saved_model_fp:\n self.saved_model_binary = saved_model_fp.read()\n\n canonical_variables_temppath = os.path.join(self.canonical_bundle_temppath, self.model_json_mode, CHECKPOINT_PB_BASENAME)\n canonical_ckpt = ckpts.find_trained_checkpoints(canonical_variables_temppath)[0]\n # Load checkpoint\n canonical_reader = tf.contrib.framework.load_checkpoint(canonical_ckpt)\n self.canonical_var_list = tf.contrib.framework.list_variables(canonical_ckpt)\n # Initialize variables/weights\n for (canonical_name, canonical_shape) in self.canonical_var_list:\n self.canonical_var_values[canonical_name] = np.zeros(canonical_shape)\n canonical_tensor = canonical_reader.get_tensor(canonical_name)\n self.canonical_var_dtypes[canonical_name] = canonical_tensor.dtype\n self.canonical_var_set.add(canonical_name)\n self.logger.info(\"Initializing aggregated variables from: {0}\".format(canonical_ckpt))\n\n\n def _get_cannonical_bunde(self, tempfile_temp_dir):\n try:\n url = \"{0}{1}\".format(self.repository, self.resource_path)\n headers = {\n \"Authorization\": \"Bearer {0}\".format(self.token)\n }\n response = requests.request(\"GET\", url, data=\"\", headers=headers)\n response_json = response.json()\n self.logger.info(\"Cannonical checkpoint JSON response {0}\".format(response_json))\n url2 = response_json['link']\n bundle_download_filename = wget.download(url2, out=tempfile_temp_dir)\n except Exception as e:\n raise TensorIOModelsRepositoryException(\n \"Failed to get tensorio-models cannonical bundle, error: {0}\".format(str(e))\n )\n\n # Unzip bundle\n bundle_basename = os.path.basename(bundle_download_filename)\n with tf.gfile.Open(bundle_download_filename, 'rb') as bundle_fp:\n with zipfile.ZipFile(bundle_fp) as zf:\n zf.extractall(tempfile_temp_dir)\n os.remove(bundle_download_filename)\n\n bundle_dirname = \".\".join(bundle_basename.split(\".\")[:-1])\n unzipped_bundle_dirs = [dir_name for dir_name in tf.gfile.ListDirectory(tempfile_temp_dir) if dir_name.split(\".\")[-1] != \"zip\"]\n assert len(unzipped_bundle_dirs) == 1\n bundle_path = os.path.join(tempfile_temp_dir, unzipped_bundle_dirs[0])\n return bundle_path\n\n\n def _aggregate_ckpts(self, bundle_paths):\n current_steps = 0\n update_var_values = copy.deepcopy(self.canonical_var_values)\n update_var_dtypes = copy.deepcopy(self.canonical_var_dtypes)\n\n # Load result/update checkpoints and aggregate\n for i, bundle_path in enumerate(bundle_paths):\n var_values, var_dtypes = {}, {}\n self.logger.info(\"Aggregating bundle: {0}\".format(bundle_path))\n self.logger.info(\"Number of steps seen thus far: {0}\".format(current_steps))\n with tempfile.TemporaryDirectory(dir=self.temp_dir) as temp:\n bundle_basename = os.path.basename(bundle_path)\n with tf.gfile.Open(bundle_path, 'rb') as bundle_fp:\n with zipfile.ZipFile(bundle_fp) as zf:\n zf.extractall(temp)\n self.logger.info(\"Unzipping succesful to directory: {0}\".format(temp))\n bundle_dirname = \".\".join(bundle_basename.split(\".\")[:-1])\n model_directory_name = os.path.join(temp, bundle_dirname)\n checkpoint_dir_name = os.path.join(model_directory_name, BUNDLE_CHECKPOINT_DIRECTORY)\n current_ckpt = ckpts.find_trained_checkpoints(checkpoint_dir_name)[0]\n\n # Get result/update checkpoint\n result_filename = os.path.join(model_directory_name, RESULT_JSON_BASENAME)\n with tf.gfile.Open(result_filename, 'r') as result_fp:\n results_dict = json.load(result_fp)\n Aggregator.validate_json_schema(results_dict, self.schema)\n checkpoint_steps = results_dict['numSamples']\n self.logger.debug(\"Number of samples for update {0}: {1}\".format(bundle_path, checkpoint_steps))\n steps = self.aggregator_step_fn(checkpoint_steps)\n self.logger.debug(\"Processed number of steps based on aggregation type: {0}\".format(steps))\n\n # Load checkpoint\n reader = tf.contrib.framework.load_checkpoint(current_ckpt)\n var_list = tf.contrib.framework.list_variables(current_ckpt)\n var_set = set([name for (name, _ ) in var_list])\n var_dict = dict(var_list)\n\n # Verify set differences\n missing_canonical_vars = self.canonical_var_set - var_set\n missing_update_vars = var_set - self.canonical_var_set\n if len(missing_canonical_vars) > 0:\n self.logger.debug(\"Canonical checkpoint variables NOT in Update: {0}\".format(missing_canonical_vars))\n if len(missing_update_vars) > 0:\n self.logger.debug(\"Update checkpoint variables NOT in Canonical: {0}\".format(missing_update_vars))\n\n # Aggregate variables/weights\n for (name, shape) in self.canonical_var_list:\n tensor = reader.get_tensor(name)\n var_values[name] = tensor\n var_dtypes[name] = tensor.dtype\n\n # Do not update variables that are not in result/update checkpoint\n if name not in var_values.keys() and name not in var_dtypes.keys():\n continue\n if shape != var_dict[name]:\n self.logger.info(\"Canonical variable of shape: {0}, Update variable of shape: {1}\".format(shape, var_list_dict[name]))\n # Check dtype match\n if var_dtypes[name] != self.canonical_var_dtypes[name]:\n self.logger.info(\"Canonical variable of type: {0}, Update variable of type: {1}\".format(canonical_var_dtypes[name], var_dtypes[name]))\n\n update_var_values[name] = Aggregator._update_function(update_var_values[name], tensor, current_steps, steps)\n self.logger.info(\"Checkpoint aggregation successful for: {0}\".format(current_ckpt))\n current_steps += steps\n\n return update_var_values, update_var_dtypes\n\n\n def _apply_aggregation(self, output_path, var_values, var_dtypes):\n # Get/Create original Tensorflow variables\n self.logger.info(\"Applying aggregation to export bundle...\")\n tf.reset_default_graph()\n tf_vars = [tf.get_variable(v, shape=var_values[v].shape, dtype=var_dtypes[v]) for v in var_values]\n # Create respective placeholders to feed in Numpy values\n placeholders = [tf.placeholder(v.dtype, shape=v.shape) for v in tf_vars]\n # Assign fed values to original Tensorflow variables\n assign_ops = [tf.assign(v, p) for (v, p) in zip(tf_vars, placeholders)]\n # Create Saver to execute sync\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=1)\n # Build a model consisting only of variables and set to average values\n with tf.Session() as session:\n # Initialize computational graph\n session.run(tf.global_variables_initializer())\n # Run built Tensorflow computational graph to assign variables/weights\n for p, assign_op, (name, value) in zip(placeholders, assign_ops, six.iteritems(var_values)):\n session.run(assign_op, {p: value})\n # Export aggregation\n self.export_fn(saver, session, output_path)\n\n\n def _output_checkpoint(self, saver, session, output_path):\n ckpts.check_or_create_dir(output_path)\n aggregated_checkpoint_path = os.path.join(output_path, self.checkpoint_basename)\n save_path = saver.save(session, aggregated_checkpoint_path, write_meta_graph=True)\n self.logger.info(\"Averaged model chackpoints saved in: {0}\".format(save_path))\n\n\n def _output_saved_model(self, saver, session, output_path):\n # Create necessary bundle structure for aggregation\n ckpts.check_or_create_dir(output_path)\n aggregated_checkpoint_directory = os.path.join(output_path, self.checkpoint_basename)\n ckpts.check_or_create_dir(aggregated_checkpoint_directory)\n # `aggregated_checkpoint_path` is not a directory, but basename for variables/ files\n aggregated_checkpoint_path = os.path.join(aggregated_checkpoint_directory, self.checkpoint_basename)\n\n # Unzip and copy necessary files\n with tempfile.TemporaryDirectory(dir=self.temp_dir) as temp:\n bundle_path = self._get_cannonical_bunde(temp)\n saved_model_pb_temppath = os.path.join(bundle_path, self.model_json_mode, SAVED_MODEL_BASENAME)\n saved_model_pb_newpath = os.path.join(output_path, SAVED_MODEL_BASENAME)\n with tf.gfile.Open(saved_model_pb_newpath, 'wb') as saved_model_output:\n saved_model_output.write(self.saved_model_binary)\n\n # No metagraph needed for pb exports\n save_path = saver.save(session, aggregated_checkpoint_path, write_meta_graph=False)\n self.logger.info(\"Averaged saved_model ProtoBuf saved in: {0}\".format(save_path))\n\n\n def _output_bundle(self, saver, session, output_path):\n with tempfile.TemporaryDirectory(dir=self.temp_dir) as temp_bundle:\n # Create necessary bundle structure for aggregation\n ckpts.check_or_create_dir(temp_bundle)\n aggregated_pb_directory = os.path.join(temp_bundle, self.model_json_mode)\n ckpts.check_or_create_dir(aggregated_pb_directory)\n aggregated_checkpoint_directory = os.path.join(aggregated_pb_directory, self.checkpoint_basename)\n ckpts.check_or_create_dir(aggregated_checkpoint_directory)\n # `aggregated_checkpoint_path` is not a directory, but basename for variables/ files\n aggregated_checkpoint_path = os.path.join(aggregated_checkpoint_directory, self.checkpoint_basename)\n\n # No metagraph needed for pb exports\n save_path = saver.save(session, aggregated_checkpoint_path, write_meta_graph=False)\n self.logger.info(\"Averaged saved_model ProtoBuf saved in: {0}\".format(save_path))\n\n # Unzip and copy necessary files\n tio_output_path = \"{0}{1}\".format(TIO_PREFIX, self.output_resource_path)\n saved_model_pb_newpath = os.path.join(aggregated_pb_directory, SAVED_MODEL_BASENAME)\n with tf.gfile.Open(saved_model_pb_newpath, 'wb') as saved_model_output:\n saved_model_output.write(self.saved_model_binary)\n\n model_json_newpath = os.path.join(temp_bundle, MODEL_JSON_BASENAME)\n self.model_json['id'] = tio_output_path\n with tf.gfile.Open(model_json_newpath, 'w') as model_json_output:\n json.dump(self.model_json, model_json_output, indent=4)\n\n # Create bundle\n bundle_basename = os.path.basename(self.canonical_bundle_temppath)\n bundle_name = \".\".join(bundle_basename.split(\".\")[:-1])\n bundle_extension = bundle_basename.split(\".\")[-1]\n # example bundle name: manna-train-aggregated-1520170716.tiobundle.zip\n tiobundle_zip_name = \"{0}-aggregated-{1}.{2}.zip\".format(bundle_name, int(time.time()), bundle_extension)\n tiobundle_output_path = os.path.join(output_path, tiobundle_zip_name)\n bundle_output_path = bundler.tiobundle_build(\n aggregated_pb_directory, # bundler only needs saved_model directory\n model_json_newpath,\n None,\n bundle_basename, # unzipped bundle directory must match canonical\n tiobundle_output_path\n )\n self.logger.info(\"Output bundle stored: {0}\".format(tiobundle_output_path))\n assert tiobundle_output_path == bundle_output_path\n\n # Register bundle\n registration = bundler.register_bundle(bundle_output_path, self.output_resource_path)\n self.logger.info('Bundle registered against repository: {}'.format(registration))\n\n\n\n","sub_path":"aggregator/aggregator.py","file_name":"aggregator.py","file_ext":"py","file_size_in_byte":18089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"332482357","text":"from requests import get\r\nfrom scrapy import Selector\r\nimport re\r\n\r\n\r\ndef catch_URL(URL):\r\n url_emploi = URL\r\n response_emploi = get(url_emploi)\r\n source_emploi = None\r\n\r\n if response_emploi.status_code == 200:\r\n source_emploi = response_emploi.text\r\n return source_emploi\r\n\r\n\r\ndef catch_data(source):\r\n if source:\r\n\r\n # Si le code source existe\r\n selector_emploi = Selector(text=source)\r\n contenus_emploi = selector_emploi.css(\"div.row\")\r\n print(\"N° DATE REGION COMPAGNIE DESCRIPTION\")\r\n print(\"_________________________________________________________________________________\")\r\n cmp = 1\r\n for contenu in contenus_emploi:\r\n if cmp < 2:\r\n date_emploi_x = contenu.css(\"p.job-recruiter::text\").extract_first()\r\n if cmp == 1:\r\n print(type(date_emploi_x))\r\n date_emploi = date_emploi_x.split(' | ')[0]\r\n date_coupee = date_emploi.split('.')\r\n print(date_coupee)\r\n\r\n jour_emploi = date_coupee[0]\r\n mois_emploi = date_coupee[1]\r\n annee_emploi = date_coupee[2]\r\n\r\n region_emploi_x = contenu.css(\"div.search-description + p::text\").extract_first()\r\n region_emploi = re.split(\" : \", region_emploi_x)[1]\r\n\r\n compagnie_emploi = contenu.css(\"p.job-recruiter b *::text\").extract_first()\r\n desc_emploi = contenu.css(\"div.search-description::text\").extract_first()\r\n\r\n link_level = contenu.css(\"h5 a::attr(href)\").extract_first()\r\n\r\n print(cmp, \" | \", jour_emploi, \" | \", mois_emploi, \" | \", annee_emploi, \" | \", region_emploi, \" | \", compagnie_emploi, \" | \", desc_emploi, \" \",\r\n link_level)\r\n cmp += 1\r\n\r\n return contenus_emploi\r\n\r\ndef catch_sec_niv(source):\r\n if source:\r\n\r\n # Si le code source existe\r\n selector_emploi = Selector(text=source)\r\n contenus_emploi = selector_emploi.css(\"body\")\r\n print(\"N° SECTEUR NIVEAU D'ETUDES \")\r\n print(\"_________________________________________________________________________________\")\r\n\r\n for contenu in contenus_emploi:\r\n secteur_emploi = contenu.css(\"div.field.field-name-field-offre-secteur.field-type-taxonomy-term-reference.field-label-hidden div.field-items div.field-item.even::text\").extract_first()\r\n if secteur_emploi == None:\r\n secteur_emploi = \"N/A\"\r\n\r\n niveau_emploi = contenu.css(\"div.field.field-name-field-offre-niveau-etude.field-type-taxonomy-term-reference.field-label-hidden div.field-items div.field-item.even::text\").extract_first()\r\n if niveau_emploi == None :\r\n niveau_emploi = \"N/A\"\r\n\r\n print(\"secteur : \", secteur_emploi)\r\n print(\"niveau d'études requis : \", niveau_emploi)\r\n print(type(secteur_emploi))\r\n print(type(niveau_emploi))\r\n return contenus_emploi\r\n\r\nurl_emploi = \"https://www.emploi.ma/offre-emploi-maroc/consultant-securite-informatique-5948742\"\r\n\r\nsource_emploi_ma = catch_URL(url_emploi)\r\n#data_emploi_ma = catch_data(source_emploi_ma)\r\ndata_emploi_ma = catch_sec_niv(source_emploi_ma)\r\n\r\nprint(data_emploi_ma)\r\n","sub_path":"test_emploima.py","file_name":"test_emploima.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"103312446","text":"import fasttext\nimport prenlp\nfrom prenlp.data import Normalizer\nfrom prenlp.tokenizer import SentencePiece\n\n# Data preparation\nnsmc_train, nsmc_test = prenlp.data.NSMC()\n\n# Corpus preparation for training SentencePiece\ncorpus_path = 'corpus.txt'\nwith open(corpus_path, 'w', encoding='utf-8') as writer:\n for text, label in nsmc_train:\n writer.write(text.strip()+'\\n')\n\n# Preprocessing\ntokenizer = SentencePiece()\ntokenizer.train(input=corpus_path, model_prefix='sentencepiece', vocab_size=10000)\ntokenizer.load('sentencepiece.model')\nnormalizer = Normalizer(url_repl=' ', tag_repl=' ', emoji_repl=' ', email_repl=' ', tel_repl=' ')\n\nfor dataset in [nsmc_train, nsmc_test]:\n for i, (text, label) in enumerate(dataset):\n dataset[i][0] = ' '.join(tokenizer(normalizer.normalize(text.strip())))\n\nprenlp.data.fasttext_transform(nsmc_train, 'nsmc.train')\nprenlp.data.fasttext_transform(nsmc_test, 'nsmc.test')\n \n# Train\nmodel = fasttext.train_supervised(input='nsmc.train', epoch=20)\n\n# Evaluate\nprint(model.test('nsmc.train'))\nprint(model.test('nsmc.test'))\n\n# Inference\nprint(model.predict(nsmc_test[0][0]))","sub_path":"examples/fasttext_nsmc_sentencepiece.py","file_name":"fasttext_nsmc_sentencepiece.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"419721631","text":"# by @f0rizen\n\nfrom .. import loader, utils\n\nimport logging\nimport asyncio\nimport time\n\nlogger = logging.getLogger(__name__)\n\n@loader.tds\nclass HACKMod(loader.Module):\n\t\"\"\"Hack your ass\"\"\"\n\tstrings = {\"name\": \"Hacking\"}\n\tdef __init__(self):\n\t\tself.name = self.strings[\"name\"]\n\tdef config_complete(self):\n\t\tpass\n\tasync def akkcmd(self, message):\n\t\t\"\"\"Hack your ass\"\"\"\n\t\ti = 0\n\t\twhile i <= 99:\n\t\t\tawait message.edit(\"Account telegram hacked for \" + str(i) + \"%\")\n\t\t\ti += 1\n\t\t\ttime.sleep(0.3)\n\t\ttime.sleep(0.3)\n\t\tawait message.edit(\"Account telegram successfully hacked\")\n\t\treturn\n","sub_path":"Vzlom.py","file_name":"Vzlom.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"647590718","text":"#!/usr/bin/env python \nfrom midca import base, rosrun\nfrom midca.modules.perceive import ROSObserver\nfrom midca.modules.plan import AsynchPyhopPlanner\nfrom midca.modules.intend import SimpleIntend\nfrom midca.modules.act import AsynchronousAct\nfrom midca.modules.interpret import InstructionReceiver\nfrom midca.modules.evaluate import EvalPointingFromFeedback\nfrom midca.modules import simulator\nfrom midca.modules._plan.asynch import asynch, operators_sr, methods_sr\nfrom midca.logging import Logger\nimport inspect, os\nfrom std_msgs.msg import String\nfrom midca.examples._gazebo_baxter import Calibrate\nfrom geometry_msgs.msg import Point, PointStamped\n\n\ndef ros_style_midca():\n\tmyMidca = base.MIDCA(None, verbose = 2)\n\tfor phase in [\"Perceive\", \"Interpret\", \"Eval\", \"Intend\", \"Plan\", \"Act\"]:\n\t\tmyMidca.append_phase(phase)\n\n\tmyMidca.append_module(\"Perceive\", ROSObserver.ROSObserver())\n\tmyMidca.append_module(\"Interpret\", InstructionReceiver.InstructionReceiver_sr())\n\tmyMidca.append_module(\"Eval\", EvalPointingFromFeedback.EvalPointingFromFeedback())\n\tmyMidca.append_module(\"Intend\", SimpleIntend.SimpleIntend())\n\tmyMidca.append_module(\"Plan\", AsynchPyhopPlanner.AsynchPyhopPlanner(methods_sr.declare_methods,\n\toperators_sr.declare_ops\n\t\n\t))\n\tmyMidca.append_module(\"Act\", AsynchronousAct.AsynchronousAct())\n\treturn myMidca\n\t\nthisDir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n\nMIDCA_ROOT = thisDir + \"/../\"\n\nmyMidca = ros_style_midca()\n\n#myMidca.logger.logOutput()\n#myMidca.mem.enableLogging(myMidca.logger)\n\n# calibration\n\n\nrosMidca = rosrun.RosMidca(myMidca, incomingMsgHandlers = [\n\t#rosrun.CalibrationHandler(\"calibrate_done\", myMidca),\n\trosrun.threeObjectsLocationHandler(\"obj_pos\", myMidca),\n\trosrun.UtteranceHandler(\"cmds_received\", myMidca),\n\trosrun.FeedbackHandler(rosrun.FEEDBACK_TOPIC, myMidca)],\n\toutgoingMsgHandlers = [rosrun.OutgoingMsgHandler(asynch.LOC_TOPIC, String), \n\t\t\t\t\t\trosrun.OutgoingMsgHandler(asynch.GRAB_TOPIC, String),\n\t\t\t\t\t\trosrun.OutgoingMsgHandler(asynch.RELEASE_TOPIC, String),\n\t\t\t\t\t\trosrun.OutgoingMsgHandler(asynch.RAISE_TOPIC, String)])\n\nrosMidca.ros_connect()\n\n\nH = Calibrate.calibrate()\n#Z = -0.15113003072395247\n#Z = -0.16113003072395247\nZ=-0.147\nmyMidca.mem.set(myMidca.mem.CALIBRATION_MATRIX, H)\nmyMidca.mem.set(myMidca.mem.CALIBRATION_Z, Z)\n#myMidca.mem.set(myMidca.mem.STACK_Z, 0.018148563732166244)\nmyMidca.mem.set(myMidca.mem.STACK_Z, -0.108833784354784)\nmyMidca.mem.set(myMidca.mem.STACK_3Z, 0.01517833784354784)\nmyMidca.mem.set(myMidca.mem.UNSTACK_Z, -0.11434523370125365)\nmyMidca.mem.set(myMidca.mem.UNSTACK_3Z, -0.05434523370125365)\n\np = Point(x = 0.5682, y = 0.1829 , z = 0.2256)\n#p = \nmyMidca.mem.set(myMidca.mem.RAISING_POINT, p)\n#0.6754473650020971, 0.3487005600746112\n#q = Point(x = 0.6754473650020971, y = 0.3487005600746112, z = -0.14113003072395247)\n#q = Point(x = 0.7596311811530513, y = 0.09691300804254104, z = -0.14113003072395247)\n#lab_q =Point(0.7450848313136519, 0.11634406023548731, -0.15821251824917773)\nq = Point(0.69, 0.01967133208903987, -0.145)\nmyMidca.mem.set(myMidca.mem.PUTTING_POINT, q)\n\n\ninput('Enter ...')\nrosMidca.run_midca()\n","sub_path":"midca/examples/baxter_run_OD_sim.py","file_name":"baxter_run_OD_sim.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"568934761","text":"\nimport pandas as pd\nimport spacy\nimport sys\nspacy.prefer_gpu()\nnlp = spacy.load(\"en_core_web_sm\")\nimport random\nimport re\nfrom random import seed\nimport time\nimport random\nfrom readAndWriteData import write_json, write_csv_from_dict\nfrom sklearn.model_selection import train_test_split\n\ndata = pd.read_csv(\"intermediate_files/new_csv_generated.csv\")\n# data = pd.read_csv(\"balacopa-dev-all.csv\")\n# data = pd.read_csv(\"balacopa-dev-small.csv\")\ncount = 0\n\npronoun_set = set()\noutput_dict = {}\n# output_dict = set()\n\nmale_set = {'her brother', 'his older brother', 'he', 'his brother', 'the man','him', 'the boy'}\nfemale_set = {'her', 'her sister', 'the girl', 'her mother','her daughter','she','the woman','his mother'}\nneutral_set = {'the suspect', 'the police officer','his classmate','the rider', 'the assailant', 'the student', 'the child', \n'a player', 'the physician', 'the scar','his enemy', 'the police', 'the bully', 'the cook', 'i', 'the customer',\n 'the therapist', 'the teacher', 'the caller','the president','her friend','the celebrity','the mayor','the baby'}\nobject_set = {'the gum', 'the computer', 'the door','the puddle', 'it', 'my foot', 'the chair', 'her finger',\n'the bottle', 'the shirt', 'the paperclip', 'the dog', 'the railing', 'her hair', 'college', 'the floor', \n'the book', 'my yard', 'the puzzle', 'the clay','the button', 'his back', 'the church', 'the moon','the disease','the question','his theory','the gift','loose change','the tablecloth','the thread','the room','the jar','the pond',\n'the fabric', 'the desk','the liquid', 'the slide',\"the patient's arm\",'the bill','his toys','the air conditioner','the hamburger','his pocket',\n'the bowling ball','school'}\nplural_set = {'the audience', 'my hands', 'the rules', 'her parents','the parents','the children','they'}\nneutral_self_set = {'i', 'we', 'them'} \n\ndef select_replace_neutral(line, chunk, he_she, word):\n pronoun = he_she\n line = re.sub(word, pronoun, line, flags=re.IGNORECASE)\n return line, word, pronoun\n\ndef select_replace(line, chunk):\n pronoun = \"_\" #\"it\"\n is_neutral=False\n word = random.choice(tuple(chunk))\n if(word in male_set): pronoun = \"_\" #\"he\"\n if(word in female_set): pronoun = \"_\" #\"she\"\n if(word in neutral_set): \n pronoun = \"_\" #\"he\"\n is_neutral = True\n if(word in object_set): pronoun = \"_\" #\"it\"\n if(word in plural_set): pronoun = \"_\" #\"they\"\n if(word in neutral_self_set): pronoun = \"_\" #word\n else: pronoun = \"_\"\n\n line = re.sub(word, pronoun, line, flags=re.IGNORECASE)\n return line, word, pronoun, is_neutral\n\ndef prepare_output(each_output, phrase, option1, option2, ans, pronoun, offset1, offset2, pronoun_offset):\n each_output['video-id'] = \"development_new\"+str(count)\n each_output[\"fold-ind\"] = 1000\n each_output[\"startphrase\"] = phrase\n # print(phrase)\n each_output[\"sent1\"] = phrase.split(\"_\")[0]\n each_output[\"sent2\"] = phrase.split(\"_\")[1]\n each_output[\"gold-source\"] = \"gold\"\n each_output[\"ending0\"] = option1\n each_output[\"ending1\"] = option2\n each_output[\"ending2\"] = \"\"\n each_output[\"ending3\"] = \"\"\n if(ans==option1):\n each_output[\"label\"] = 1\n else:\n each_output[\"label\"] = 2\n\ndef get_values(referring_word, union_set, phrase):\n ans = referring_word\n option1 = ans\n union_set.discard(ans)\n option2 = union_set.pop()\n seed(time.time())\n randval = random.randint(0,1)\n if(randval == 0):\n option1, option2 = option2, option1\n offset1 = phrase.lower().find(option1)\n offset2 = phrase.lower().find(option2)\n return ans, option1, option2, offset1, offset2\n\ndef set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset):\n global count\n global pronoun_set\n global output_dict\n count+=1\n each_output = {}\n prepare_output(each_output, phrase, option1, option2, ans, pronoun, offset1, offset2, pronoun_offset)\n pronoun_set.add(ans)\n output_dict[str(count)] = each_output\n # output_dict.add(each_output)\n\nfor row in data.itertuples(index=True, name='Pandas'):\n # print(row)\n textp = row.p\n docp = nlp(textp)\n chunkp = [chunk.text.lower() for chunk in docp.noun_chunks]\n chunkp = set(chunkp)\n\n texta1 = row.a1\n doca1 = nlp(texta1)\n chunka1 = [chunk.text.lower() for chunk in doca1.noun_chunks]\n chunka1 = set(chunka1)\n\n texta2 = row.a2\n doca2 = nlp(texta2)\n chunka2 = [chunk.text.lower() for chunk in doca2.noun_chunks]\n chunka2 = set(chunka2)\n\n line = row.p+\" \"+row.a1+\" \"+row.a2\n intr1 = chunkp.intersection(chunka1)\n intr2 = chunka1.intersection(chunka2)\n intr3 = chunkp.intersection(chunka2)\n\n total_set = intr1.union(intr2, intr3)\n total_length = len(total_set)\n # print(total_set)\n union_set = chunkp.union(chunka1).union(chunka2)\n # change it >0 afterwards\n if (total_length ==2):\n # print(\"hi\")\n while(len(union_set)>1):\n # print(union_set)\n # print(len(intr1), len(intr2), len(intr3))\n if(len(intr1)>0):\n line, referring_word, pronoun,is_neutral = select_replace(row.a1, intr1)\n if(is_neutral):\n # line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"he\", referring_word)\n line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"_\", referring_word)\n phrase = row.p+\" \"+line+\" \"+row.a2\n ans, option1, option2, offset1, offset2 = get_values(referring_word, union_set, phrase)\n pronoun_offset = phrase.lower().find(pronoun)\n set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset)\n \n # line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"she\", referring_word)\n line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"_\", referring_word) \n phrase = row.p+\" \"+line+\" \"+row.a2\n pronoun_offset = phrase.lower().find(pronoun)\n set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset)\n else: \n phrase = row.p+\" \"+line+\" \"+row.a2\n ans, option1, option2, offset1, offset2 = get_values(referring_word, union_set, phrase)\n pronoun_offset = phrase.lower().find(pronoun)\n set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset)\n\n\n elif(len(intr2)>0):\n line, referring_word, pronoun, is_neutral = select_replace(row.a2, intr2)\n if(is_neutral):\n # line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"he\", referring_word)\n line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"_\", referring_word)\n phrase = row.p+\" \"+row.a1+\" \"+line\n ans, option1, option2, offset1, offset2 = get_values(referring_word, union_set, phrase)\n pronoun_offset = phrase.lower().find(pronoun)\n set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset)\n\n # line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"she\", referring_word)\n line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"_\", referring_word)\n phrase = row.p+\" \"+row.a1+\" \"+line\n pronoun_offset = phrase.lower().find(pronoun)\n set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset)\n else:\n phrase = row.p+\" \"+row.a1+\" \"+line\n ans, option1, option2, offset1, offset2 = get_values(referring_word, union_set, phrase)\n pronoun_offset = phrase.lower().find(pronoun)\n set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset)\n\n elif(len(intr2)>0):\n line, referring_word, pronoun, is_neutral = select_replace(row.a2, intr2)\n if(is_neutral):\n # line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"he\", referring_word)\n line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"_\", referring_word)\n phrase = row.p+\" \"+row.a1+\" \"+line\n ans, option1, option2, offset1, offset2 = get_values(referring_word, union_set, phrase)\n pronoun_offset = phrase.lower().find(pronoun)\n set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset)\n\n # line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"she\", referring_word)\n line, referring_word, pronoun = select_replace_neutral(row.a1, intr1,\"_\", referring_word)\n phrase = row.p+\" \"+row.a1+\" \"+line\n pronoun_offset = phrase.lower().find(pronoun)\n set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset)\n else:\n phrase = row.p+\" \"+row.a1+\" \"+line\n ans, option1, option2, offset1, offset2 = get_values(referring_word, union_set, phrase)\n pronoun_offset = phrase.lower().find(pronoun)\n set_values(ans, option1, option2, phrase, pronoun, offset1, offset2, pronoun_offset) \n else:\n break\n \n# print(output_dict)\noutput_df = pd.DataFrame.from_dict(output_dict, orient='index')\n # print(output_df)\n # output_df.drop(output_df.columns[[0]], axis=1) \noutput_df = output_df.loc[:, ~output_df.columns.str.contains('^Unnamed')]\n # print(output_df.columns)\n # print(output_df)\ntrain, test = train_test_split(output_df, test_size=0.2)\ntrain.to_csv('output/train.csv')\ntest.to_csv('output/val.csv')\n# write_json(output_dict, \"model_output2.json\")\nprint(\"Check train.csv and val.csv \")\n # write_csv_from_dict(output_dict, \"model_output.csv\")\n\n\n# print(len(male_set)+len(female_set)+len(neutral_set)+len(object_set)+len(plural_set)+len(neutral_self_set))\n# combined_set = (male_set).union(female_set).union(neutral_set).union(object_set).union(plural_set).union(neutral_self_set)\n# print(len(pronoun_set))\n# # pronoun_set.remove(combined_set)\n# # print(pronoun_set)\n# print(combined_set.difference(pronoun_set))\n# print(pronoun_set.difference(combined_set))","sub_path":"code/dataset_generation_new.py","file_name":"dataset_generation_new.py","file_ext":"py","file_size_in_byte":10649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"549857423","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 30 12:19:54 2019\n\n@author: K-D Marie Auriane\n\"\"\"\n\n#programme pour convertir les heures en minute\n\n#variable x designant le nombre d'heures\n#pour afficher la valeur a la ligne (\\n)\nheures=int(input('entrez une valeur: \\n'))\n\nminutes= heures*60\n\nprint(minutes)\n","sub_path":"6.Capstone-I/300116670.py","file_name":"300116670.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"512770069","text":"from typing import Dict\n\nimport numpy as np\nimport torch\n\n\nfrom allennlp.data.vocabulary import Vocabulary\nfrom allennlp.models import Model\nfrom allennlp.modules.seq2vec_encoders import Seq2VecEncoder\nfrom allennlp.modules.text_field_embedders import TextFieldEmbedder\nfrom allennlp.nn.util import get_text_field_mask\nfrom allennlp.training.metrics import CategoricalAccuracy, F1Measure\n\nfrom overrides import overrides\n\nEMBEDDING_DIM = 128\nHIDDEN_DIM = 128\n\n\n@Model.register(\"lstm_classifier\")\nclass LstmClassifier(Model):\n def __init__(self,\n word_embeddings: TextFieldEmbedder,\n encoder: Seq2VecEncoder,\n vocab: Vocabulary,\n positive_label: int = 4) -> None:\n super().__init__(vocab)\n \n self.word_embeddings = word_embeddings\n\n self.encoder = encoder\n\n \n self.linear = torch.nn.Linear(in_features=encoder.get_output_dim(),\n out_features=vocab.get_vocab_size('labels'))\n\n \n self.accuracy = CategoricalAccuracy()\n self.f1_measure = F1Measure(positive_label)\n\n \n self.loss_function = torch.nn.CrossEntropyLoss()\n\n \n def forward(self,\n tokens: Dict[str, torch.Tensor],\n label: torch.Tensor = None) -> torch.Tensor:\n \n mask = get_text_field_mask(tokens)\n\n \n embeddings = self.word_embeddings(tokens)\n encoder_out = self.encoder(embeddings, mask)\n logits = self.linear(encoder_out)\n\n \n output = {\"logits\": logits}\n if label is not None:\n self.accuracy(logits, label)\n self.f1_measure(logits, label)\n output[\"loss\"] = self.loss_function(logits, label)\n\n return output\n\n def get_metrics(self, reset: bool = False) -> Dict[str, float]:\n precision, recall, f1_measure = self.f1_measure.get_metric(reset)\n return {'accuracy': self.accuracy.get_metric(reset),\n 'precision': precision,\n 'recall': recall,\n 'f1_measure': f1_measure}\n","sub_path":"lib/model/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"231915474","text":"import discord\r\nfrom discord.ext import commands\r\nimport asyncio\r\nimport socket #used to send UDP packets\r\nimport random\r\nimport colorsys\r\nimport time\r\nimport pickle\r\n\r\n#functions needed to decode the message\r\ndef popString(stack):\r\n length = 1+int.from_bytes(stack[:1],byteorder='big')\r\n string = stack[1:length].decode(\"utf-8\")\r\n return stack[length:], string\r\n\r\ndef popInt(stack):\r\n integer = int.from_bytes(stack[:4],byteorder='big')\r\n return stack[4:],integer\r\n\r\ndef parseResponse(response):\r\n response, _ = popString(response) #msg would be server\r\n response, mapName = popString(response)\r\n response, players = popInt(response)\r\n response, wave = popInt(response)\r\n response, version = popInt(response)\r\n response = {'mapName': mapName,\r\n 'players': players,\r\n 'wave': wave,\r\n 'version': version}\r\n return response\r\n\r\ndef ping(host:str, port:int):\r\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n sock.settimeout(4) #request timedout\r\n ms = 'ping failed'\r\n try:\r\n sent = sock.sendto(b'\\xFE\\x01',(host, port)) #send [-2,1] (bytes)\r\n start = time.time()\r\n data, server = sock.recvfrom(128)\r\n ms = '%.d ms' %((time.time()-start)*1000) \r\n finally:\r\n response = {'ping':ms} \r\n sock.close()\r\n if (ms!='ping failed'):\r\n response.update(parseResponse(data))\r\n return response\r\n\r\n\r\nclass MindustryCog:\r\n def __init__(self, bot):\r\n self.bot = bot\r\n self.servers = [\"mindustry.kr\",\"mindustry.indielm.com\"]\r\n\r\n @commands.group(name='mindustry',aliases=[\"m\"])\r\n async def mindustry(self, ctx):\r\n #Subcommand check\r\n if ctx.invoked_subcommand is None:\r\n await ctx.send(\"You haven't sent a mindustry subcommand. To learn how to use this command say `&&help mindustry`.\")\r\n\r\n #LengthOfHostName HostName, LengthOfMapName MapName, PlayerAmount, Wave, Version\r\n @mindustry.command(name='ping')\r\n async def Mping(self,ctx,server:str=None, port:str='6567'):\r\n print(server)\r\n if server is None:\r\n await ctx.send(\"Please specify a server.\")\r\n return\r\n try:\r\n if ':' in server:\r\n ip, port = server.split(':')\r\n else:\r\n ip = server\r\n response = ping(ip, int(port))\r\n randomColour = [int(x*255) for x in colorsys.hsv_to_rgb(random.random(), 1, 1)]\r\n randomColour = discord.Colour.from_rgb(*randomColour)\r\n embed = discord.Embed(title=server,\r\n colour=randomColour)\r\n embed.set_author(name=self.bot.user.display_name,\r\n icon_url=self.bot.user.avatar_url_as(format='png'))\r\n for key in response:\r\n embed.add_field(name=key,\r\n value=response[key])\r\n \r\n embed.set_footer(text=ctx.guild.name,\r\n icon_url=ctx.guild.icon_url_as(format='png'))\r\n await ctx.send(embed=embed)\r\n print(server, response)\r\n except Exception as e:\r\n print(e)\r\n \r\n @mindustry.command(name='servers')\r\n async def MServers(self,ctx):\r\n randomColour = [int(x*255) for x in colorsys.hsv_to_rgb(random.random(), 1, 1)]\r\n randomColour = discord.Colour.from_rgb(*randomColour)\r\n embed = discord.Embed(title=\"Servers:\",\r\n colour=randomColour)\r\n embed.set_author(name=self.bot.user.display_name,\r\n icon_url=self.bot.user.avatar_url_as(format='png'))\r\n embed.add_field(name=\"_*IP*_\",\r\n value=\"*Map*, *Players*, *Wave*\")\r\n for server in self.servers:\r\n try:\r\n if ':' in server:\r\n ip, port = server.split(':')\r\n else:\r\n ip, port = server, '6567'\r\n response = ping(ip, int(port))\r\n if len(response) != 1:\r\n embed.add_field(name=server,\r\n value=f\"{response['mapName']},{response['players']},{response['wave']}\")\r\n else:\r\n embed.add_field(name=server,\r\n value=\"**OFFLINE**\")\r\n\r\n except Exception as e:\r\n print(e)\r\n embed.set_footer(text=ctx.guild.name,\r\n icon_url=ctx.guild.icon_url_as(format='png'))\r\n await ctx.send(embed=embed)\r\n\r\n @mindustry.command(name='certify',aliases=['verify'])\r\n async def MCertify(self,ctx,ip=None):\r\n await ctx.send('not updated yet might cause a crash')\r\n if ip == None:\r\n await ctx.send(\"Please input an ip.\")\r\n return\r\n else:\r\n servers = pickle.load(open(\"verify.data\", \"rb\"))\r\n try:\r\n print(servers[f'{ip}'])\r\n await ctx.send(f\"{ctx.author.mention}, you have already submitted `{ip}` for verification. Please be patient. We will get to it eventually.\")\r\n return\r\n except KeyError:\r\n servers[f'{ip}'] = {'id':len(servers),'host':ctx.author.id,'timeOfRequest':time.time(),'pings':0}\r\n channel = self.bot.get_channel(469612268439601152)\r\n embed = discord.Embed(title=\"New certification request:\",\r\n colour=0x00FFEE)\r\n embed.set_author(name=self.bot.user.display_name,\r\n icon_url=self.bot.user.avatar_url_as(format='png'))\r\n embed.add_field(name='IP',\r\n value=ip)\r\n embed.add_field(name='Requester',\r\n value=f\"{ctx.author.name}#{ctx.author.discriminator}\")\r\n embed.set_footer(text=ctx.guild.name,\r\n icon_url=ctx.guild.icon_url_as(format='png'))\r\n await channel.send(embed=embed)\r\n channel = self.bot.get_channel(471002326824386591)\r\n embed.set_field_at(index=1,name=\"Requester\",\r\n value=f\"{ctx.author.mention}\")\r\n await channel.send(embed=embed)\r\n pickle.dump(servers, open('verify.data','wb'))\r\n serverList = pickle.load(open(\"verify.list\",\"rb\"))\r\n serverList.append(f'{ip}')\r\n pickle.dump(serverList,open('verify.list','wb'))\r\n await ctx.send(f\"I have submitted `{ip}` for verification.\")\r\n for i in range(1,500):\r\n try:\r\n async with websockets.connect(f'ws://{ip}:6568') as websocket:\r\n await websocket.send('ping')\r\n reply = await websocket.recv()\r\n dreply = base64.b64decode(reply)\r\n servers[f'{ip}']['pings'] += 1\r\n except OSError:\r\n adsh = 0\r\n time.sleep(172.8)\r\n if server[f'{ip}']['pings'] < 475:\r\n channel = self.bot.get_channel(469612268439601152)\r\n embed = discord.Embed(title=\"IP Denied:\",\r\n colour=0x990000)\r\n embed.set_author(name=self.bot.user.display_name,\r\n icon_url=self.bot.user.avatar_url_as(format='png'))\r\n embed.add_field(name='IP',\r\n value=ip)\r\n embed.add_field(name='Requester',\r\n value=self.bot.get_user(servers[f\"{ip}\"][\"host\"]).name+'#'+self.bot.get_user(servers[f\"{ip}\"][\"host\"]).discriminator)\r\n embed.add_field(name='Denier',\r\n value=f\"{self.bot.user.mention}\")\r\n embed.add_field(name='Reason',\r\n value=\"Server failed to have 95% uptime.\")\r\n embed.set_footer(text=ctx.guild.name,\r\n icon_url=ctx.guild.icon_url_as(format='png'))\r\n await channel.send(embed=embed)\r\n channel = self.bot.get_channel(471002326824386591)\r\n embed.set_field_at(index=1,name=\"Host\",\r\n value=self.bot.get_user(ctx.author.id).mention)\r\n await channel.send(embed=embed)\r\n servers.pop(ip)\r\n pickle.dump(servers, open('verify.data','wb'))\r\n serverList = pickle.load(open(\"verify.list\",\"rb\"))\r\n serverList.remove(ip)\r\n pickle.dump(serverList,open('verify.list','wb'))\r\n else:\r\n channel = self.bot.get_channel(469612268439601152)\r\n await channel.send(f\"IP `{ip}` has at least 95% uptime.\")\r\n \r\n\r\n @mindustry.command(name='allow',aliases=['approve'])\r\n @commands.has_any_role('Verification Helper')\r\n async def MAllow(self,ctx,ip=None):\r\n if ip == None:\r\n await ctx.send(\"Please input an ip.\")\r\n return\r\n else:\r\n servers = pickle.load(open(\"verify.data\", \"rb\"))\r\n try:\r\n print(servers[f'{ip}'])\r\n except KeyError:\r\n await ctx.send(f\"The ip `{ip}` hasn't been submitted for verification.\")\r\n return\r\n if (servers[f'{ip}']['timeOfRequest']+(60*60*24)) > time.time():\r\n await ctx.send(f\"Please wait at least 24 hours so that uptime can be measured.\")\r\n return\r\n channel = self.bot.get_channel(469612268439601152)\r\n embed = discord.Embed(title=\"IP Verified:\",\r\n colour=0x008800)\r\n #Difficulty, Catching, obtaining high *, Arena, community\r\n embed.set_author(name=self.bot.user.display_name,\r\n icon_url=self.bot.user.avatar_url_as(format='png'))\r\n embed.add_field(name='IP',\r\n value=ip)\r\n embed.add_field(name='Host',\r\n value=self.bot.get_user(servers[f\"{ip}\"][\"host\"]).name+'#'+self.bot.get_user(servers[f\"{ip}\"][\"host\"]).discriminator)\r\n embed.add_field(name='Verifier',\r\n value=f\"{self.bot.get_user(ctx.author.id).mention}\")\r\n embed.set_footer(text=ctx.guild.name,\r\n icon_url=ctx.guild.icon_url_as(format='png'))\r\n await channel.send(embed=embed)\r\n channel = self.bot.get_channel(471002326824386591)\r\n embed.set_field_at(index=1,name=\"Host\",\r\n value=self.bot.get_user(servers[f\"{ip}\"][\"host\"]).mention)\r\n await channel.send(embed=embed)\r\n servers.pop(ip)\r\n pickle.dump(servers, open('verify.data','wb'))\r\n serverList = pickle.load(open(\"verify.list\",\"rb\"))\r\n serverList.remove(ip)\r\n pickle.dump(serverList,open('verify.list','wb'))\r\n \r\n\r\n @mindustry.command(name='queue')\r\n async def MVNext(self,ctx,position=0):\r\n serverList = pickle.load(open(\"verify.list\", \"rb\"))\r\n try: \r\n await ctx.send(serverList[position-1])\r\n except IndexError:\r\n print(serverList)\r\n await ctx.send(\"There isn't an ip at that position\")\r\n\r\n @mindustry.command(name='deny')\r\n @commands.has_any_role('Verification Helper')\r\n async def MDeny(self,ctx,ip=None,*,reason=None):\r\n if ip is None:\r\n await ctx.send(\"Please input an ip.\")\r\n return\r\n elif reason is None:\r\n await ctx.send(\"Please input a reason.\")\r\n return\r\n else:\r\n servers = pickle.load(open(\"verify.data\", \"rb\"))\r\n try:\r\n print(servers[f'{ip}'])\r\n except KeyError:\r\n await ctx.send(f\"The ip `{ip}` hasn't been submitted for verification.\")\r\n return\r\n channel = self.bot.get_channel(469612268439601152)\r\n embed = discord.Embed(title=\"IP Denied:\",\r\n colour=0x990000)\r\n embed.set_author(name=self.bot.user.display_name,\r\n icon_url=self.bot.user.avatar_url_as(format='png'))\r\n embed.add_field(name='IP',\r\n value=ip)\r\n embed.add_field(name='Requester',\r\n value=self.bot.get_user(servers[f\"{ip}\"][\"host\"]).name+'#'+self.bot.get_user(servers[f\"{ip}\"][\"host\"]).discriminator)\r\n embed.add_field(name='Denier',\r\n value=f\"{self.bot.get_user(ctx.author.id).mention}\")\r\n embed.add_field(name='Reason',\r\n value=reason)\r\n embed.set_footer(text=ctx.guild.name,\r\n icon_url=ctx.guild.icon_url_as(format='png'))\r\n await channel.send(embed=embed)\r\n channel = self.bot.get_channel(471002326824386591)\r\n embed.set_field_at(index=1,name=\"Requester\",\r\n value=self.bot.get_user(servers[f\"{ip}\"][\"host\"]).mention)\r\n await channel.send(embed=embed)\r\n servers.pop(ip)\r\n pickle.dump(servers, open('verify.data','wb'))\r\n serverList = pickle.load(open(\"verify.list\",\"rb\"))\r\n serverList.remove(ip)\r\n pickle.dump(serverList,open('verify.list','wb'))\r\n\r\n @mindustry.command(name='position')\r\n async def MVProgress(self,ctx,ip):\r\n servers = pickle.load(open(\"verify.list\", \"rb\"))\r\n for index in range(len(servers)):\r\n if servers[index] == ip:\r\n await ctx.send(f\"Your ip is at position {index+1}.\")\r\n return\r\n await ctx.send(\"I couldn't find that ip in the verification queue.\")\r\n\r\n @mindustry.command(name='v_reset')\r\n @commands.has_any_role('Verification Helper')\r\n async def MVReset(self,ctx):\r\n #{'ip':{'id':0,'host':hostID,'timeOfRequest':time.time,'pings':500}}\r\n servers = {}\r\n serverList = []\r\n pickle.dump(servers, open('verify.data','wb'))\r\n pickle.dump(serverList, open('verify.list','wb'))\r\n\r\n @mindustry.command(name='vote')\r\n async def MVote(self,ctx,ip=None,score=None):\r\n if ip is None:\r\n await ctx.send(\"Please input an ip.\")\r\n return\r\n if score is None:\r\n await ctx.send(\"Please input a score.\")\r\n return\r\n try:\r\n if int(score) < 0 or int(score) > 10:\r\n await ctx.send(\"Please input a valid score.\")\r\n return\r\n except ValueError:\r\n await ctx.send(\"Please input a valid score.\")\r\n return\r\n servers = pickle.load(open(\"verified.data\", \"rb\"))\r\n try:\r\n currServ = servers[f'{ip}']\r\n except KeyError:\r\n await ctx.send(f\"The ip `{ip}` hasn't been verified.\")\r\n return\r\n for item in range(len(servers[f'{ip}']['votes'])):\r\n if servers[f'{ip}']['votes'][item][1] == ctx.author.id:\r\n servers[f'{ip}']['votes'][item][0] = score\r\n if len(servers[f'{ip}']['votes']) > 4:\r\n servers[f'{ip}']['score'] = 0\r\n for item in servers[f'{ip}']['votes']:\r\n servers[f'{ip}']['score'] += item[0]\r\n servers[f'{ip}']['score'] = servers[f'{ip}']['score'] / len(servers[f'{ip}']['votes'])\r\n pickle.dump(servers, open('verified.data','wb'))\r\n await ctx.send(\"Vote changed\")\r\n return\r\n servers[f'{ip}']['votes'].append([int(score),ctx.author.id])\r\n if len(servers[f'{ip}']['votes']) > 4:\r\n servers[f'{ip}']['score'] = 0\r\n for item in servers[f'{ip}']['votes']:\r\n servers[f'{ip}']['score'] += item[0]\r\n servers[f'{ip}']['score'] = servers[f'{ip}']['score'] / len(servers[f'{ip}']['votes'])\r\n pickle.dump(servers, open('verified.data','wb'))\r\n await ctx.send(\"Vote submitted\")\r\n\r\n @mindustry.command(name='info')\r\n async def MServerInfo(self,ctx,ip=None):\r\n if ip is None:\r\n await ctx.send(\"Please input an ip.\")\r\n return\r\n servers = pickle.load(open(\"verified.data\", \"rb\"))\r\n try:\r\n currServ = servers[f'{ip}']\r\n except KeyError:\r\n await ctx.send(f\"The ip `{ip}` hasn't been verified.\")\r\n return\r\n embed = discord.Embed(title=f\"{ip}'s info:\")\r\n embed.set_author(name=self.bot.get_user(servers[f'{ip}']['host']).display_name,\r\n icon_url=self.bot.get_user(servers[f'{ip}']['host']).avatar_url_as(format='png'))\r\n if servers[f'{ip}']['score'] == -1:\r\n embed.add_field(name='Score',\r\n value='Needs 5 votes to score')\r\n else:\r\n embed.add_field(name='Score',\r\n value=servers[f'{ip}']['score'])\r\n embed.set_footer(text=ctx.guild.name,\r\n icon_url=ctx.guild.icon_url_as(format='png'))\r\n await ctx.send(embed=embed)\r\n\r\n @mindustry.command(name='add')\r\n @commands.has_any_role('Verification Helper')\r\n async def MServerAdd(self,ctx,ip=None,host:discord.Member=None):\r\n if ip is None or host is None:\r\n await ctx.send(\"Please input __all__ required data.\")\r\n server=pickle.load(open('verified.data','rb'))\r\n server[f'{ip}'] = {'host':host.id,'votes':[],'score':-1}\r\n pickle.dump(server, open('verified.data','wb'))\r\n await ctx.send(\"Server added.\")\r\n\r\n @mindustry.command(name='remove')\r\n @commands.has_any_role('Verification Helper')\r\n async def MServerRemove(self,ctx,ip=None):\r\n if ip is None:\r\n await ctx.send(\"Please input an ip.\")\r\n return\r\n servers = pickle.load(open(\"verified.data\", \"rb\"))\r\n try:\r\n currServ = servers[f'{ip}']\r\n except KeyError:\r\n await ctx.send(f\"The ip `{ip}` hasn't been verified.\")\r\n return\r\n servers.pop(f'{ip}')\r\n pickle.dump(servers, open('verified.data','wb'))\r\n await ctx.send(\"Server removed.\")\r\n\r\n @mindustry.command(name='clear')\r\n @commands.has_any_role('Verification Helper')\r\n async def MVServerClear(self,ctx):\r\n servers = {}\r\n pickle.dump(servers, open('verified.data','wb'))\r\n\r\n @mindustry.command(name='edit')\r\n @commands.has_any_role('Verification Helper', 'Verified Host')\r\n async def MServerEdit(self,ctx):\r\n await ctx.send(\"There isn't any data to edit.\")\r\n \r\n# The setup fucntion below is neccesarry. Remember we give bot.add_cog() the name of the class in this case MembersCog.\r\n# When we load the cog, we use the name of the file.\r\ndef setup(bot):\r\n bot.add_cog(MindustryCog(bot))\r\n","sub_path":"cogs/mindustry.py","file_name":"mindustry.py","file_ext":"py","file_size_in_byte":18983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"570161009","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\ndef input_string(st):\n main_dicti = {}\n jj = []\n for i in st:\n if i not in main_dicti:\n main_dicti[i] = 1\n else:\n main_dicti[i]+=1 \n # - sign used to descending order sort in lambda functions\n jj = sorted(main_dicti.items(), key=lambda x:(-x[1],x[0]))\n for k in range(0,3):\n print(jj[k][0],jj[k][1])\n \n\n\nif __name__ == '__main__':\n s = input()\n input_string(s)\n","sub_path":"hackerrank/e_18_company_log.py","file_name":"e_18_company_log.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"238503960","text":"import requests\n\n\nclass Person(object):\n def __init__(self, name=None, email=None, phone=None, website=None):\n self.full_name = name\n self.email = email\n self.phone = phone\n self.website = website\n self.first_name, self.last_name = name.split(' ', 1)\n\n def contact_info(self):\n return self.full_name + ' || ' + self.email + ' || ' + self.phone\n\n @classmethod\n def getAll(self):\n database = requests.get('https://jsonplaceholder.typicode.com/users')\n result = []\n json_list = database.json()\n for item in json_list:\n person = Person(\n item['name'], item['email'],\n item['phone'], item['website']\n )\n result.append(person)\n return result\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"391680164","text":"import numpy as np\nimport cv2\nimport imutils\nimport serial\nimport struct\n\nwinName = \"Movement Indicator\"\ncam1= cv2.VideoCapture(1) #Motion Threshold\n\n#setting up 2 cameras in order to\n\nLowercolor = (29, 86, 6)\nUppercolor = (64, 255, 255)\n\n\ndef diffImg(t0, t1, t2):\n d1 = cv2.absdiff(t2, t1)\n d2 = cv2.absdiff(t1, t0)\n added = cv2.add(d1, d2)\n thresholdImage = cv2.threshold(added, 30, 255, cv2.THRESH_BINARY)[1]\n return thresholdImage\n #cv2.bitwise_and\ndef packIntegerAsULong(value):\n \"\"\"Packs a python 4 byte unsigned integer to an arduino unsigned long\"\"\"\n return struct.pack('I', value) #should check bounds\n\n#t_minus = cv2.cvtColor(cam1.read()[1], cv2.COLOR_RGB2GRAY)\n#t = cv2.cvtColor(cam1.read()[1], cv2.COLOR_RGB2GRAY)\n#t_plus = cv2.cvtColor(cam1.read()[1], cv2.COLOR_RGB2GRAY)\nser = serial.Serial(11,9600,timeout =1)\nwhile(True):\n kernel = np.ones((5, 5), np.uint8)\n _,frame = cam1.read()\n mainbase = imutils.resize(frame, width=600)\n # motioncam imageload\n #t_minus = t\n #t = t_plus\n #t_plus = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)\n\n #Colourcam Imageload\n #isol_read_blur = cv2.dilate(mainbase, kernel, iterations=1)\n isol_colour = cv2.cvtColor(mainbase, cv2.COLOR_BGR2HSV)\n ####################################################################\n\n colourcam = cv2.inRange(isol_colour, Lowercolor, Uppercolor)\n\n #motioncam = diffImg(t_minus, t, t_plus)\n\n #motioncam = cv2.erode(motioncam, None, iterations=2)\n colourcam = cv2.erode(colourcam, None, iterations=2)\n #motioncam = cv2.dilate(motioncam, None, iterations=2)\n colourcam = cv2.dilate(colourcam, None, iterations=2)\n\n cnts = cv2.findContours(colourcam.copy(), cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_SIMPLE)[-2]\n center = None\n\n if len(cnts) > 0:\n # find the largest contour in the mask, then use\n # it to compute the minimum enclosing circle and\n # centroid\n c = max(cnts, key=cv2.contourArea)\n ((x, y), radius) = cv2.minEnclosingCircle(c)\n M = cv2.moments(c)\n center = (int(M[\"m10\"] / M[\"m00\"]), int(M[\"m01\"] / M[\"m00\"]))\n angleHor = int(center[0] / 600 * 60)\n angleVer = int(center[1] / 500 * 60)\n\n\n # only proceed if the radius meets a minimum size\n if radius > 10:\n # draw the circle and centroid on the frame,\n # then update the list of tracked points\n cv2.circle(frame, (int(x), int(y)), int(radius),\n (0, 255, 255), 2)\n cv2.circle(frame, center, 5, (0, 0, 255), -1)\n else:\n angleHor = 30\n angleVer = 30\n\n key = cv2.waitKey(10)\n if key == 27:\n break\n cv2.destroyWindow(winName)\n\n #image, contours, hierarchy = cv2.findContours(Targetcam, cv2.RETR_EXTERNAL , cv2.CHAIN_APPROX_SIMPLE)\n #Targetcam = cv2.drawContours(Targetcam, contours, -1, (0, 255, 0), 3)\n cv2.imshow(\"Image\", frame)\n cv2.waitKey(10)\n\n #Object coordinate recognition is now complete. Now head on to making servo coordinates\n height, width = frame.shape[:2]\n\n ser.write(struct.pack('>BB',angleHor,angleVer))\n\n# When everything done, release the capture\n\ncv2.destroyAllWindows()","sub_path":"sourceAA.py","file_name":"sourceAA.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"372584664","text":"from grid.Grid import Grid\nfrom cats.astarcat.AstarCat import AstarCat\nfrom cats.catshelper.DistanceCalculator import DistanceTypes\n\nfrom util.Helper import Help\n\n#DO NOT REUSE\n\nclass ScoreCalculator:\n def __init__(self, walls, goals, cat):\n self.walls = set(walls)\n self.goals = set(goals)\n self.cat = cat\n\n self.grid = Grid(goals, walls, (5, 5), rows=11, cols=11)\n\n self.dist = DistanceTypes.HEX\n\n astar_cat = AstarCat(\n max_iterations=200,\n grid=self.grid,\n gWeight=1,\n hWeight=1,\n fWeight=1,\n distanceType=self.dist\n )\n self.cat_obj = astar_cat\n self.score_range = (0, 6)\n\n\n def all_positions(self):\n return [(i,j) for i in range(0,11) for j in range(0,11)]\n\n\n def metadata(self):\n\n cell_set = self.all_positions()\n\n process_data = {\n 'data':{},\n 'normalization':{\n 'min_hits_min': 0,\n 'min_hits_max': 0,\n\n 'path_len_min': 0,\n 'path_len_max': 0,\n\n 'cat_dist_min' : 0,\n 'cat_dist_max' : 0,\n\n 'leads_to_goals_min': 0,\n 'leads_to_goals_max': 0,\n\n 'in_diamond_min': 0,\n 'in_diamond_max': 0,\n\n 'catcher_panic_min': 0,\n 'catcher_panic_max': 0,\n\n 'squares_min': 0,\n 'squares_max': 0,\n }\n }\n\n full_path = []\n full_min_hits = []\n full_cat_dist = [1]\n full_lead_to_goal_count = []\n full_is_diamond = [0,1]\n full_catcher_panic = []\n full_squares = []\n full_cat_trapper = [7]\n \n for elem in cell_set:\n\n local_diff = []\n local_path = []\n\n if elem in self.walls:\n continue\n\n for goal in [goal for goal in self.goals if goal not in self.walls]:\n\n self.cat_obj.reset()\n self.cat_obj.find_path(goal, elem)\n if self.cat_obj.path is None:\n continue\n dist = self.cat_obj.path.get_distance()\n diff = self.cat_obj.path.get_difficulty()\n\n if not elem in Help.valid_goals(goals=self.goals, walls=self.walls):\n local_path.append(dist)\n\n local_diff.append(diff)\n\n\n\n # Aqui local path e diff tem a lista de dados do nó para cada goal\n #local_path.sort()\n #local_diff.sort()\n\n if len(local_path) == 0:\n local_path.append(0)\n\n min_hits_count = Help.count(local_path, [min(local_path)])\n\n if elem not in process_data['data']:\n process_data['data'][elem] = {}\n\n\n process_data['data'][elem]['min_hits'] = min_hits_count\n process_data['data'][elem]['path_len'] = Help.minimum_average(local_path, 5)\n\n lead_to_goals = Help.count_lead_goals(cell=elem, cat=self.cat, goals=self.goals, walls=self.walls)\n\n process_data['data'][elem]['leads_to_goals'] = lead_to_goals\n in_diamond=Help.in_diamond(elem)\n process_data['data'][elem]['in_diamond'] = in_diamond\n\n process_data['data'][elem]['catcher_panic'] = 0\n\n if elem in Help.valid_goals(goals=self.goals, walls=self.walls) and \\\n self.cat in Help.neibs_pos(elem, self.walls, self.cat, False):\n process_data['data'][elem]['catcher_panic'] = 1\n\n process_data['data'][elem]['squares'] = 0\n\n if elem[0] % 3 == 0:\n process_data['data'][elem]['squares'] += 5\n if elem[1] % 3 == 0:\n process_data['data'][elem]['squares'] += 5\n\n if elem[0] % 2 == 0:\n process_data['data'][elem]['squares'] += 1\n if elem[1] % 2 == 0:\n process_data['data'][elem]['squares'] += 1\n\n full_squares.append(process_data['data'][elem]['squares'])\n\n walkables = 0\n n = set(Help.neibs_pos(elem, self.walls, self.cat, exclude_non_walkable = False))\n\n if self.cat in n:\n exitforcat = len(Help.neibs_pos(self.cat, self.walls, self.cat, exclude_non_walkable=True))\n\n if exitforcat == 1:\n walkables = 7\n\n elif exitforcat == 2:\n walkables = 2\n\n elif exitforcat == 3:\n walkables = 1\n\n\n\n process_data['data'][elem]['cat_trap'] = walkables\n full_cat_trapper.append(walkables)\n\n full_path.extend( local_path[ 0:min(len(local_path), 3)] )\n full_min_hits.append( min_hits_count )\n full_lead_to_goal_count.append(lead_to_goals)\n full_is_diamond.append(in_diamond)\n full_catcher_panic.append(process_data['data'][elem]['catcher_panic'])\n\n for position, data in process_data['data'].items():\n self.cat_obj.reset()\n # goal_cell = self.grid.get_cell(goal)\n self.cat_obj.find_path(position, self.cat)\n\n if self.cat_obj.path is None:\n data['cat_dist'] = 20\n full_cat_dist.append(data['cat_dist'])\n continue\n\n dist = self.cat_obj.path.get_distance()\n data['cat_dist'] = dist\n full_cat_dist.append(data['cat_dist'])\n\n process_data['normalization']['min_hits_min'] = min(full_min_hits)\n process_data['normalization']['min_hits_max'] = max(full_min_hits)\n\n process_data['normalization']['path_len_min'] = min(full_path)\n process_data['normalization']['path_len_max'] = max(full_path)\n\n process_data['normalization']['cat_dist_min'] = min(full_cat_dist)\n process_data['normalization']['cat_dist_max'] = max(full_cat_dist)\n\n process_data['normalization']['leads_to_goals_min'] = min(full_lead_to_goal_count)\n process_data['normalization']['leads_to_goals_max'] = max(full_lead_to_goal_count)\n\n process_data['normalization']['in_diamond_min'] = min(full_is_diamond)\n process_data['normalization']['in_diamond_max'] = max(full_is_diamond)\n\n process_data['normalization']['catcher_panic_min'] = min(full_catcher_panic)\n process_data['normalization']['catcher_panic_max'] = max(full_catcher_panic)\n\n process_data['normalization']['squares_min'] = min(full_squares)\n process_data['normalization']['squares_max'] = max(full_squares)\n\n process_data['normalization']['cat_trap_min'] = min(full_cat_trapper)\n process_data['normalization']['cat_trap_max'] = max(full_cat_trapper)\n\n return process_data\n\n\n def scores(self, score_range = (0,50)):\n\n md = self.metadata()\n self.score_range = score_range\n\n norm = md['normalization']\n elems = md['data']\n\n answer = {}\n\n for elem, data in elems.items():\n\n s1_path_len = Help.normalize(\n data['path_len'],\n norm['path_len_min'],\n norm['path_len_max'],\n reversed=True,\n )\n\n s2_min_hits = Help.normalize(\n data['min_hits'],\n norm['min_hits_min'],\n norm['min_hits_max'],\n reversed=False,\n )\n\n s3_cat_dist = Help.normalize(\n data['cat_dist'],\n norm['cat_dist_min'],\n norm['cat_dist_max'],\n reversed=True,\n )\n\n s4_lead_to_goal = Help.normalize(\n data['leads_to_goals'],\n norm['leads_to_goals_min'],\n norm['leads_to_goals_max'],\n reversed=False,\n )\n\n s5_in_diamond = Help.normalize(\n data['in_diamond'],\n norm['in_diamond_min'],\n norm['in_diamond_max'],\n reversed=False,\n )\n\n s6_catcher_panic = Help.normalize(\n data['catcher_panic'],\n norm['catcher_panic_min'],\n norm['catcher_panic_max'],\n reversed=False,\n )\n\n s7_squares = Help.normalize(\n data['squares'],\n norm['squares_min'],\n norm['squares_max'],\n reversed=False,\n )\n\n s8_cat_trap = Help.normalize(\n data['cat_trap'],\n norm['cat_trap_min'],\n norm['cat_trap_max'],\n reversed=False,\n )\n\n #score = (s1_path_len/2) + (s2_min_hits/3) + (s3_cat_dist * 2) + s4_lead_to_goal + (s5_in_diamond/2) + (3*s6_catcher_panic)\n score = ( s3_cat_dist * 20 ) + \\\n ( s2_min_hits * 2 ) + \\\n ( s4_lead_to_goal * .8 ) + \\\n ( s5_in_diamond * 1 ) + \\\n ( s6_catcher_panic * 10 ) + \\\n ( s7_squares * 1 ) + \\\n ( s8_cat_trap * 5 ) + \\\n ( (1+s3_cat_dist*4) * (1+s4_lead_to_goal) * 2 )\n\n if score == -0.0:\n score = 0.0\n\n cell = self.grid.get_cell(elem)\n cell.set_score(score)\n\n\n answer[(elem, cell)] = {\n 's1_path_len':s1_path_len,\n 's2_min_hits':s2_min_hits,\n 's3_cat_dist':s3_cat_dist,\n 'score' : score,\n }\n\n return answer\n","sub_path":"Project4/entrega_final/Pegador_novo/scores_calculator_catcher.py","file_name":"scores_calculator_catcher.py","file_ext":"py","file_size_in_byte":9566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"109574418","text":"\"\"\"\n@author: Duy Le \n\"\"\"\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport pandas as pd\nimport segmentation_models_pytorch as smp\nimport torch\nimport torch.nn.functional as F\nfrom torch.optim.lr_scheduler import CyclicLR, ReduceLROnPlateau\nfrom torch.utils.data import DataLoader\nimport torch.nn as nn\nfrom pytorch_toolbelt.utils.catalyst import (\n HyperParametersCallback,\n draw_binary_segmentation_predictions,\n ShowPolarBatchesCallback,\n)\nfrom catalyst.contrib.nn import OneCycleLRWithWarmup\nfrom catalyst import dl, metrics\nfrom catalyst.contrib.callbacks.wandb_logger import WandbLogger\nfrom catalyst.dl import SupervisedRunner, CriterionCallback, EarlyStoppingCallback, SchedulerCallback, MetricAggregationCallback, IouCallback, DiceCallback\nfrom catalyst import utils\nfrom functools import partial\nfrom collections import OrderedDict\nfrom pathlib import Path\nfrom typing import List, Union, Tuple\nimport os\nimport json\nimport logging\nlogging.basicConfig(level=logging.INFO, format='')\n\nfrom . import util\nfrom .util import lesion_dict\nfrom ..data import *\nfrom .scheduler import get_scheduler\nfrom .optim import get_optimizer\nfrom .losses import get_loss, WeightedBCEWithLogits\nfrom ..data import OneLesionSegmentation, CLASS_COLORS, CLASS_NAMES\nfrom . import archs\n\ndef get_model(params, model_name):\n \n # Model return logit values\n model = getattr(smp, model_name)(\n **params\n )\n\n return model\n\ndef get_loader(\n images: Union[List[Path], Tuple[List[Path]]],\n is_gray: bool,\n random_state: int,\n masks: Union[List[Path], Tuple[List[Path]]] = None,\n valid_size: float = 0.2,\n batch_size: int = 4,\n val_batch_size: int = 8,\n num_workers: int = 4,\n train_transforms_fn=None,\n valid_transforms_fn=None,\n preprocessing_fn=None,\n ben_method = None,\n mode='binary',\n data_type = 'tile'\n): \n if isinstance(images, List):\n if data_type == 'all':\n indices = np.arange(len(images))\n\n train_indices, valid_indices = train_test_split(\n indices, test_size=valid_size, random_state=random_state, shuffle=True)\n\n np_images = np.array(images)\n train_imgs = np_images[train_indices].tolist()\n valid_imgs = np_images[valid_indices].tolist()\n else:\n train_df = pd.read_csv('data/processed/IDRiD/train/EX/img_mask.csv')\n train_df = train_df.sample(frac=1).reset_index(drop=True)\n train_imgs= train_df.loc[:, 'img'].values.tolist()\n train_imgs = [Path('/'.join(list(Path(path).parts[2:])) + '/') for path in train_imgs]\n train_masks = train_df.loc[:, 'mask'].values.tolist()\n train_masks = [Path('/'.join(list(Path(path).parts[2:])) + '/') for path in train_masks]\n \n val_df = pd.read_csv('data/processed/IDRiD/val/EX/img_mask.csv')\n val_df = val_df.sample(frac=1).reset_index(drop=True)\n valid_imgs= val_df.loc[:, 'img'].values.tolist()\n valid_imgs = [Path('/'.join(list(Path(path).parts[2:])) + '/') for path in valid_imgs]\n valid_masks = val_df.loc[:, 'mask'].values.tolist()\n valid_masks = [Path('/'.join(list(Path(path).parts[2:])) + '/') for path in valid_masks]\n else:\n if data_type == 'all':\n train_imgs = images[0]\n valid_imgs = images[1]\n else:\n pass\n \n if mode == 'binary':\n if isinstance(masks, List):\n if data_type == 'all':\n np_masks = np.array(masks)\n train_masks = np_masks[train_indices].tolist()\n valid_masks = np_masks[valid_indices].tolist()\n else:\n pass\n else:\n if data_type == 'all':\n train_masks = masks[0]\n valid_masks = masks[1]\n else:\n pass\n \n train_dataset = OneLesionSegmentation(\n train_imgs,\n is_gray,\n masks=train_masks,\n transform=train_transforms_fn,\n preprocessing_fn=preprocessing_fn,\n ben_transform = ben_method,\n data_type = data_type\n )\n\n valid_dataset = OneLesionSegmentation(\n valid_imgs,\n is_gray,\n masks=valid_masks,\n transform=valid_transforms_fn,\n preprocessing_fn=preprocessing_fn,\n ben_transform = ben_method,\n data_type = data_type\n )\n\n train_loader = DataLoader(\n train_dataset,\n batch_size=batch_size,\n num_workers=num_workers,\n shuffle=True,\n pin_memory=True,\n drop_last=True\n )\n\n valid_loader = DataLoader(\n valid_dataset,\n batch_size=val_batch_size,\n num_workers=num_workers,\n shuffle=True,\n pin_memory=True,\n drop_last=False\n )\n\n loaders = OrderedDict()\n loaders['train'] = train_loader\n loaders['valid'] = valid_loader\n\n log_info = [['train', 'valid'], [[len(train_loader), len(valid_loader)], [\n len(train_dataset), len(valid_dataset)]]]\n\n return loaders, log_info\n\n\ndef train_model(exp_name, configs, seed):\n torch.autograd.set_detect_anomaly(True)\n\n TRAIN_IMG_DIRS = configs['train_img_path']\n TRAIN_MASK_DIRS = configs['train_mask_path']\n\n # Get model\n use_smp = True\n if hasattr(smp, configs['model_name']):\n model = get_model(\n configs['model_params'], configs['model_name'])\n elif configs['model_name'] == \"TransUnet\":\n from self_attention_cv.transunet import TransUnet\n model = TransUnet(**configs['model_params'])\n use_smp=False\n else:\n model = archs.get_model(\n model_name=configs['model_name'], \n params = configs['model_params'])\n use_smp = False\n preprocessing_fn, mean, std = archs.get_preprocessing_fn(dataset_name=configs['dataset_name'], grayscale=configs['gray'])\n\n #Define transform (augemntation)\n Transform = get_transform(configs['augmentation'])\n transforms = Transform(\n configs['scale_size'],\n preprocessing_fn=preprocessing_fn\n )\n\n train_transform = transforms.train_transform()\n val_transform = transforms.validation_transform()\n preprocessing = transforms.get_preprocessing()\n\n if configs['data_mode'] == 'binary':\n ex_dirs, mask_dirs = util.get_datapath(\n img_path=TRAIN_IMG_DIRS, mask_path=TRAIN_MASK_DIRS, lesion_type=configs['lesion_type'])\n\n util.log_pretty_table(['full_img_paths', 'full_mask_paths'], [\n [len(ex_dirs), len(mask_dirs)]])\n elif configs['data_mode'] == 'multiclass':\n pass\n else:\n ex_dirs = list(TRAIN_IMG_DIRS.glob('*.jpg'))\n mask_dirs = None\n\n # Get data loader\n if configs['use_ben_transform']:\n ben_transform = load_ben_color\n else:\n ben_transform = None\n\n loader, log_info = get_loader(\n images=ex_dirs,\n is_gray=configs['gray'],\n masks=mask_dirs,\n random_state=seed,\n batch_size=configs['batch_size'],\n val_batch_size=configs['val_batch_size'],\n num_workers=0,\n train_transforms_fn=train_transform,\n valid_transforms_fn=val_transform,\n preprocessing_fn=preprocessing,\n ben_method = ben_transform,\n mode=configs['data_mode'],\n data_type=configs['data_type']\n )\n\n #Visualize on terminal\n util.log_pretty_table(log_info[0], log_info[1])\n\n if use_smp:\n if configs['finetune']:\n #Free all weights in the encoder of model\n for param in model.encoder.parameters():\n param.requires_grad = False\n if configs['model_params']['encoder_weights'] is not None:\n bn_types = nn.BatchNorm2d\n #Disable batchnorm update\n for m in model.encoder.modules():\n if isinstance(m, bn_types):\n m.eval()\n\n param_group = model.get_paramgroup(configs['learning_rate_decode'], configs['weight_decay'])\n trainable, total = model.get_num_parameters()\n # param_group = []\n # if hasattr(model, 'encoder'):\n # encoder_params = filter(lambda p: p.requires_grad, model.encoder.parameters())\n # param_group += [{'params': encoder_params, 'lr': configs['learning_rate']}] \n # if hasattr(model, 'decoder'):\n # decoder_params = filter(lambda p: p.requires_grad, model.decoder.parameters())\n # param_group += [{'params': decoder_params}] \n # if hasattr(model, 'segmentation_head'):\n # head_params = filter(lambda p: p.requires_grad, model.segmentation_head.parameters())\n # param_group += [{'params': head_params}] \n # if hasattr(model, 'supervision'):\n # deep_params = filter(lambda p: p.requires_grad, model.supervision.parameters())\n # param_group += [{'params': deep_params}] \n # if len(param_group) == 0:\n # param_group = [{'params': filter(lambda p: p.requires_grad, model.parameters())}]\n\n # total = int(sum(p.numel() for p in model.parameters()))\n # trainable = int(sum(p.numel() for p in model.parameters() if p.requires_grad))\n count_parameters = {\"total\": total, \"trainable\": trainable}\n\n logging.info(\n f'[INFO] total and trainable parameters in the model {count_parameters}')\n \n #Set optimizer\n optimizer = get_optimizer(\n configs['optimizer'], param_group, configs['learning_rate_decode'], configs['weight_decay'])\n #Set learning scheduler\n scheduler = get_scheduler(\n configs['scheduler'], optimizer, configs['learning_rate'], configs['num_epochs'],\n batches_in_epoch=len(loader['train']), mode=configs['mode']\n )\n #Set loss\n criterion = {}\n for loss_name in configs['criterion']:\n if loss_name == 'wbce':\n pos_weights = torch.tensor(configs['pos_weights'], device=utils.get_device())\n loss_fn = WeightedBCEWithLogits(pos_weights=pos_weights)\n else:\n loss_fn = get_loss(loss_name)\n criterion[loss_name] = loss_fn\n\n #Define callbacks\n callbacks = []\n losses = []\n for loss_name, loss_weight in configs['criterion'].items():\n criterion_callback = CriterionCallback(\n input_key=\"mask\",\n output_key=\"logits\",\n criterion_key=loss_name,\n prefix=\"loss_\"+loss_name,\n multiplier=float(loss_weight)\n )\n\n callbacks.append(criterion_callback)\n losses.append(criterion_callback.prefix)\n\n callbacks += [MetricAggregationCallback(\n prefix=\"loss\",\n mode=\"sum\",\n metrics=losses\n )]\n\n if isinstance(scheduler, (CyclicLR, OneCycleLRWithWarmup)):\n callbacks += [SchedulerCallback(mode=\"batch\")]\n elif isinstance(scheduler, (ReduceLROnPlateau)):\n callbacks += [SchedulerCallback(reduced_metric=configs['metric'])]\n\n hyper_callbacks = HyperParametersCallback(configs)\n\n if configs['data_mode'] == 'binary':\n image_format = 'gray' if configs['gray'] else 'rgb'\n visualize_predictions = partial(\n draw_binary_segmentation_predictions, image_key=\"image\", targets_key=\"mask\", mean=mean, std=std, image_format=image_format\n )\n # elif configs['data_mode'] == 'multilabel':\n # visualize_predictions = partial(\n # draw_multilabel_segmentation_predictions, image_key=\"image\", targets_key=\"mask\", class_colors=CLASS_COLORS\n # )\n\n show_batches_1 = ShowPolarBatchesCallback(\n visualize_predictions, metric=\"iou\", minimize=False)\n\n # show_batches_2 = ShowPolarBatchesCallback(\n # visualize_predictions, metric=\"loss\", minimize=True)\n\n early_stopping = EarlyStoppingCallback(\n patience=20, metric=configs['metric'], minimize=False)\n\n iou_scores = IouCallback(\n input_key=\"mask\",\n activation=\"Sigmoid\",\n threshold=0.5\n )\n\n dice_scores = DiceCallback(\n input_key=\"mask\",\n activation=\"Sigmoid\",\n threshold=0.5\n )\n\n # aucpr_scores = AucPRMetricCallback(\n # input_key=\"mask\",\n # )\n\n # aucroc_scores = RocAucMetricCallback(\n # input_key=\"mask\",\n # )\n #End define\n # if configs['resume'] is not None:\n # exp_name = configs['resume'].split(os.path.sep)[-3]\n\n prefix = f\"{configs['lesion_type']}/{exp_name}\"\n log_dir = os.path.join(\"models/\", configs['dataset_name'], prefix)\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n\n # if configs['kfold']:\n # logger = WandbLogger(project=lesion_dict[configs['lesion_type']].project_name,\n # name=)\n\n logger = WandbLogger(project=lesion_dict[configs['lesion_type']].project_name,\n name=exp_name)\n\n\n #Save config as JSON format\n with open(os.path.join(log_dir, 'config.json'), 'w') as f:\n configs['train_img_path'] = str(configs['train_img_path'])\n configs['train_mask_path'] = str(configs['train_mask_path'])\n json.dump(configs, f)\n\n callbacks += [hyper_callbacks, early_stopping,\n iou_scores, dice_scores]\n\n \n # class CustomRunner(dl.SupervisedRunner):\n # def _handle_batch(self, batch):\n # x, y = batch\n\n # y_pred = self.model(x)\n # pass\n\n if configs['is_fp16']:\n fp16_params = dict(amp=True) # params for FP16\n else:\n fp16_params = None\n \n # model training\n if not configs['deep_supervision']:\n runner = SupervisedRunner(\n device=utils.get_device(), input_key=\"image\", input_target_key=\"mask\")\n\n runner.train(\n model=model,\n criterion=criterion,\n optimizer=optimizer,\n callbacks=callbacks,\n logdir=log_dir,\n loaders=loader,\n num_epochs=configs['num_epochs'],\n scheduler=scheduler,\n main_metric=configs['metric'],\n minimize_metric=False,\n timeit=True,\n fp16=fp16_params,\n resume=configs['resume_path'],\n verbose=True,\n )\n else:\n callbacks = []\n if isinstance(scheduler, (CyclicLR, OneCycleLRWithWarmup)):\n callbacks += [SchedulerCallback(mode=\"batch\")]\n elif isinstance(scheduler, (ReduceLROnPlateau)):\n callbacks += [SchedulerCallback(reduced_metric=configs['metric'])]\n\n hyper_callbacks = HyperParametersCallback(configs)\n\n optim_cb = dl.OptimizerCallback(\n metric_key=\"loss\", \n accumulation_steps=1, \n grad_clip_params=None\n )\n \n callbacks += [optim_cb, hyper_callbacks, early_stopping, logger]\n\n def get_pyramid(mask: torch.Tensor, height, shape_list, include_final_mask=False):\n with torch.no_grad():\n if include_final_mask:\n masks = [mask]\n big_mask = masks[-1]\n else:\n masks = []\n big_mask = mask\n for _, shape in zip(range(height), shape_list):\n small_mask = F.adaptive_avg_pool2d(big_mask, shape)\n masks.append(small_mask)\n big_mask = masks[-1]\n\n targets = []\n for mask in masks:\n targets.append(mask)\n\n return targets\n\n class CustomRunner(dl.Runner):\n def _handle_batch(self, batch):\n results = batch\n x = results['image']\n y = results['mask']\n y_hat, y_hat_levels = self.model(x)\n shape_list =[]\n for level in y_hat_levels:\n shape_list.append(np.array(level.shape[2:]).tolist())\n\n targets = get_pyramid(y, len(y_hat_levels), shape_list, False)\n loss_levels = []\n\n criterion_ds = get_loss(configs['criterion_ds'])\n for y_hat_level, target in zip(y_hat_levels, targets):\n loss_levels.append(criterion_ds(y_hat_level, target))\n\n loss_final = None \n loss_com = {}\n for loss_name, loss_weight in configs['criterion'].items():\n loss_com['loss_' + loss_name] = criterion[loss_name](y_hat, y) \n if loss_final is None:\n loss_final = criterion[loss_name](y_hat, y)*float(loss_weight)\n else:\n loss_final += criterion[loss_name](y_hat,y)*float(loss_weight)\n\n loss_deep_super = torch.sum(torch.stack(loss_levels))\n loss = loss_final + loss_deep_super\n\n target = y\n pred = torch.sigmoid(y_hat)\n dice = metrics.dice(pred, target, threshold=0.5).mean()\n iou = metrics.iou(pred, target, threshold=0.5).mean()\n\n self.batch_metrics = {\n 'loss': loss,\n 'dice': dice,\n 'iou': iou\n }\n\n for key in loss_com:\n self.batch_metrics[key] = loss_com[key]\n \n runner = CustomRunner(device = utils.get_device())\n runner.train(\n model=model,\n optimizer=optimizer,\n callbacks=callbacks,\n logdir=log_dir,\n loaders=loader,\n num_epochs=configs['num_epochs'],\n scheduler=scheduler,\n main_metric=configs['metric'],\n minimize_metric=False,\n timeit=True,\n fp16=fp16_params,\n resume=configs['resume_path'],\n verbose=True,\n )\n\ndef run_cross_validation(fold):\n #@TODO Not doing yet because training with cross validation take so much time \n pass\n","sub_path":"src/main/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":17962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"395784284","text":"import matplotlib.pyplot as plt\nimport seaborn as sns\n\ninfile = open('perihelion20_8Newton.txt')\n\nnumbers = []\nfor line in infile:\n\tnumbers.append(float(line))\n\n\n\nplt.plot(numbers)\nplt.title('The perihelion precession of Mercury')\nplt.ylabel('Perihelion angle [rad]')\nplt.xlabel('Number of full rotations around the Sun')\nplt.show()\n","sub_path":"plotting/plot_perihelion.py","file_name":"plot_perihelion.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"408237965","text":"import GPUtil\nimport time\nimport psutil\nimport math\nfrom log.log import Logger\nimport sys\n\n\ndef memoryuse():\n gpulist = []\n memory = []\n\n # f = open('./log/2.txt', 'a+')\n # sys.stdout = f\n\n gpuss = GPUtil.getGPUs()\n for gpu in gpuss:\n gpulist.append(gpu.memoryUsed)\n print('总gpu:', gpu.memoryTotal, 'gpuused:', gpu.memoryUsed)\n cpu = psutil.cpu_percent()\n mem = psutil.virtual_memory() #\n\n mem_total = mem[0] / math.pow(1024, 3)\n mem_used = mem[2]\n mem1 = mem[3] / math.pow(1024, 3)\n memory.append(mem_used)\n print('cpu:', str(cpu) + '%,', '总memory:', round(mem_total), '占用率', str(mem_used) + '%,', 'memory used:', str(mem1))\n time.sleep(3)","sub_path":"MemoryUse.py","file_name":"MemoryUse.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"218666631","text":"import pyqtgraph as pg\nimport numpy as np\nfrom PyQt5 import QtCore\nfrom datetime import datetime\n\nfrom MusicalIllusion.Visualizer.VisualizerData import VisualizerData\n\n\nclass Visualizer():\n def __init__(self, plot, parent, defaultSize, defaultGain, connectDots):\n\n self.parent = parent\n self.data = VisualizerData(defaultSize, defaultGain)\n self.frame = 0\n self.connectDots = connectDots\n\n # Timings used for the output file\n self.timings = {}\n\n # Set the plot up for visualization\n self.lines = pg.GraphItem(pos=np.array([(-100, -100)]))\n plot.addItem(self.lines)\n p = plot.getPlotItem()\n p.setXRange(0, 10)\n p.setYRange(0, 10)\n p.showGrid(False, False)\n p.showAxis('left', False)\n p.showAxis('bottom', False)\n p.setMouseEnabled(False, False)\n p.hideButtons()\n\n self.plotTimer = QtCore.QTimer()\n self.plotTimer.setTimerType(QtCore.Qt.PreciseTimer)\n self.plotTimer.timeout.connect(self.plotData)\n\n self.audTimer = QtCore.QTimer()\n self.audTimer.setTimerType(QtCore.Qt.PreciseTimer)\n self.audTimer.timeout.connect(self.playAudio)\n\n self.audComplete = QtCore.QTimer()\n self.audComplete.timeout.connect(self.progressAudio)\n\n def setData(self, data):\n self.data.loadData(data)\n self.frame = 0\n self.timings = {}\n\n def clearPlot(self):\n self.lines.setData(pos=np.array([(-100, -100)]))\n\n def play(self):\n self.plotTimer.start(0)\n if self.data.isAudio:\n self.audTimer.start(self.data.audOffset)\n self.frame = 0\n time = datetime.now()\n self.timings = {\"animationStart\": time, \"animationDelay\": self.data.audOffset,\n \"audioStart\": time, \"audioDelay\": 0}\n\n def playAudio(self):\n self.data.audio.play()\n self.audTimer.stop()\n self.audComplete.start(1000)\n\n def progressAudio(self):\n if not self.data.audio.isPlaying():\n self.audComplete.stop()\n self.parent.state.currentTrialData.update(self.timings)\n if self.parent.data.propertiesVer == 'si.properties':\n self.parent.state.updateState()\n return\n\n def plotData(self):\n\n if self.data.isAnim == False:\n self.plotTimer.stop()\n return\n\n pens = [pg.mkPen(color=[j for j in i]) for i in self.data.pens[self.frame]]\n brushes = [pg.mkBrush(color=[j for j in i]) for i in self.data.pens[self.frame]]\n lines = np.array([(i[0], i[1], i[2], 255, 1) for i in self.data.pens[self.frame]], dtype=[('red', np.ubyte), ('green', np.ubyte), ('blue', np.ubyte), ('alpha', np.ubyte), ('width', float)])\n\n # Ugly but the only way it'll let me toggle the lines\n # Pushed a fix for this to matplotlib but not sure when it'll be\n # included in the full version. Ugly will have to do for now\n if self.connectDots:\n self.lines.setData(pos=np.array(self.data.pos[self.frame]),\n adj=self.data.adj,\n pen=lines,\n symbolPen=pens,\n symbolBrush=brushes,\n symbol=self.data.shapes[self.frame],\n size=self.data.sizes[self.frame]\n )\n else:\n self.lines.setData(pos=np.array(self.data.pos[self.frame]),\n pen=lines,\n symbolPen=pens,\n symbolBrush=brushes,\n symbol=self.data.shapes[self.frame],\n size=self.data.sizes[self.frame]\n )\n\n self.frame += 1\n if self.frame < len(self.data.times) - 1:\n dt = int((self.data.times[self.frame] - self.data.times[self.frame - 1]) * 1000)\n self.plotTimer.setInterval(dt)\n else:\n self.plotTimer.stop()\n self.lines.setData(pos=np.array([(-100, -100)]))\n self.parent.state.currentTrialData.update(self.timings)\n self.parent.state.updateState()\n","sub_path":"src/python3/MusicalIllusion/Visualizer/Visualizer.py","file_name":"Visualizer.py","file_ext":"py","file_size_in_byte":4235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"214404034","text":"#!/usr/bin/env python\n\nimport rospy\nfrom std_msgs.msg import String\nfrom trajectory_msgs.msg import JointTrajectory\nfrom trajectory_msgs.msg import JointTrajectoryPoint\nimport math as mt\nfrom control_msgs.msg import JointTrajectoryControllerState\nfrom han2um_test.srv import *\nimport numpy as np\n\n\ndef Path_move(request):\n #link length\n l1=25\n l2=20\n l3=5\n # go position\n pos_x=request.fpos_x\n pos_y=request.fpos_y\n pos_z=request.fpos_z\n # calculate angle\n r=mt.sqrt(pos_x*pos_x+pos_y*pos_y+pos_z*pos_z)\n if r>50:\n print(\"over max distance\")\n\n #reference=robotarm current joint angle\n rospy.wait_for_service('jointstate')\n word=True\n jointangle=rospy.ServiceProxy('jointstate',jointstate)\n res=jointangle(word) # res.th0~3\n \n res_rx=l1*mt.cos(res.th1)+l2*mt.cos(res.th1+res.th2)\n res_rrx=l1*mt.cos(res.th1)+l2*mt.cos(res.th1+res.th2)+l3*mt.cos(res.th1+res.th2+res.th3)\n res_rz=l1*mt.sin(res.th1)+l2*mt.sin(res.th1+res.th2)\n res_rrz=l1*mt.sin(res.th1)+l2*mt.sin(res.th1+res.th2)+l3*mt.sin(res.th1+res.th2+res.th3)\n\n # circle's dot min distance\n num=8\n t=np.linspace(0,2*mt.pi,num)\n Cx=np.zeros(num)\n Cz=np.zeros(num)\n for i in range(0,num):\n Cx[i]=l3*mt.cos(t[i])+pos_x\n Cz[i]=l3*mt.sin(t[i])+pos_z\n\n distance=np.zeros(num)\n for i in range(0,num):\n distance[i]=mt.sqrt((res_rx-Cx[i])**2+(res_rz-Cz[i])**2)\n min_num=np.argmin(distance)\n Px=Cx[min_num]\n Pz=Cz[min_num]\n print(Px,Pz)\n #IK\n th0=mt.atan(pos_y/pos_x)\n d=mt.sqrt(Px**2+Pz**2)\n th2=-1*mt.acos((d**2-l1**2-l2**2)/(2*l1*l2))\n alpha=mt.atan(Pz/Px)\n th1=mt.acos((d**2+l1**2-l2**2)/(2*d*l1))+alpha\n rx=l1*mt.cos(th1)\n rz=l1*mt.sin(th1)\n th2_m=mt.atan((Pz-rz)/(Px-rx))\n th3_m=mt.atan((pos_z-Pz)/(pos_x-Px))\n th3=(th3_m-th2_m)\n\n # distance error\n de=0.1\n pub = rospy.Publisher('/arm_controller/command', JointTrajectory, queue_size=10)\n print('real')\n print('th0: %f,th1: %f,th2:%f,th3:%f' %(th0,th1,th2,th3))\n #angle error fillter\n \n th1=angle_filter(th1)\n th2=angle_filter(th2)\n th3=angle_filter(th3)\n print('filter')\n print('th0: %f,th1: %f,th2:%f,th3:%f' %(th0,th1,th2,th3))\n print('th0_d:%f,th1_d:%f,th2_d:%f,th3_d:%f' %(th0*180/mt.pi,th1*180/mt.pi,th2*180/mt.pi,th3*180/mt.pi))\n \n\n while not rospy.is_shutdown():\n msg=JointTrajectory()\n msg.joint_names=['base2','link1_joint','link2_joint','link3_joint']\n ptn=JointTrajectoryPoint()\n\n ptn.positions=[th0,th1,th2,th3]\n ptn.time_from_start=rospy.Duration.from_sec(1)\n msg.points.append(ptn)\n pub.publish(msg)\n rate.sleep()\n\n rospy.wait_for_service('jointstate')\n word=True\n jointangle=rospy.ServiceProxy('jointstate',jointstate)\n res=jointangle(word) # res.th0~3\n \n #0<=res.th0<=360degree\n #0<=res.th1<=90degree\n #0<=res.th2<=90degree\n #0<=res.th3<=90degree\n\n if ((res.th0-th0)<=de)and((res.th1-th1)<=de)and((res.th2-th2)<=de)and((res.th3-th3)<=de):\n print('move complete')\n break\n\ndef angle_filter(theta):\n if theta<0:\n theta=-theta\n return theta\n\"\"\"\ndef angle_filter123(theta):\n \n if theta<0:\n theta=-theta\n\n theta=mt.pi/2-theta\n\n if not 0<=theta<=mt.pi/2:\n theta=theta-mt.pi\n return theta\"\"\"\n \n\n\nrospy.init_node('Path_move', anonymous=True)\nservice=rospy.Service('Path_move',path_move,Path_move)\nrate = rospy.Rate(10) # 10hz\nrospy.spin()\n","sub_path":"main/Robot Arm Control/Path_move_server.py","file_name":"Path_move_server.py","file_ext":"py","file_size_in_byte":3550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"196779834","text":"from sklearn import linear_model\nimport pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import Imputer\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import datasets, linear_model\nfrom sklearn.metrics import mean_squared_error, r2_score\nimport matplotlib.pyplot as plt\n\n\n#Function to handle the non-numeric data.\ndef handle_non_numeric_data(df):\n columns=df.columns.values\n \n for column in columns:\n text_digit_vals={}\n def convet_to_int(val):\n return text_digit_vals[val]\n \n if df[column].dtype!=np.int64 and df[column].dtype!=np.float64:\n column_content=df[column].values.tolist()\n unique_element=set(column_content)\n x=0\n for unique in unique_element:\n if unique not in text_digit_vals:\n text_digit_vals[unique]=x\n x+=1\n \n df[column]=list(map(text_digit_vals.get, df[column]))\n return df \n\n\n#Filepath of the training and testing dataset.\ntrain_filepath='/home/shashank/NRP/Linear Regression/train.csv'\ntest_filepath='/home/shashank/NRP/Linear Regression/test.csv'\n\n\n\n#Read the csv file\ntrain_data=pd.read_csv(train_filepath)\ntest_data=pd.read_csv(test_filepath)\n\ny=train_data.SalePrice\nX=train_data.drop(['Id','SalePrice'],axis=1)\n\nX=handle_non_numeric_data(X)\n\n#Split tha data for testing and training.\ntrain_X,test_X,train_y,test_y=train_test_split(X.as_matrix(), y.as_matrix(), test_size=0.25)\n\n#Imputer for adding value where data is blank or NaN.\nmy_imputer = Imputer()\ntrain_X = my_imputer.fit_transform(train_X)\ntest_X = my_imputer.transform(test_X)\nX_scaled = preprocessing.scale(train_X)\nregr = linear_model.LinearRegression()\n\n# Train the model using the training sets\nregr.fit(train_X,train_y)\n\n# Make predictions using the testing set\npred_y = regr.predict(test_X)\n\n\n\nprint(mean_squared_error(test_y,pred_y))\nprint(mean_absolute_error(test_y,pred_y))\n\n\n\n\n","sub_path":"Linear Regression/regression_scikit.py","file_name":"regression_scikit.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"598172847","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2018, OVENUBE and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe.model.document import Document\n\nclass TiposdeTransaccionSunat(Document):\n\tpass\n\n@frappe.whitelist()\ndef get_tipo_transaccion(customer):\n\tcliente = frappe.get_doc(\"Customer\", customer)\n\tif cliente.codigo_tipo_documento in ['-', '1', '4', '6']:\n\t\ttransaccion = frappe.get_doc(\"Tipos de Transaccion Sunat\", \"VENTA INTERNA\")\n\telif cliente.codigo_tipo_documento == \"0\":\n\t\ttransaccion = frappe.get_doc(\"Tipos de Transaccion Sunat\", \"EXPORTACION\")\n\telse:\n\t\ttransaccion = frappe.get_doc(\"Tipos de Transaccion Sunat\", \"NO DOMICILIADO\")\n\treturn {\"codigo\": transaccion.codigo_tipo_transaccion, \"descripcion\": transaccion.name}\n\n@frappe.whitelist()\ndef get_tipo_transaccion_compras(supplier):\n\tproveedor = frappe.get_doc(\"Supplier\", supplier)\n\tif proveedor.codigo_tipo_documento in ['-', '1', '4', '6']:\n\t\ttransaccion = frappe.get_doc(\"Tipos de Transaccion Sunat\", \"VENTA INTERNA\")\n\telse:\n\t\ttransaccion = frappe.get_doc(\"Tipos de Transaccion Sunat\", \"NO DOMICILIADO\")\n\treturn {\"codigo\": transaccion.codigo_tipo_transaccion, \"descripcion\": transaccion.name}\n\n@frappe.whitelist()\ndef get_tipo_transaccion_fee(student):\n\tstudent = frappe.get_doc(\"Student\", student)\n\tif student.codigo_tipo_documento in ['-', '1', '4', '6']:\n\t\ttransaccion = frappe.get_doc(\"Tipos de Transaccion Sunat\", \"VENTA INTERNA\")\n\telse:\n\t\ttransaccion = frappe.get_doc(\"Tipos de Transaccion Sunat\", \"NO DOMICILIADO\")\n\treturn {\"codigo\": transaccion.codigo_tipo_transaccion, \"descripcion\": transaccion.name}","sub_path":"nubefact_integration/nubefact_integration/doctype/tipos_de_transaccion_sunat/tipos_de_transaccion_sunat.py","file_name":"tipos_de_transaccion_sunat.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"350536725","text":"import json\nimport pytest\nimport requests\nfrom server import *\n\n\n# REQUEST_REQUIRED_KEYS = [[\"patient_id\", \"attending_email\", \"user_age\"],\n# [\"patient_id\", \"heart_rate\"],\n# [\"patient_id\", \"heart_rate_average_since\"]]\n\n\n@pytest.mark.parametrize(\"HR, age, expected, broke\", [\n (200, 2, True, False),\n (120, 2, False, False),\n (110, 6000, True, False),\n (101, 5000, False, False),\n (\"abc\", 5000, False, True)\n])\ndef test_is_tachycardic(HR, age, expected, broke):\n age_years = float(age)/float(365)\n try:\n out = is_tachycardic(HR, age_years)\n except TypeError:\n assert broke is True\n else:\n assert broke is False\n assert out == expected\n\n\n@pytest.mark.parametrize(\"r, broke\", [\n ({\"patient_id\": \"1\", \"attending_email\": \"hi@duke.edu\", \"user_age\": 30},\n False),\n ({\"attending_email\": \"hi@duke.edu\", \"user_age\": 30}, True),\n ({\"patient_id\": \"1\", \"attending_email\": \"hi@duke.edu\"}, True)\n])\ndef test_validate_new_patient_request(r, broke):\n try:\n validate_new_patient_request(r)\n except ValidationError:\n assert broke is True\n except TypeError:\n assert broke is True\n else:\n assert broke is False\n\n\n@pytest.mark.parametrize(\"r, broke\", [\n ({\"patient_id\": \"1\", \"heart_rate\": 30}, False),\n ({\"patient_id\": \"1\"}, True),\n ({\"heart_rate\": 30}, True),\n ({\"patient_id\": \"1\", \"heart_rate\": 30,\n \"attending_email\": \"hi@duke.edu\"}, False),\n])\ndef test_validate_heart_rate_request(r, broke):\n try:\n validate_heart_rate_request(r)\n except ValidationError:\n assert broke is True\n except TypeError:\n assert broke is True\n else:\n assert broke is False\n\n\n@pytest.mark.parametrize(\"r, broke\", [\n ({\"patient_id\": \"1\",\n \"heart_rate_average_since\": \"2018-03-09 11:00:36.372339\"}, False),\n ({\"patient_id\": \"1\"}, True),\n ({\"heart_rate_average_since\": \"2018-03-09 11:00:36.372339\"}, True),\n ({\"patient_id\": \"1\",\n \"heart_rate_average_since\": \"2018-03-09 11:00:36.3\", \"hi\": 0}, False)\n])\ndef test_validate_internal_average_request(r, broke):\n try:\n validate_internal_average_request(r)\n except ValidationError:\n assert broke is True\n except TypeError:\n assert broke is True\n else:\n assert broke is False\n","sub_path":"test_server.py","file_name":"test_server.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"600449219","text":"import pandas as pd\nimport numpy as np \nimport Utils as utils\nimport kNN as knn\nimport kfold as kfold\nimport OLS as ols\n\nclass CentroidData:\n def __init__(self):\n self.centoid = []\n self.nearestDataPoints = []\n #for performance\n self.nearestDataPointsTempList = []\n #testing data for centroid\n self.testingData = []\n #for performance\n self.nearestDataPointsTempListForTestingData = []\n\nclass CentroidResults:\n def __init__(self):\n self.centroidData = []\n self.olsRuns = []\n\ndef randomN(df):\n return pd.DataFrame( np.random.rand(1,11), columns=df.columns)\n\ndef getKCentroids(k,df):\n list = []\n for i in range(k):\n list.append( randomN(df) )\n return list\n\ndef getKSpacedCentroids(k,df,delta):\n list = []\n for i in np.arange(0.0,1.1,delta):\n for j in np.arange(0,1.1,delta):\n for k in np.arange(0,1.1,delta):\n for l in np.arange(0,1.1,delta):\n centroid = randomN(df)\n centroid.head(1).Health_Expenditure = i\n centroid.head(1).GDP_Per_Capita = j\n centroid.head(1).Unemployment = k\n centroid.head(1).Education = l\n list.append( centroid )\n return list \n\n\ndef getK(delta):\n k = int(1/delta) + 1\n return k**4\n\n\n\ndef getSpacedCentoids(ddf):\n centroidsDF = pd.read_csv(\"clustering-InitialCentroids0.5.csv\")\n l = []\n for i in range(len(centroidsDF)):\n df = pd.DataFrame( columns=ddf.columns)\n df = df.append(centroidsDF.iloc[i])\n l.append(df)\n return l\n\n#sort datapoints according to nearest centroid\n\n\ndef getInitialCentroidDatas(k,df,delta): \n centroidDatas = []\n centroids = getKSpacedCentroids(k,df,delta)\n #centroids = getSpacedCentoids(df)\n for i in range(len(centroids)):\n centroidData = CentroidData()\n centroidData.centoid = centroids[i]\n centroidData.centoid.Country_Name = 'Centroid' + str(i)\n centroidData.nearestDataPoints = pd.DataFrame( columns=df.columns)\n centroidDatas.append(centroidData)\n return centroidDatas\n\n\n#onlySelectCentroidIfNearsestPointsIsEmpty means that thre needs to be nearest points already selected \ndef getClosestCentroid(datapoint,centroidDatas,onlySelectCentroidIfNearsestPointsIsEmpty):\n closestCentroidData = []\n closestDistance = 9999999999.9\n for i in range(len(centroidDatas)):\n #distance = knn.distance(centroidDatas[i].centoid, datapoint)\n distance = utils.GetEuclideanDistanceBetweenFeatureVectors(kfold.getX(centroidDatas[i].centoid),kfold.getX(datapoint) )\n if( distance < closestDistance):\n #this centroid can oly be selected if nearest points exists. This is in the case for selecting centroids for testing data\n if onlySelectCentroidIfNearsestPointsIsEmpty:\n if not centroidDatas[i].nearestDataPoints.empty:\n closestCentroidData = centroidDatas[i]\n closestDistance = distance\n else:\n uu = 0\n #select centroid regardless\n else:\n closestCentroidData = centroidDatas[i]\n closestDistance = distance\n return closestCentroidData\n\n\n\ndef getMeanPoint(nearestDataPoints,trainingData):\n #create new centroid \n meanPoint = randomN(trainingData)\n\n #set values of centroid to mean of each dimension\n meanPoint.head(1).Health_Expenditure = nearestDataPoints['Health_Expenditure'].mean()\n meanPoint.head(1).GDP_Per_Capita = nearestDataPoints['GDP_Per_Capita'].mean()\n meanPoint.head(1).Unemployment = nearestDataPoints['Unemployment'].mean()\n meanPoint.head(1).Education = nearestDataPoints['Education'].mean()\n return meanPoint\n\n\n\ndef CalculateCentroids(trainingData, k, movingThreshold, centroidDatas):\n for j in range(150):\n #assign training data point to closest centroid\n for i in range(len(trainingData)):\n dataRow = trainingData.iloc[i]\n centroidData = getClosestCentroid( dataRow, centroidDatas, onlySelectCentroidIfNearsestPointsIsEmpty = False)\n centroidData.nearestDataPointsTempList.append(dataRow)\n #centroidData.nearestDataPoints = centroidData.nearestDataPoints.append( dataRow, ignore_index=True,sort=False )\n\n numberOfCentroidsThatDidNotMove = 0\n for i in range(len(centroidDatas)):\n #removing all nearest points\n centroidDatas[i].nearestDataPoints.dropna()\n centroidDatas[i].nearestDataPoints = pd.DataFrame(centroidDatas[i].nearestDataPointsTempList, columns=trainingData.columns)\n # centroidDatas[i].nearestDataPoints = pd.concat( [centroidDatas[i].nearestDataPoints, centroidDatas[i].nearestDataPointsTempList])\n #clear temp list \n centroidDatas[i].nearestDataPointsTempList = []\n \n #if no points are assosiated with the centroid then the centroid does not move\n if not centroidDatas[i].nearestDataPoints.empty:\n newCentroid = getMeanPoint(centroidDatas[i].nearestDataPoints,trainingData)\n else:\n newCentroid = centroidDatas[i].centoid\n \n \n \n #calculate mean of data points assigned to the centroid\n #newCentroid = utils.GetMeanPointOfDataset( centroidDatas[i].nearestDataPoints)\n #get the change in position of the centroid\n old = kfold.getX(centroidDatas[i].centoid)\n new = kfold.getX(newCentroid)\n diffrenceInCentroid = old - new \n distanceBetweenOldAndNewCentroid = utils.GetEuclideanDistanceBetweenFeatureVectors(kfold.getX(centroidDatas[i].centoid),kfold.getX(newCentroid) )\n print( \"centroid difference \" + str(i) + ' distance= ' + str(distanceBetweenOldAndNewCentroid) )\n print( diffrenceInCentroid )\n #set new mean of data points as the new centroid\n centroidDatas[i].centoid = newCentroid\n if( distanceBetweenOldAndNewCentroid < movingThreshold ):\n numberOfCentroidsThatDidNotMove = numberOfCentroidsThatDidNotMove +1\n\n #return if none of the centroids have moved\n if( numberOfCentroidsThatDidNotMove >= k):\n print( \"no centroids have moved with threshold=\" + str(movingThreshold) + \" on itteration \" + str(j))\n return centroidDatas\n # return if j itterations have been reached\n print(\"returning after \" + str(j) + \"itterations\")\n return centroidDatas\n\ndef RunClustering(testSet, k, movingThreshold, delta):\n centroidResults = CentroidResults()\n\n centroidDatas = getInitialCentroidDatas(k,testSet.trainingDF, delta) \n\n centroidDatas = CalculateCentroids(testSet.trainingDF, k, movingThreshold, centroidDatas)\n \n #associate testing data to centroids\n for i in range(len(testSet.testingDF)):\n dataRow = testSet.testingDF.iloc[i]\n centroidData = getClosestCentroid( dataRow, centroidDatas, onlySelectCentroidIfNearsestPointsIsEmpty = True)\n centroidData.nearestDataPointsTempListForTestingData.append(dataRow)\n \n for i in range(k):\n centroidDatas[i].testingData = pd.DataFrame(centroidDatas[i].nearestDataPointsTempListForTestingData, columns=testSet.testingDF.columns)\n\n trainingX = kfold.getX(centroidDatas[i].nearestDataPoints).to_numpy()\n trainingY = kfold.getY(centroidDatas[i].nearestDataPoints).to_numpy()\n testingX = kfold.getX(centroidDatas[i].testingData).to_numpy()\n testingY = kfold.getY(centroidDatas[i].testingData).to_numpy()\n \n #training data and testing data has to be available for the OLS regression to run\n results = ols.OLSRun()\n if not centroidDatas[i].nearestDataPoints.empty and not centroidDatas[i].testingData.empty and ols.givesSingularMatrix(trainingX) == False:\n results = ols.RunDataset( trainingY, trainingX, testingY, testingX)\n\n #store centroid data in results\n centroidResults.centroidData.append(centroidDatas[i])\n #store results of running ols on the test data for that centroid\n centroidResults.olsRuns.append( results )\n return centroidResults\n\n\n#l = getKCentroids(2)\n\n#a = randomN()\n\n#dist = utils.GetEuclideanDistanceBetweenFeatureVectors( a, x_df.head(1).to_numpy())\n\n\n\n\n\n\n#b = 1","sub_path":"Hons Project/kMeansClustering.py","file_name":"kMeansClustering.py","file_ext":"py","file_size_in_byte":8431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"251490353","text":"#import asyncio\nimport discord # discord.py rewrite\nfrom discord.ext import commands\nimport os\nfrom pymongo import MongoClient\nimport random\nimport traceback\n\n\n# Load secure environment variables\nBOT_TOKEN = os.environ['BOT_TOKEN']\n#SERVER_ID = os.environ['SERVER_ID']\n\n\nbot = commands.Bot(command_prefix='.')\n\n\n@bot.command(pass_context = True)\nasync def adduser(ctx, user : discord.User, nation):\n \"\"\"Add a user to the users table.\n Requires an @mentioned user and their nation (separated by a space).\"\"\"\n client = MongoClient(MONGODB_URI)\n # As far as I can tell, on the free plan you're only allowed to access the\n # default database created for you by heroku.\n db = client.get_database()\n users = db['users'] # Select or create collection\n\n user_data = {'uid' : user.id, 'username' : user.name,\n 'discriminator' : user.discriminator, 'nation' : nation}\n users.insert_one(user_data)\n client.close() # Clean up\n\n await ctx.send('Added {} playing as {}.'.format(user.name, nation))\n\n\n@bot.command(pass_context = True)\nasync def addnation(ctx, user : discord.User, nation, pres, ind, mil, pop):\n \"\"\"Add a nation to the nation collection.\n\n Requires an @mentioned user, their nation, prestige, industry, and mil\n scores, and the population (separated by spaces, no commas in numbers).\"\"\"\n client = MongoClient(MONGODB_URI)\n db = client.get_database()\n nations = db['nations'] # Select or create collection\n\n n_data = {'nation' : nation, 'uid' : user.id, 'prestige' : pres,\n 'industry' : ind, 'military' : mil, 'pop' : pop}\n nations.insert_one(n_data)\n client.close() # Clean up\n\n await ctx.send('Added {} playing as {}.'.format(user.name, nation))\n\n\n@bot.event\nasync def on_ready():\n print('Logged in as')\n print(bot.user.name)\n print(bot.user.id)\n print('-'*max(len(bot.user.name), len(str(bot.user.id))))\n\ncogs = ['cogs.userquery', 'cogs.utility']\n\nif __name__ == '__main__':\n for cog in cogs:\n try:\n bot.load_extension(cog)\n except Exception as e:\n print(f'Failed to load {cog}.')\n traceback.print_exc()\n\n# Actually run the bot\nbot.run(BOT_TOKEN, bot=True, reconnect=True)\n","sub_path":"va.py","file_name":"va.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"549167355","text":"from prog import require\n\n\ndef clitext(f=None):\n require(f, 'str')\n while KeyboardInterrupt:\n with open(f, 'w') as stream:\n data = raw_input('%s->') % f\n stream.write(data)\n\n\ndef searchfile(key, obj):\n require(obj, 'str')\n require(key, 'str')\n\n with open(obj, 'r') as stream:\n d = stream.read()\n if key in d:\n lines = d.splitlines(key)\n return lines\n else:\n return False\n","sub_path":"nstd/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"160297291","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import (absolute_import, division,\n print_function, unicode_literals)\nfrom ph_plotter.band_sf_plotter import BandSFPlotter\n\n\n__author__ = \"Yuji Ikeda\"\n\n\nclass BandSFContourPlotter(BandSFPlotter):\n def _plot_sf(self, ax, distances, frequencies, sf):\n variables = self._variables\n\n # \"pcolormesh\" is much faster than \"pcolor\".\n quad_contour_set = ax.contour(\n distances,\n frequencies * variables[\"unit\"],\n sf,\n cmap=self._colormap,\n linecolor=\"k\",\n linewidths=variables[\"linewidth\"],\n vmin=variables[\"sf_min\"],\n vmax=variables[\"sf_max\"],\n levels=self._sf_ticks,\n extend=\"both\",\n # rasterized=True, # This is important to make the figure light.\n )\n return quad_contour_set\n","sub_path":"ph_plotter/band_sf_contour_plotter.py","file_name":"band_sf_contour_plotter.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"468430530","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport numpy as np\nfrom configparser import ConfigParser\nfrom typing import Union, Tuple\n\n# Typing\nndarray = np.ndarray\nFloatArray = Union[ndarray, float]\n\n# Shortcuts\nABS = np.abs\nARGWHERE = np.argwhere\nSIGN = np.sign\nDIFF = np.diff\n\ndef find_equilibrium_points(heating, cooling, domain, diff_tol=0.1):\n \"\"\" Returns the position of equilibrium points. \"\"\"\n if len(heating.shape) > 1:\n if heating.shape[1] == 1:\n heating = heating[:,0]\n elif heating.shaep[0] == 1:\n heating = heating[0,:]\n else:\n raise Exception('Only 1D Arrays Allowed')\n if len(cooling.shape) > 1:\n if cooling.shape[1] == 1:\n cooling = cooling[:,0]\n elif cooling.shaep[0] == 1:\n cooling = cooling[0,:]\n else:\n raise Exception('Only 1D Arrays Allowed')\n\n index = ARGWHERE(DIFF(SIGN(heating - cooling)) != 0).reshape(-1) + 0\n y = heating[index]\n x = domain[index]\n if len(x) > 1:\n p_i = 0\n possible_points = list()\n for x_i, x in enumerate(domain[index]):\n found = False\n if p_i > 0:\n for p_ii, p in enumerate(possible_points):\n for s in p:\n if abs(x-s) < diff_tol:\n found = True\n break\n if found:\n new_p_loc = p_ii\n break\n if found:\n possible_points[new_p_loc].append(x)\n else:\n possible_points.append([x])\n p_i += 1\n else:\n possible_points.append([x])\n p_i += 1\n # Now combine similar points\n x = []\n y = []\n index = []\n for point_set in possible_points:\n new_x = np.median(point_set)\n ind, real_x = find_nearest(domain, new_x, return_value=True)\n x.append(real_x)\n index.append(ind)\n y.append(heating[ind])\n return x, y, index\n\ndef find_nearest(array: ndarray, value: FloatArray, return_value: bool = False):\n idx = (ABS(array - value)).argmin()\n if return_value:\n output = (idx, array[idx]) # type: Tuple[int, float]\n else:\n output = idx # type: int\n return output\n\ndef find_path(wanted_file_name: str,\n top_level: str = '.',\n ignore_git: bool = True, ignore_python: bool = False) -> str:\n \"\"\" DOC STR\"\"\"\n path = '' # type; str\n if top_level == '.':\n top_level = os.getcwd()\n for dir_name, dir_names, file_names in os.walk(top_level):\n if '__pycache__' in dir_name:\n continue\n if ignore_git and '.git' in dir_name:\n continue\n for file_name in file_names:\n if ignore_python and ('.py' in file_name or '.pyx' in file_name):\n continue\n if file_name == wanted_file_name:\n path = os.path.join(dir_name, file_name)\n break\n if path:\n break\n if not path:\n raise Exception('Can not locate {}'.format(wanted_file_name))\n else:\n return path\n\nBOOL_LIKE_TRUE = ['true', int(1), '1', 'True', 'TRUE', True]\nBOOL_LIKE_FALSE = ['false', int(0), '0', 'False', 'FALSE', False]\nNONE_LIKE = ['none', 'None', '', 'NONE', None]\n\ndef int_float_none(string_: str):\n \"\"\" Attempts to convert to int or float if the string is 'None' it will return a None otherwise it raises an error.\n \"\"\"\n output = None # type: None\n if string_ is not None:\n try:\n output = int(string_) # type: int\n except ValueError:\n try:\n output = float(string_) # type: float\n except ValueError:\n if string_.lower() in BOOL_LIKE_TRUE:\n output = True\n elif string_.lower() in BOOL_LIKE_FALSE:\n output = False\n elif string_.lower() in NONE_LIKE:\n output = None\n else:\n # Leave it as a string.\n pass\n return output\n\ndef pull_cfg_info(cfg_file_name, header_name, var_name, convert: bool = False, starting_dir: str = False):\n \"\"\" Uses the config parser to pull out configuration data information. Converts type if needed.\n\n \"\"\"\n\n if not starting_dir:\n starting_dir = '.'\n cfg_path = find_path(cfg_file_name, top_level=starting_dir, ignore_python=True)\n config = ConfigParser()\n config.read(cfg_path)\n\n value = config[header_name][var_name]\n if convert:\n value = int_float_none(value)\n\n return value\n\n","sub_path":"src/other_funcs/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":4731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"496677907","text":"import pprint\nimport re # noqa: F401\n\nimport six\n\nfrom karix.models.whatsapp_account_error import WhatsappAccountError # noqa: F401,E501\n\n\nclass WhatsappAccount(object):\n\n swagger_types = {\n 'uid': 'str',\n 'karix_account_uid': 'str',\n 'name': 'str'\n }\n attribute_map = {\n 'uid': 'uid',\n 'karix_account_uid': 'karix_account_uid',\n 'name': 'name'\n }\n\n def __init__(self, uid=None, karix_account_uid=None, name=None):\n\n self._uid = None\n self._karix_account_uid = None\n self._name = None\n\n if uid is not None:\n self.uid = uid\n if karix_account_uid is not None:\n self.karix_account_uid = karix_account_uid\n if name is not None:\n self.name = name\n\n @property\n def uid(self):\n return self._uid\n\n @uid.setter\n def uid(self, uid):\n self._uid = uid\n\n @property\n def karix_account_uid(self):\n return self._karix_account_uid\n\n @karix_account_uid.setter\n def karix_account_uid(self, karix_account_uid):\n self._karix_account_uid = karix_account_uid\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, name):\n self._name = name\n\n def to_dict(self):\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n if issubclass(WhatsappAccount, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n return self.to_str()\n\n def __eq__(self, other):\n if not isinstance(other, WhatsappAccount):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n return not self == other\n","sub_path":"karix/models/whatsapp_account.py","file_name":"whatsapp_account.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"505112574","text":"import sys\nimport scrabble_best_move as sc\n\n\ndef main(argv):\n if len(argv) == 2:\n input_file = argv[1].strip()\n else:\n print('Please specify the input file')\n exit()\n\n best_move = sc.play(input_file, \"resources/dict.txt\")\n print(best_move)\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"315135214","text":"def check_valid_input(s):\n \"\"\" function which check that the input is True or False \"\"\"\n\n if s == \"rock\":\n return True\n elif s == \"paper\":\n return True\n elif s == \"scissors\":\n return True\n else:\n return False\n\n\ndef convert_to_num(s):\n \"\"\" function which tranfer string to a number of choice\n\n >>> convert_to_num(\"scissors\")\n 2\n >>> convert_to_num(\"paper\")\n 1\n \"\"\"\n\n if s == \"rock\":\n return 0\n elif s == \"paper\":\n return 1\n elif s == \"scissors\":\n return 2\n else:\n print(\"Error: should not reach this if input is a valid one\")\n\n\ndef convert_to_string(n):\n \"\"\" function which tranfer number of choice to string\n\n >>> convert_to_string(1)\n \"paper\"\n >>> convert_to_string(2)\n \"scissors\"\n\n \"\"\"\n\n if n == 0:\n return \"rock\"\n elif n == 1:\n return \"paper\"\n elif n == 2:\n return \"scissors\"\n else:\n print(\"Error: should not reach this if input is a valid one\")\n\n\ndef game_decision(player, com):\n \"\"\" function which get a choice from layer and computer then return the winner\n\n >>> game_decision(2,2)\n Both ties!\n >>> game_decision(1,2)\n Player wins!\n >>> game_decision(0,2)\n Computer wins!\n\n \"\"\"\n\n if player == com:\n print(\"Both ties!\")\n if com - player < 0:\n com += 3\n if com - player == 1:\n print(\"Player wins!\")\n elif com - player == 2:\n print(\"Computer wins!\")\n\n\nvalid = False\nwhile valid == False:\n player_choice = input(\"Enter your choice: \")\n valid = check_valid_input(player_choice)\n if valid == False:\n print(\"Invalid choice. Enter again.\")\n\nimport random\n\ncomputer_choice_num = random.randint(0, 2)\ncomputer_choice = convert_to_string(computer_choice_num)\nplayer_choice_num = convert_to_num(player_choice)\nprint(\"Players chooses \", player_choice)\nprint(\"Computer chooses \", computer_choice)\n\ngame_decision(player_choice_num, computer_choice_num)","sub_path":"grader/files_mai/6210546668_task1.py","file_name":"6210546668_task1.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"369717582","text":"# 单调栈问题\n# 给定一个数组, 找到左边第一个比它大的数字,和 右边比它大的数字\n# 核心思想是: 维护一个从大到小的栈, 一个元素进入栈的时候和栈内元素比较, 如比栈内元素大就出栈, 出栈的元素记录左右两边比它大的元素\n# 记得最后栈不为空的时候,清空栈\ndef find_ans(arr):\n if not arr:\n return [], []\n\n stack = []\n left = []\n right = []\n for each in arr:\n if len(stack) >= 1:\n while stack:\n top = stack[-1]\n if top < each:\n stack.pop()\n if stack:\n left.append((top, stack[-1]))\n else:\n left.append((top, -1))\n right.append((top, each))\n else:\n stack.append(each)\n break\n if len(stack) < 1:\n stack.append(each)\n while stack:\n top = stack.pop()\n if stack:\n left.append((top, stack[-1]))\n else:\n left.append((top, -1))\n right.append((top, -1))\n\n return left, right\n\n\nif __name__ == '__main__':\n arr = [3, 5, 2, 4, 6, 0, 1, 5]\n # arr = [1]\n left, right = find_ans(arr)\n print(left)\n print(right)\n","sub_path":"target_offer/栈+队列+堆/单调栈.py","file_name":"单调栈.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"505910179","text":"# %%\nimport pandas as pd\nfrom datetime import date\nfrom os.path import split as split_path\nfrom tqdm import tqdm\nfrom joblib import Parallel, delayed\n\nfrom src.data import trimmed_data_dir\nfrom src.data import parquet_paths\nfrom src.data.constants import PREPAY_STATUSES, DEFAULT_STATUSES, x_cols, y_cols\n\n\n# %%\ndef trim_to_first_60_day_delinq(raw_df):\n raw_df = raw_df.drop(['current_date', 'current_month', 'current_year'], axis=1)\n current_month = (raw_df['orig_month'] + raw_df['month_count'] -1 ) % 12 + 1\n current_year = raw_df['orig_year'] + (raw_df['orig_month'] + raw_df['month_count'] -1) // 12\n current_date = current_year.apply(str) + '-' + current_month.apply('{:02}'.format) + '-01'\n current_date = pd.to_datetime(current_date)\n\n # The current date (year) in the raw data in wrong\n raw_df = raw_df.assign(current_date=current_date, current_year=current_year, current_month=current_month)\n\n post_crisis = (raw_df[raw_df['sr_date_transfer'] >= 20090101])\n post_crisis = post_crisis.set_index(['mcd_loanid', 'sr_unique_id', 'sr_property_id', pd.to_datetime(post_crisis['current_date'])]).sort_index()\n\n # Regard 60-day as absorbing state, and ignore entries with unknown status\n delinq = post_crisis['payment_current_status'].isin(list(DEFAULT_STATUSES))\n first_delinquent_date = (delinq[delinq]\n .reset_index('current_date')\n .groupby('mcd_loanid')['current_date']\n .first()\n .rename('first_delinquent_date'))\n\n post_crisis['first_delinquent_date'] = first_delinquent_date.reindex(delinq.index, level='mcd_loanid')\n\n no_delinq = post_crisis['first_delinquent_date'].isnull()\n before_deliq = post_crisis['current_date'] <= post_crisis['first_delinquent_date']\n missing_status = post_crisis['payment_current_status'] == '-'\n trimmed_df = post_crisis[(no_delinq|before_deliq) & ~missing_status].drop('first_delinquent_date', axis=1)\n \n # Categories to predict\n X = trimmed_df.reindex(x_cols, axis=1)\n X['prepaid'] = trimmed_df['payment_current_status'].isin(list(PREPAY_STATUSES)).astype(int)\n X['default'] = trimmed_df['payment_current_status'].isin(list(DEFAULT_STATUSES)).astype(int)\n X['current'] = 1 - (X['prepaid'] | X['default'])\n return X\n\n\n#%%\ndef trim_and_save(file_path):\n file_name = split_path(file_path)[-1]\n df = pd.read_parquet(file_path)\n t_df = trim_to_first_60_day_delinq(df)\n loanid = t_df.index.get_level_values('mcd_loanid')\n hashkey = pd.util.hash_array(loanid) % 100\n for key, g_df in t_df.groupby(hashkey):\n g_path = trimmed_data_dir + file_name + '.bucket_' + f'{key:02}'\n g_df.to_parquet(g_path)\n return file_name\n#%%\nif __name__ == '__main__':\n Parallel(n_jobs=8)(delayed(trim_and_save)(p) for p in tqdm(parquet_paths))\n\n# %%\n# # %% CHECK if dates are correct\n# g = post_crisis.groupby('mcd_loanid')\n# mono = g['month_count'].is_monotonic_increasing\n# mono","sub_path":"src/data/cleaning.py","file_name":"cleaning.py","file_ext":"py","file_size_in_byte":2963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"370510884","text":"#\n# @lc app=leetcode.cn id=20 lang=python3\n#\n# [20] 有效的括号\n#\n# https://leetcode-cn.com/problems/valid-parentheses/description/\n#\n# algorithms\n# Easy (40.85%)\n# Likes: 1385\n# Dislikes: 0\n# Total Accepted: 204.3K\n# Total Submissions: 500K\n# Testcase Example: '\"()\"'\n#\n# 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。\n#\n# 有效字符串需满足:\n#\n#\n# 左括号必须用相同类型的右括号闭合。\n# 左括号必须以正确的顺序闭合。\n#\n#\n# 注意空字符串可被认为是有效字符串。\n#\n# 示例 1:\n#\n# 输入: \"()\"\n# 输出: true\n#\n#\n# 示例 2:\n#\n# 输入: \"()[]{}\"\n# 输出: true\n#\n#\n# 示例 3:\n#\n# 输入: \"(]\"\n# 输出: false\n#\n#\n# 示例 4:\n#\n# 输入: \"([)]\"\n# 输出: false\n#\n#\n# 示例 5:\n#\n# 输入: \"{[]}\"\n# 输出: true\n#\n#\n\n# @lc code=start\n\n\nclass Solution:\n def isValid(self, s: str) -> bool:\n stack = []\n val = {'(': 1, '[': 2, '{': 3, ')': -1, ']': -2, '}': -3}\n for i in range(len(s)):\n if val[s[i]] > 0:\n stack.append(val[s[i]])\n else:\n if len(stack) != 0 and stack[-1] + val[s[i]] == 0:\n stack.pop()\n else:\n return False\n return len(stack) == 0\n# @lc code=end\n","sub_path":"20.有效的括号.py","file_name":"20.有效的括号.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"624233858","text":"from typing import List\nfrom cs54_list import nil, head, tail, add, instance_as_list, list_as_str\nfrom cs54_tools import read_instances\n\nfrom dernier import dernier\nfrom sauf_dernier import sauf_dernier\n\n\ndef palindrome(list: List[str]) -> bool:\n if nil(list):\n return True\n elif nil(tail(list)):\n return True\n elif head(list) != dernier(list):\n return False\n else:\n return palindrome(sauf_dernier(tail(list)))\n\n\nif __name__ == \"__main__\":\n # assert palindrome([])\n # assert palindrome(['a'])\n # assert palindrome(['a', 'a'])\n # assert palindrome(['a', 'b']) == False\n # assert palindrome(['a', 'b', 'a']) == True\n # assert palindrome(['a', 'b', 'b', 'a']) == True\n # assert palindrome(['a', 'b', 'c', 'b', 'a']) == True\n\n with open(\"./data/R17.txt\", \"w\") as output_file:\n instances = read_instances(\"./data/T17.txt\")\n output_file.write(f\"{len(instances)}\\n\")\n for num, instance in enumerate(instances, start=1):\n if num >= 4:\n instance = instance.replace(\" \", \"\").replace(\",\", \"\").replace(\"?\", \"\").replace(\"!\", \"\").lower()\n\n l = instance_as_list(instance)\n output_file.write(f\"{palindrome(l)}\\n\")\n","sub_path":"S5/CS54/Algo/Cours/cs54-lab2-solution/palindrome.py","file_name":"palindrome.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"573296109","text":"from haystack.views import FacetedSearchView\nfrom django.contrib.localflavor.us import us_states\n\nDATE_FIELDS = ('start_date', 'end_date')\n\n\nclass ImprovedFacetedSearchView(FacetedSearchView):\n def __name__(self):\n return \"ImprovedFacetedSearchView\"\n\n def extra_context(self):\n extra = super(ImprovedFacetedSearchView, self).extra_context()\n facet_tuple = tuple([item.split(':') for item in self.request.GET.getlist('selected_facets')])\n facet_dict = dict([(item[0].split('_exact')[0], item[1]) for item in facet_tuple if len(item) > 1])\n extra['selected_facets'] = facet_dict\n extra['date_filters'] = []\n for key, value in self.request.GET.iteritems():\n if key.startswith(DATE_FIELDS):\n extra['date_filters'].append((key, value))\n extra['date_filters'].sort()\n extra['us_states'] = us_states.US_STATES\n extra['sfapp_base_template'] = 'sfapp/base-full.html'\n\n return extra\n","sub_path":"fcc_adtracker/search/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"105325112","text":"import cv2 as cv\nimport numpy as np\nimport random\nimport math\nimport sys\nimport os\nimport time\nrandom.seed(time.time)\n\nif __name__ == '__main__':\n img_path = sys.argv[1]\n fileName = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..')) + '/' + img_path\n print(fileName)\n\n # 2a: read and display the image\n # img = cv.imread('../images/bonn.png')\n img = cv.imread(fileName)\n cv.imshow('Original Image', img)\n cv.waitKey(0)\n\n # 2b: display the intenstity image\n intensityImg = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n cv.imshow('Intensity Image', intensityImg)\n cv.waitKey(0)\n\n # 2c: for loop to perform the operation\n diffImg = img.copy()\n\n for y in range(intensityImg.shape[0]):\n for x in range(intensityImg.shape[1]):\n diffImg[y, x, :] -= np.uint8(intensityImg[y, x] * 0.5)\n \n diffImg[diffImg < 0] = 0\n cv.imshow('Difference Image', diffImg)\n cv.waitKey(0)\n\n # 2d: one-line statement to perfom the operation above\n diffImg2 = img - np.uint8(np.expand_dims(intensityImg, axis = 2) * 0.5)\n diffImg2[diffImg2 < 0] = 0\n cv.imshow('Difference Image 2', diffImg2)\n cv.waitKey(0)\n\n\n # 2e: Extract a random patch\n cy = int(img.shape[0]/2)\n cx = int(img.shape[1]/2)\n imgPatch = img[cy - 8 : cy + 8, cx - 8 : cx + 8]\n cv.imshow('Image Patch', imgPatch)\n cv.waitKey(0)\n\n ry = random.randint(0,img.shape[0]-16)\n rx = random.randint(0,img.shape[1]-16)\n imgWithPatch = img.copy()\n imgWithPatch[ry : ry + 16, rx : rx + 16] = imgPatch[:,:]\n cv.imshow('Image with Patch', imgWithPatch)\n cv.waitKey(0)\n\n # 2f: Draw random rectangles and ellipses\n imgRectangles = img.copy()\n for i in range(10):\n ry = random.randint(0,img.shape[0])\n rx = random.randint(0,img.shape[1])\n w = random.randint(1,50)\n h = random.randint(1,50)\n cv.rectangle(imgRectangles, (ry, rx), (ry + w, rx + x), (255, 0, 0), 2)\n \n cv.imshow('Random Rectangles', imgRectangles)\n cv.waitKey(0)\n\n\n # draw ellipses\n imgEllipses = img.copy()\n for i in range(10):\n ry = random.randint(0,img.shape[0])\n rx = random.randint(0,img.shape[1])\n raxisy = random.randint(0,150)\n raxisx = random.randint(0,150)\n cv.ellipse(imgEllipses, (ry, rx), (raxisy, raxisx), 0, 0, 360, (0, 255, 0), 3)\n \n cv.imshow('Random Ellipses', imgEllipses)\n cv.waitKey(0)\n\n\n # destroy all windows\n cv.destroyAllWindows()","sub_path":"Sheet00/src/sheet00.py","file_name":"sheet00.py","file_ext":"py","file_size_in_byte":2482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"604037770","text":"# Introduction to Artificial Intelligence\n# Neural network classifier for credit default using TensorFlow, part 2\n# By Juan Carlos Rojas\n\nimport numpy as np\nimport pandas as pd\nimport pickle\nimport tensorflow as tf\nimport sklearn.metrics\nimport matplotlib.pyplot as plt\n\n# Load the training and test data from the Pickle file\nwith open(\"credit_card_default_dataset.pickle\", \"rb\") as f:\n train_data, train_labels, test_data, test_labels = pickle.load(f)\n\n# Get some lengths\nn_inputs = train_data.shape[1]\nnsamples = train_data.shape[0]\n\n# Training constants\nbatch_size = 60\nlearning_rate = .02\nn_epochs = 500\neval_step = 10\nn_nodes_l1 = 100\n\n# TensorFlow constants\n\n# Input vectors\nX = tf.constant(train_data.values.astype(np.float32))\nY = tf.constant(train_labels.values.reshape(-1,1).astype(np.float32))\n\nn_batches = int(np.ceil(nsamples / batch_size))\n\n# Print the configuration\nprint(\"Batch size: {} Num batches: {} Num epochs: {} Learning rate: {}\".format(batch_size, n_batches, n_epochs, learning_rate))\nprint(\"Num nodes in L1: {} Activation function: ReLU\".format(n_nodes_l1))\n\n# TensorFlow constants\n\n# Input vector placeholders. Length is unspecified.\nX = tf.placeholder(tf.float32, shape=(None, n_inputs), name=\"X\")\nY = tf.placeholder(tf.float32, shape=(None, 1), name=\"Y\")\n\n# Hidden layer 1:\n# Inputs: n_inputs\n# Outputs: n_nodes_l1\n# Activation: ReLU\nW_L1 = tf.Variable(tf.truncated_normal([n_inputs, n_nodes_l1], stddev=1/np.sqrt(n_inputs)))\nb_L1 = tf.Variable(tf.zeros(n_nodes_l1)) \nY_L1 = tf.nn.relu(tf.add(tf.matmul(X, W_L1), b_L1))\n\n# Output layer:\n# Inputs: n_nodes_l1\n# Outputs: 1\n# Activation: logistic\nW_L2 = tf.Variable(tf.truncated_normal([n_nodes_l1, 1], stddev=1/np.sqrt(n_nodes_l1)))\nb_L2 = tf.Variable(tf.zeros(1)) \nY_L2_linear = tf.add(tf.matmul(Y_L1, W_L2), b_L2)\n\n# Cost function, plus the sigmoid part of the prediction\ncost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits( \n logits = Y_L2_linear, labels = Y))\n\n# Optimize cost through gradient descent\noptimizer = tf.train.GradientDescentOptimizer(learning_rate)\nupdate_op = optimizer.minimize(cost)\n\n# Prediction probability values\nY_pred_proba_calc = tf.nn.sigmoid(Y_L2_linear)\n\n# Create TensorFlow session and initialize it\nsess = tf.Session()\ninit = tf.global_variables_initializer()\nsess.run(init)\n\nepoch = 0\nwhile epoch < n_epochs:\n batch = 0\n\n while batch < n_batches:\n\n # Select the data for the next batch\n dataidx = batch * batch_size\n X_batch = train_data[dataidx:(dataidx+batch_size)]\n Y_batch = train_labels[dataidx:(dataidx+batch_size)].values.reshape(-1,1)\n feed_dict = {X: X_batch, Y: Y_batch}\n\n # Run one iteration of the computation session to update coefficients\n _ = sess.run(update_op, feed_dict=feed_dict)\n batch += 1\n\n # Evaluate the test score every certain number of epochs\n if (epoch % eval_step == 0):\n\n # Compute the test accuracy\n feed_dict = {X: test_data, Y: test_labels.values.reshape(-1,1)}\n Y_pred_proba_test = sess.run(Y_pred_proba_calc, feed_dict=feed_dict)\n auc_score = sklearn.metrics.roc_auc_score(test_labels, Y_pred_proba_test)\n print(\"Epoch {:4d}: Test AUC score: {:.4f}\".format(epoch, auc_score))\n \n epoch += 1\n\n# Run a session to compute the predictions against the training data\nfeed_dict = {X: train_data, Y: train_labels.values.reshape(-1,1)}\nY_pred_proba_training = sess.run(Y_pred_proba_calc, feed_dict=feed_dict)\n\n# Run a session to compute the predictions against the test data\nfeed_dict = {X: test_data, Y: test_labels.values.reshape(-1,1)}\nY_pred_proba_test = sess.run(Y_pred_proba_calc, feed_dict=feed_dict)\n\nauc_score = sklearn.metrics.roc_auc_score(test_labels, Y_pred_proba_test)\nprint(\"Test AUC score: {:.4f}\".format(auc_score))\n\n# Predict new labels for training data\nauc_score_training = sklearn.metrics.roc_auc_score(\\\n train_labels, Y_pred_proba_training)\nprint(\"Training AUC score: {:.4f}\".format(auc_score_training))\n","sub_path":"Week 5/CreditDefault_NN_2.py","file_name":"CreditDefault_NN_2.py","file_ext":"py","file_size_in_byte":4023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"179279478","text":"import logging\nimport json\nimport random\nfrom collections import deque\n\nfrom dungeon.models import Dungeon, DungeonTile, DungeonRoom, DungeonObject, DungeonLevel\nfrom character.models import Character\nfrom item.models import Item\n\nlogger_ = logging.getLogger(\"generator\")\nlogger_.addHandler(logging.StreamHandler())\n\n\nclass DungeonGenerator(object):\n \"\"\"\n Takes a level config and outputs a new dungeon maze.\n \"\"\"\n dungeon_monsters = []\n dungeon_items = []\n num_rooms = 0\n is_final_level = False\n level = None\n maze = []\n monster_rooms = []\n\n def _create_room(self, room):\n # go through the tiles in the rectangle and make them passable\n for x in range(room.x1 + 1, room.x2):\n for y in range(room.y1 + 1, room.y2):\n tile = self.maze[x][y]\n tile.is_blocked = False\n tile.block_sight = False\n tile.is_ground = True\n\n # place the player in the center of the first room\n if self.num_rooms == 0:\n x, y = room.center()\n tile = self.maze[x][y]\n self.place_player(tile)\n else:\n self.monster_rooms.append(room)\n\n def place_monsters_in_rooms(self):\n \"\"\"\n Go through each room and drop a monster in it. Keep\n going until there are no more monsters to place.\n \"\"\"\n while len(self.dungeon_monsters):\n for room in self.monster_rooms:\n tile = self.get_random_room_tile(room)\n self.place_monster(tile)\n\n def place_items_in_rooms(self):\n \"\"\"\n Go through each room and drop an item in it. Keep\n going until there are no more items to place.\n \"\"\"\n for item in self.dungeon_items:\n random_room = random.choice(self.monster_rooms)\n tile = self.get_random_room_tile(random_room)\n self.place_item(tile, item)\n\n def get_random_room_tile(self, room, depth=0):\n \"\"\"\n Get a random ground tile that does not already contain a object\n @param depth: This prevents crash by infinite recursion.\n @param room:\n @return:\n \"\"\"\n x = random.randint(room.x1 + 1, room.x2 - 1)\n y = random.randint(room.y1 + 1, room.y2 - 1)\n tile = self.maze[x][y]\n\n if not tile.contains_object:\n return tile\n\n if depth > 50:\n logger_.debug(\"Could not find appropriate tile to spawn item.\")\n return tile\n\n # if we didn't find an empty tile, try again\n return self.get_random_room_tile(room, depth=depth + 1)\n\n def _create_h_tunnel(self, x1, x2, y):\n # horizontal tunnel. min() and max() are used in case x1>x2\n for x in range(min(x1, x2), max(x1, x2) + 1):\n self.maze[x][y].is_blocked = False\n self.maze[x][y].block_sight = False\n self.maze[x][y].is_ground = True\n\n def _create_v_tunnel(self, y1, y2, x):\n # vertical tunnel\n for y in range(min(y1, y2), max(y1, y2) + 1):\n self.maze[x][y].is_blocked = False\n self.maze[x][y].block_sight = False\n self.maze[x][y].is_ground = True\n\n def generate(self, level):\n \"\"\"\n Generates a new dungeon based the level\n @param level:\n \"\"\"\n width = 80\n height = 45\n max_rooms = level.max_rooms\n max_room_size = level.max_room_size\n min_room_size = level.min_room_size\n\n self.level = level\n self.is_final_level = level.is_final_level\n self.dungeon_monsters = deque([m for m in\n Character\n .select()\n .join(DungeonLevel)\n .where(\n (DungeonLevel.level_id == level.level_id) &\n (Character.name != 'player'))\n ])\n\n self.dungeon_items = deque([item for item in Item\n .select()\n .join(DungeonLevel)\n .where((DungeonLevel.level_id == level.level_id))])\n\n # self.max_num_items = level.max_num_items\n # fill map with \"blocked\" tiles\n self.maze = [[DungeonTile(x, y, True) for y in range(height)] for x in range(width)]\n\n rooms = []\n\n for r in range(max_rooms):\n # random width and height\n w = random.randint(min_room_size, max_room_size)\n h = random.randint(min_room_size, max_room_size)\n # random position without going out of the boundaries of the map\n x = random.randint(0, width - w - 1)\n y = random.randint(0, height - h - 1)\n\n # \"DungeonRoom\" class makes rectangles easier to work with\n new_room = DungeonRoom(x, y, w, h)\n\n # run through the other rooms and see if they intersect with this one\n failed = False\n for other_room in rooms:\n if new_room.intersect(other_room):\n failed = True\n break\n\n if not failed:\n # this means there are no intersections, so this room is valid\n\n # \"paint\" it to the map's tiles\n self._create_room(new_room)\n\n # center coordinates of new room, will be useful later\n new_x, new_y = new_room.center()\n\n if self.num_rooms > 0:\n # connect it to the previous room with a tunnel\n # center coordinates of previous room\n (prev_x, prev_y) = rooms[self.num_rooms-1].center()\n\n # draw a coin (random number that is either 0 or 1)\n if random.randint(0, 1) == 1:\n # first move horizontally, then vertically\n self._create_h_tunnel(prev_x, new_x, prev_y)\n self._create_v_tunnel(prev_y, new_y, new_x)\n else:\n # first move vertically, then horizontally\n self._create_v_tunnel(prev_y, new_y, prev_x)\n self._create_h_tunnel(prev_x, new_x, new_y)\n\n # finally, append the new room to the list\n rooms.append(new_room)\n self.num_rooms += 1\n\n self.place_monsters_in_rooms()\n self.place_items_in_rooms()\n # if not level.final_level:\n # self.place_stairs(rooms)\n\n # connect them with a tunnel\n self._create_h_tunnel(25, 55, 23)\n\n serialized_maze = json.dumps([\n [\n {\n 'x': tile.x,\n 'y': tile.y,\n 'is_blocked': tile.is_blocked,\n 'is_explored': tile.is_explored,\n 'is_ground': tile.is_ground,\n 'contains_object': tile.contains_object,\n 'block_sight': tile.block_sight\n } for tile in row\n ] for row in self.maze\n ])\n\n new_dungeon = Dungeon(level=level, width=width, height=height, maze=serialized_maze)\n new_dungeon.save()\n\n def place_monster(self, tile):\n\n try:\n monster = self.dungeon_monsters.popleft()\n new_dungeon_object = DungeonObject(\n coords=json.dumps((tile.x, tile.y)),\n blocks=True\n )\n new_dungeon_object.save()\n monster.dungeon_object = new_dungeon_object\n monster.save()\n tile.contains_object = True\n except IndexError:\n pass\n\n def place_player(self, tile):\n \"\"\"\n Place the player in the maze.\n \"\"\"\n dungeon_object = DungeonObject(\n coords=json.dumps((tile.x, tile.y)),\n blocks=True\n )\n\n player = Character.get(Character.name == 'player')\n player.level = self.level\n player.dungeon_object = dungeon_object\n\n dungeon_object.save()\n player.save()\n\n tile.contains_object = True\n\n def place_item(self, tile, item):\n item.dungeon_object = DungeonObject(coords=json.dumps((tile.x, tile.y)))\n item.level = self.level\n item.dungeon_object.save()\n item.save()\n\n# def place_stairs(self, tile):\n# TODO: fix this to use new item system\n# room = random.choice(rooms[1::])\n#\n# (x, y) = room.center()\n#\n# if not util.is_blocked(x, y, self):\n# stairs = DungeonObject(x, y, '>', 'Stairs')\n#\n# self.stairs = stairs\n# self.objects.append(stairs)\n# util.send_to_back(stairs, self.objects)\n# else:\n# # if the spot was blocked find another spot to place the item\n# self.place_stairs(rooms)\n","sub_path":"dungeon/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":8884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"488935096","text":"import copy\nimport json\nimport logging\nimport math\nimport multiprocessing\nimport threading\nimport pathlib\nfrom collections import namedtuple\nfrom itertools import count, repeat\nfrom contextlib import AbstractContextManager, contextmanager\n\nfrom music21 import stream, duration, note\n\nfrom db.DbMaster import DbMaster\nfrom gconfig import gconfig\nfrom libs import StreamPackage\nfrom libs.exceptions import dbException\nfrom libs.m21 import melIDsToString\nfrom libs.math import distToMultipleOf\nfrom libs.masterLogger import logger\n\nMeaRange = namedtuple('MeaRange', ['a', 'b'])\n\n# this var is used to monitor progress\n\nclass DbChild(AbstractContextManager):\n \"\"\"\n Each mashup-generating process has one instance of this class to record individually generated mashups.\n The childJson are then sent to dbMaster.\n \"\"\"\n\n def __init__(self):\n # keeps track of threads that are writing musicxml to disk\n self._writeThreads = []\n self._db = {}\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if exc_type == dbException:\n return False\n\n # wait for all writeProcess to finish before exit\n for proc in self._writeThreads:\n proc.join()\n\n @property\n def db(self):\n return self._db\n\n @contextmanager\n def startFile(self, melIDs: frozenset):\n # signals that all incoming mashups will be made up of melody with ids in melID\n try:\n # name of db unit will be melIDs joined by @\n # must sort name because otherwise the order of melIDs will be random\n fileName = melIDsToString(melIDs)\n # these attributes will disappear after exiting context\n setattr(self, '_partsList_', [stream.Part() for _ in range(4)])\n setattr(self, '_measureRanges_', [])\n\n yield self\n if self._partsList_: # only write to disk if _partsList_ not empty\n # if no exception happened, write to file\n pathToFile = pathlib.Path(gconfig.db.dbPath).joinpath(fileName)\\\n .with_suffix(f'.{gconfig.db.dbFileFormat}')\n if pathToFile.exists():\n logger.warning(f'Path {pathToFile} already exists. Overwriting...')\n pathToFile.unlink(missing_ok=True)\n\n s = stream.Stream()\n for part in self._partsList_:\n s.insert(0, part)\n\n writer = threading.Thread(target=s.write, args=(gconfig.db.dbFileFormat, pathToFile))\n self._writeThreads.append(writer)\n writer.start()\n\n self._db[melIDs] = {\n 'fileName': fileName,\n 'filePath': str(pathToFile),\n 'measureRanges': self._measureRanges_\n }\n\n except dbException as dbe:\n # do not write to file\n raise dbe\n\n finally:\n delattr(self, '_partsList_')\n delattr(self, '_measureRanges_')\n\n def addMashup(self, mash: StreamPackage):\n mash.parts[0].flat.notesAndRests[0].style.color = '#FF0000'\n assert len(self._partsList_) == 2 * mash.numParts\n for i in range(mash.numParts):\n rst = note.Rest(\n duration=duration.Duration(distToMultipleOf(mash.quarterLength))\n )\n self._partsList_[2 * i].append([e for e in mash.parts[i].flat.notesAndRests])\n self._partsList_[2 * i + 1].append([e for e in mash.parts[i].cf.flat.notesAndRests])\n if rst.duration.quarterLength != 0:\n self._partsList_[2 * i].append(rst)\n self._partsList_[2 * i + 1].append(rst)\n\n endingRstLength = distToMultipleOf(mash.quarterLength)\n measureLength = math.floor((mash.quarterLength + endingRstLength) / 4)\n curMeasureNumber = self._measureRanges_[-1].b + 1 if self._measureRanges_ else 1\n self._measureRanges_.append(MeaRange(curMeasureNumber, curMeasureNumber + measureLength - 1))\n\n\ndef localTest():\n pass\n\n\nif __name__ == '__main__':\n localTest()\n","sub_path":"db/DbChild.py","file_name":"DbChild.py","file_ext":"py","file_size_in_byte":4172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"166368271","text":"#!/usr/bin/env python3\n#coding=utf-8\n#\n# Copyright (c) HiSilicon Technologies Co., Ltd. 2019-2019. All rights reserved.\n# Description: Menuconfig entry\n# Author: HiSilicon\n# Create: 2019-12-31\n#\n\nimport os\nfrom kconfiglib import Kconfig\nfrom menuconfig import menuconfig\n\ndef mconf_set_env(style, conf, header):\n \"\"\"\n These parameters would not be effect unless kconflib supported these.\n \"\"\"\n os.environ[\"MENUCONFIG_STYLE\"] = style\n os.environ[\"KCONFIG_CONFIG\"] = conf\n os.environ[\"KCONFIG_CONFIG_HEADER\"] = header\n\ndef hi_mconfig():\n kconfig = os.path.join(\"tools\", \"menuconfig\", \"Kconfig\")\n display_style = \"default selection=fg:white,bg:red\"\n target_conf = os.path.join(\"build\", \"config\", \"usr_config.mk\")\n header = \"# Generated by HiSilicon menuconfig tool\"\n mconf_set_env(display_style, target_conf, header)\n kconf = Kconfig(filename=kconfig)\n menuconfig(kconf)\n\nif __name__ == \"__main__\":\n hi_mconfig()\n","sub_path":"tools/menuconfig/usr_config.py","file_name":"usr_config.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"627995349","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Apr 19 10:58:04 2019\r\n\r\n@author: Admin\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n# reading the csv file \r\nhousing = pd.read_csv('housing.csv') \r\n#to see the first 5 elements of the table \r\nhousing.head()\r\n# gives the detailed info of the table \r\nhousing.info()\r\n# gives the mean median mode of the quantitative attributes \r\nhousing_describe = housing.describe() \r\n#In a given column It gives the number of unique elements along with its count \r\nhousing['ocean_proximity'].value_counts()\r\n\r\n# plotting histogram to get the overall picture of the data \r\nimport matplotlib.pyplot as plt \r\nhousing.hist(bins=50,figsize=(20,20)) # number of bins is 50 in this case \r\n\r\n# splitting the train test data \r\nfrom sklearn.model_selection import train_test_split \r\ntrain_set,test_set = train_test_split(housing,test_size=0.2,random_state= 42)\r\n\r\nhousing[\"income_cat\"]=np.ceil(housing[\"median_income\"]/1.5)\r\nhousing.hist(column='income_cat')\r\n\r\n#Doubt?\r\nhousing[\"income_cat\"].where(housing[\"income_cat\"]<5,5.0,inplace=True)\r\n\r\nhousing[\"income_cat\"].value_counts()/len(housing)\r\n\r\nfrom sklearn.model_selection import StratifiedShuffleSplit\r\nsplit=StratifiedShuffleSplit(n_splits=1,test_size=0.2,random_state=42)\r\nfor train_index,test_index in split.split(housing,housing[\"income_cat\"]):\r\n strat_train_set=housing.loc[train_index]\r\n strat_test_set=housing.loc[test_index]\r\n \r\n\r\nfor set_ in(strat_train_set,strat_test_set):\r\n set_.drop(\"income_cat\",axis=1,inplace=True)\r\n \r\nhousing = strat_train_set.copy()\r\n\r\nhousing.plot(kind=\"scatter\",x=\"longitude\",y=\"latitude\")\r\nhousing.plot(kind=\"scatter\",x=\"longitude\",y=\"latitude\",alpha=0.1)\r\n\r\n#Why X axis label is not printing?\r\nhousing.plot(kind=\"scatter\",x=\"longitude\",y=\"latitude\",alpha=0.4,\r\n s=housing[\"population\"]/100,label=\"population\",figsize=(10,7),\r\n c=\"median_house_value\",cmap=plt.get_cmap(\"jet\"),colorbar=True,)\r\n#s = size\r\n#c = color\r\n#jet = jet returns the jet colormap as a three-column array\r\n\r\n#why legend?\r\nplt.legend()\r\n\r\n\r\ncorr_matrix=housing.corr()\r\ncorr_matrix[\"median_house_value\"].sort_values(ascending=False)\r\n\r\nfrom pandas.tools.plotting import scatter_matrix\r\nattributes=[\"median_house_value\",\"median_income\",\"total_rooms\",\r\n \"housing_median_age\"]\r\nscatter_matrix(housing[attributes],figsize=(12,8))\r\n\r\nhousing.plot(kind=\"scatter\",x=\"median_income\",y=\"median_house_value\",alpha=0.1)\r\n\r\nhousing[\"rooms_per_hopusehold\"]=housing[\"total_rooms\"]/housing[\"households\"]\r\nhousing[\"bedrooms_per_room\"]=housing[\"total_bedrooms\"]/housing[\"total_rooms\"]\r\nhousing[\"population_per_household\"]=housing[\"population\"]/housing[\"households\"]\r\n\r\ncorr_matrix=housing.corr()\r\ncorr_matrix[\"median_house_value\"].sort_values(ascending=False)\r\n\r\nhousing=strat_train_set.drop(\"median_house_value\",axis=1)\r\nhousing_labels=strat_train_set[\"median_house_value\"].copy()\r\n\r\nhousing.dropna(subset=[\"total_bedrooms\"])\r\nhousing.drop(\"total_bedrooms\",axis=1)\r\nmedian=housing[\"total_bedrooms\"].median()\r\nhousing[\"total_bedrooms\"].fillna(median,inplace=True)\r\n\r\nfrom sklearn.preprocessing import Imputer\r\nimputer=Imputer(strategy=\"median\")\r\nhousing_num=housing.drop(\"ocean_proximity\",axis=1)\r\nimputer.fit(housing_num)\r\n\r\nimputer.statistics_ \r\nhousing_num.median().values\r\n\r\nX=imputer.transform(housing_num)\r\nhousing_tr=pd.DataFrame(X,columns=housing_num.columns)\r\n\r\nfrom sklearn.preprocessing import LabelEncoder\r\nencoder=LabelEncoder()\r\nhousing_cat=housing[\"ocean_proximity\"]\r\nhousing_cat_encoded=encoder.fit_transform(housing_cat)\r\nhousing_cat_encoded\r\n\r\nprint(encoder.classes_)\r\n\r\nfrom sklearn.base import BaseEstimator,TransformerMixin\r\nrooms_ix,bedrooms_ix,population_ix,household_ix=3,4,5,6\r\nclass CombinedAttributesAdder(BaseEstimator,TransformerMixin):\r\n def __init__(self,add_bedrooms_per_room=True):\r\n self.add_bedrooms_per_room=add_bedrooms_per_room\r\n def fit(self,X,y=None):\r\n return self\r\n def transform(self,X,y=None):\r\n rooms_per_household=X[:,rooms_ix]/X[:,household_ix]\r\n population_per_household=X[:,population_ix]/X[:,household_ix]\r\n if self.add_bedrooms_per_room:\r\n bedrooms_per_room=X[:,bedrooms_ix]/X[:,household_ix]\r\n return np.c_[X,rooms_per_household,population_per_household,bedrooms_per_room]\r\n else:\r\n return np.c_[X,rooms_per_household,population_per_household]\r\n \r\nattr_adder=CombinedAttributesAdder(add_bedrooms_per_room=False)\r\nhousing_extra_attribs=attr_adder.transform(housing.values)\r\n\r\nfrom sklearn.pipeline import Pipeline\r\nfrom sklearn.preprocessing import StandardScaler\r\nnum_pipeline=Pipeline([('imputer',Imputer(strategy=\"median\")),('attribs_adder',\r\n CombinedAttributesAdder()),('std_scaler',\r\n StandardScaler()),])\r\nhousing_num_tr=num_pipeline.fit_transform(housing_num)\r\n\r\nfrom sklearn.base import BaseEstimator , TransformerMixin \r\nclass DataFrameSelector(BaseEstimator,TransformerMixin):\r\n def __init__(self,attribute_names):\r\n self.attribute_names=attribute_names\r\n def fit(self,X,y=None):\r\n return self\r\n def transform(self,X):\r\n return X[self.attribute_names].values\r\n \r\nfrom sklearn.preprocessing import LabelBinarizer \r\nnum_attribs=list(housing_num)\r\ncat_attribs=[\"ocean_proximity\"]\r\nnum_pipeline=Pipeline([('selector',DataFrameSelector(num_attribs)),\r\n ('imputer',Imputer(strategy=\"median\")),\r\n ('attribs_adder',CombinedAttributesAdder()),\r\n ('std_scaler',StandardScaler()),])\r\ncat_pipeline=Pipeline([('selector',DataFrameSelector(cat_attribs)),\r\n ('label_binarizer',LabelBinarizer()),])\r\n \r\nfrom sklearn.pipeline import FeatureUnion\r\nfull_pipeline=FeatureUnion(transformer_list=[(\"num_pipeline\",num_pipeline),\r\n (\"cat_pipeline\",cat_pipeline),]) \r\n \r\nhousing_prepared=full_pipeline.fit_transform(housing)\r\nhousing_prepared\r\n\r\nfrom sklearn.linear_model import LinearRegression \r\nlin_reg = LinearRegression()\r\nlin_reg.fit(housing_prepared , housing_labels)\r\nsome_data = housing.iloc[:5]\r\nsome_data_prepared = full_pipeline.transform(some_data)\r\nprint(\"Predictions:\", lin_reg.predict(some_data_prepared))\r\n\r\nfrom sklearn.metrics import mean_squared_error\r\nhousing_predictions= lin_reg.predict(housing_prepared)\r\nlin_mse=mean_squared_error(housing_labels,housing_predictions)\r\nlin_rmse=np.sqrt(lin_mse)\r\nlin_rmse\r\n \r\n#Decision Tree\r\nfrom sklearn.tree import DecisionTreeRegressor\r\ntree_reg=DecisionTreeRegressor()\r\ntree_reg.fit(housing_prepared,housing_labels)\r\n\r\nhousing_predictions=tree_reg.predict(housing_prepared)\r\ntree_mse=mean_squared_error(housing_labels,housing_predictions)\r\ntree_rmse=np.sqrt(tree_mse)\r\ntree_rmse\r\n\r\n#cross validation\r\nlin_scores = cross_val_score(lin_reg, housing_prepared, housing_labels,\r\n scoring=\"neg_mean_squared_error\", cv=10)\r\nlin_rmse_scores = np.sqrt(-lin_scores)\r\ndisplay_scores(lin_rmse_scores) \r\n\r\nfrom sklearn.model_selection import cross_val_score\r\nscores=cross_val_score(tree_reg,housing_prepared,housing_labels,\r\n scoring=\"neg_mean_squared_error\",cv=10) #Doubt?\r\ntree_rmse_scores=np.sqrt(-scores)\r\n\r\ndef display_scores(scores):\r\n print(\"scores:\",scores)\r\n print(\"Mean\",scores.mean())\r\n print(\"Standard deviation:\",scores.std())\r\ndisplay_scores(tree_rmse_scores) \r\n\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nforest_reg = RandomForestRegressor()\r\nforest_reg.fit(housing_prepared, housing_labels)\r\n\r\ndisplay_scores(forest_rmse_scores)\r\n\r\n\r\nfrom sklearn.externals import joblib\r\njoblib.dump(my_model, \"my_model.pkl\")\r\nmy_model_loaded = joblib.load(\"my_model.pkl\") \r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Housing Data Analytics.py","file_name":"Housing Data Analytics.py","file_ext":"py","file_size_in_byte":7919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"405611563","text":"import math\nfrom collections import defaultdict, namedtuple\nfrom operator import itemgetter\nfrom pprint import pformat\n\nfrom useful import Graph, input_from, manhattan\n\n\ndef coordinates_from_points(points):\n return [\n tuple(int(coordinate) for coordinate in point)\n for point in map(lambda x: x.split(\",\"), points)\n ]\n\n\n\"\"\"\nFailed attempt at an n log n solution using kdtrees. Left here for posterity.\n\"\"\"\n\n\n# class Node(namedtuple(\"Node\", \"location left_child right_child\")):\n# def __repr__(self):\n# return pformat(tuple(self))\n\n# def points(self):\n# points = []\n# s = []\n# node = self\n# while len(s) > 0 or node is not None:\n# if node is not None:\n# s.append(node)\n# node = node.left_child\n# else:\n# node = s.pop()\n# points.append(node.location)\n# node = node.right_child\n\n# return points\n\n\n# def tree_add(tree, new):\n# \"\"\"\n# Add a new node to this Node tree. For now do it by creating a new\n# kdtree with the new node.\n# \"\"\"\n# new_tree = tree.points()\n# new_tree.append(new)\n# return kdtree_from_points(new_tree)\n\n\n# def tree_insert(new, tree, axis=0):\n# \"\"\"\n# Add a new node to a Node object naively\n# (without regard for tree balance) along the given axis (e.g. x, y, z, etc.)\n\n# Returns a copy of the tree for convenience.\n# TODO: Can't set attributes to new values due to Node being subclassed\n# from namedtuple.\n# Methods using replace only return the tree at that branch of recursion\n# \"\"\"\n# if tree.left_child is None and tree.right_child is None:\n# if new[axis] <= tree.location[axis]:\n# tree.location = tree._replace(\n# location=tree.location,\n# left_child=Node(location=new, left_child=None, right_child=None),\n# right_child=None,\n# )\n# else:\n# tree.location = tree._replace(\n# location=tree.location,\n# left_child=Node(location=new, left_child=None, right_child=None),\n# right_child=None,\n# )\n# elif new[axis] <= tree.location[axis]:\n# tree_insert(new, tree.left_child)\n# else:\n# tree_insert(new, tree.right_child)\n\n\n# def kdtree_from_points(points, depth=0):\n# # print(points)\n# try:\n# k = len(points[0])\n# except IndexError as e:\n# return None\n\n# axis = depth % k\n# sorted_points = sorted(points, key=itemgetter(axis))\n# median = len(points) // 2\n\n# return Node(\n# location=sorted_points[median],\n# left_child=kdtree_from_points(sorted_points[:median], depth + 1),\n# right_child=kdtree_from_points(sorted_points[median + 1 :], depth + 1),\n# )\n\n\n# def nearest_neighbor(tree, point, d=manhattan):\n# \"\"\"\n# Return the nearest node to the input point in the tree of Nodes accoding\n# to the distance function d.\n# \"\"\"\n\n# def nn(tree, point, best_node, best_dist):\n# if tree is None:\n# return best_node\n\n# distance = d(point, tree.location)\n# if distance < best_dist:\n# return min(\n# nn(tree.left_child, point, tree.location, distance),\n# nn(tree.right_child, point, tree.location, distance),\n# key=lambda x: d(point, x),\n# )\n# else:\n# return min(\n# nn(tree.left_child, point, best_node, best_dist),\n# nn(tree.right_child, point, best_node, best_dist),\n# key=lambda x: d(point, x),\n# )\n\n# if tree.location is None or len(tree) < 1:\n# return None\n# else:\n# return nn(tree, point, None, math.inf)\n\n\n# def num_constellations(points):\n# \"\"\"\n# Greedy algorithm to determine number of constellations present in a list\n# of coordinates. Form a constellation (set of points) using the first point\n# encountered. Then add points using nearest neighbor search on a k-d tree\n# of the set to determine set membership until a point can't be added.\n# Then form a new set with the point that cannot be added. Continue until the\n# list of points is exhausted.\n# \"\"\"\n# coordinates = sorted(\n# coordinates_from_points(points), key=lambda x: (x[0], x[1], x[2], x[3])\n# )\n# MAX_DIST = 3\n\n# constellations = [kdtree_from_points(coordinates[:1])]\n# for point in coordinates[1:]:\n# did_add = False\n# for i, constellation in enumerate(constellations):\n# if manhattan(point, nearest_neighbor(constellation, point)) <= MAX_DIST:\n# constellations[i] = tree_add(constellation, point)\n# did_add = True\n# break\n\n# if did_add == False:\n# constellations.append(kdtree_from_points([point]))\n\n# return len(constellations)\n\n\ndef num_constellations(points):\n # Create adjacency list from points if manhattan <= 3\n MAX_DIST = 3\n coordinates = coordinates_from_points(points)\n adjacency_list = defaultdict(list)\n for point_1 in coordinates:\n adjacency_list[point_1] = []\n for point_2 in coordinates:\n if point_1 != point_2 and manhattan(point_1, point_2) <= MAX_DIST:\n adjacency_list[point_1].append(point_2)\n\n G = Graph(adjacency_list=adjacency_list)\n strongly_connected_components = G.Tarjans()\n return len(strongly_connected_components)\n\n\npoints = input_from(25).read().split(\"\\n\")\n\n# We can think of part 1's problem as a subset of the strongly connected\n# components problem. E.g., in trying to find the number of constellations\n# in our set of coordinates/points, we can phrase the problem as finding\n# the number of subgraphs in which each vertex is reachable from every other\n# vertex.\nprint(f\"Part 1: {num_constellations(points)}\")\n\n# TODO: Come back to this once I have 49 stars.\n","sub_path":"day25.py","file_name":"day25.py","file_ext":"py","file_size_in_byte":6017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"377387280","text":"# __init__.py\n# Authors: Yang Lu and Jacob Schreiber \n\nfrom .ledidi import Ledidi\nfrom .ledidi import TensorFlowRegressor\n\n__version__ = '0.2.0'\n\nimport numpy\nimport pyBigWig\n\nfrom tqdm import tqdm\n\ndef sequence_to_ohe(sequence, ignore='N', alphabet=None, dtype='int8', \n\tverbose=False, **kwargs):\n\t\"\"\"Converts a string or list of characters into a one-hot encoding.\n\n\tThis function will take in either a string or a list and convert it into a\n\tone-hot encoding. If the input is a string, each character is assumed to be\n\ta different symbol, e.g. 'ACGT' is assumed to be a sequence of four \n\tcharacters. If the input is a list, the elements can be any size.\n\n\tAlthough this function will be used here primarily to convert nucleotide\n\tsequences into one-hot encoding with an alphabet of size 4, in principle\n\tthis function can be used for any types of sequences.\n\n\tParameters\n\t----------\n\tsequence : str or list\n\t\tThe sequence to convert to a one-hot encoding.\n\n\tignore : str, optional\n\t\tA character to indicate setting nothing to 1 for that row, keeping the\n\t\tencoding entirely 0's for that row. In the context of genomics, this is\n\t\tthe N character. Default is 'N'.\n\n\talphabet : set or tuple or list, optional\n\t\tA pre-defined alphabet. If None is passed in, the alphabet will be\n\t\tdetermined from the sequence, but this may be time consuming for\n\t\tlarge sequences. Default is None.\n\n\tdtype : str or numpy.dtype, optional\n\t\tThe data type of the returned encoding. Default is int8.\n\n\tverbose : bool or str, optional\n\t\tWhether to display a progress bar. If a string is passed in, use as the\n\t\tname of the progressbar. Default is False.\n\n\tkwargs : arguments\n\t\tArguments to be passed into tqdm. Default is None.\n\n\tReturns\n\t-------\n\tone : numpy.ndarray\n\t\tA binary matrix of shape (alphabet_size, sequence_length) where\n\t\talphabet_size is the number of unique elements in the sequence and\n\t\tsequence_length is the length of the input sequence.\n\t\"\"\"\n\n\tname = None if verbose in (True, False) else verbose\n\td = verbose is False\n\n\tif isinstance(sequence, str):\n\t\tsequence = list(sequence)\n\n\talphabet = alphabet or numpy.unique(sequence)\n\talphabet = [char for char in alphabet if char != ignore]\n\talphabet_lookup = {char: i for i, char in enumerate(alphabet)}\n\n\tohe = numpy.zeros((len(sequence), len(alphabet)), dtype=dtype)\n\tfor i, char in tqdm(enumerate(sequence), disable=d, desc=name, **kwargs):\n\t\tif char != ignore:\n\t\t\tidx = alphabet_lookup[char]\n\t\t\tohe[i, idx] = 1\n\n\treturn ohe\n\ndef fasta_to_ohe(filename, include_chroms=None, exclude_chroms=None, \n\tignore='N', alphabet=['A', 'C', 'G', 'T', 'N'], dtype='int8', verbose=True):\n\t\"\"\"Read in a FASTA file and output a dictionary of binary encodings.\n\n\tThis function will take in the path to a FASTA-formatted file and convert\n\tit to a set of one-hot encodings---one for each chromosome. Optionally,\n\tthe user can specify a set of chromosomes to include or exclude from\n\tthe returned dictionary.\n\n\tParameters\n\t----------\n\tfilename : str\n\t\tThe path to the FASTA-formatted file to open.\n\n\tinclude_chroms : set or tuple or list, optional\n\t\tThe exact names of chromosomes in the FASTA file to include, excluding\n\t\tall others. If None, include all chromosomes (except those specified by\n\t\texclude_chroms). Default is None.\n\n\texclude_chroms : set or tuple or list, optional\n\t\tThe exact names of chromosomes in the FASTA file to exclude, including\n\t\tall others. If None, include all chromosomes (or the set specified by\n\t\tinclude_chroms). Default is None.\n\n\tignore : str, optional\n\t\tA character to indicate setting nothing to 1 for that row, keeping the\n\t\tencoding entirely 0's for that row. In the context of genomics, this is\n\t\tthe N character. Default is 'N'.\n\n\talphabet : set or tuple or list, optional\n\t\tA pre-defined alphabet. If None is passed in, the alphabet will be\n\t\tdetermined from the sequence, but this may be time consuming for\n\t\tlarge sequences. Must include the ignore character. Default is\n\t\t['A', 'C', 'G', 'T', 'N'].\n\n\tdtype : str or numpy.dtype, optional\n\t\tThe data type of the returned encoding. Default is int8. \n\n\tverbose : bool or str, optional\n\t\tWhether to display a progress bar. If a string is passed in, use as the\n\t\tname of the progressbar. Default is False.\n\n\tReturns\n\t-------\n\tchroms : dict\n\t\tA dictionary of one-hot encodings where the keys are the names of the\n\t\tchromosomes (exact strings from the header lines in the FASTA file)\n\t\tand the values are the one-hot encodings as numpy arrays.\n\t\"\"\"\n\n\tsequences = {}\n\tname, sequence = None, None\n\tskip_chrom = False\n\n\twith open(filename, \"r\") as infile:\n\t\tfor line in infile:\n\t\t\tif line.startswith(\">\"):\n\t\t\t\tif name is not None and skip_chrom is False:\n\t\t\t\t\tsequences[name] = sequence\n\n\t\t\t\tsequence = []\n\t\t\t\tname = line[1:].strip(\"\\n\")\n\t\t\t\tif include_chroms is not None and name not in include_chroms:\n\t\t\t\t\tskip_chrom = True\n\t\t\t\telif exclude_chroms is not None and name in exclude_chroms:\n\t\t\t\t\tskip_chrom = True\n\t\t\t\telse:\n\t\t\t\t\tskip_chrom = False\n\n\t\t\telse:\n\t\t\t\tif skip_chrom == False:\n\t\t\t\t\tsequence.extend(list(line.rstrip(\"\\n\").upper()))\n\n\tencodings = {}\n\tfor i, (name, sequence) in enumerate(sequences.items()):\n\t\tencodings[name] = sequence_to_ohe(sequence, ignore=ignore, \n\t\t\talphabet=alphabet, dtype=dtype, position=i,\n\t\t\tverbose=name if verbose else verbose)\n\n\treturn encodings\n\ndef bigwig_to_arrays(filename, include_chroms=None, exclude_chroms=None, \n\t fillna=0, dtype='float32'):\n\t\"\"\"Read in a bigWig file and output a dictionary of signal arrays.\n\n\tThis function will take in a filename, open it, and output the\n\tbasepair-resolution signal for the track for all desired chromosomes.\n\n\tParameters\n\t----------\n\tfilename : str\n\t\tThe path to the bigWig to open.\n\n\tinclude_chroms : set or tuple or list, optional\n\t\tThe exact names of chromosomes in the bigWig file to include, excluding\n\t\tall others. If None, include all chromosomes (except those specified by\n\t\texclude_chroms). Default is None.\n\n\texclude_chroms : set or tuple or list, optional\n\t\tThe exact names of chromosomes in the bigWig file to exclude, including\n\t\tall others. If None, include all chromosomes (or the set specified by\n\t\tinclude_chroms). Default is None.\n\n\tfillna : float or None, optional\n\t\tThe value to fill NaN values with. If None, keep them as is. Default is 0.\n\n\tdtype : str or numpy.dtype, optional\n\t\tThe data type of the returned encoding. Default is int8.\n\n\tReturns\n\t-------\n\tsignals : dict\n\t\tA dictionary of signal values where the keys are the names of the\n\t\tchromosomes and the values are arrays of signal values.\n\t\"\"\"\n\n\tsignals = {}\n\tchroms = []\n\n\tbw = pyBigWig.open(filename, \"r\")\n\tfor chrom in bw.chroms().keys():\n\t\tif include_chroms and chrom not in include_chroms:\n\t\t\tcontinue\n\t\telif exclude_chroms and chrom in exclude_chroms:\n\t\t\tcontinue\n\t\telse:\n\t\t\tsignal = bw.values(chrom, 0, -1, numpy=True).astype(dtype)\n\t\t\tif fillna is not None:\n\t\t\t\tsignal = numpy.nan_to_num(signal, nan=fillna, copy=False)\n\n\t\t\tsignals[chrom] = signal\n\n\treturn signals","sub_path":"ledidi/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"380724794","text":"import discord\r\n\r\nhelp = discord.Embed(title='도움말', description='도움이 필요할때 ```^도움말 or ^help``` 라고 해줘!!', color = 0x39c5bb)\r\nhelp.add_field(name='```^세카이검색```', value='세카이에 관한 정보를 볼수 있습니다', inline=True)\r\nhelp.set_footer(text='Made By Luen')\r\nhelp.set_thumbnail(url=\"https://media.discordapp.net/attachments/828467375337766962/828581378827485275/1.jpg?width=465&height=491\")\r\n\r\nsk_help = discord.Embed(title='세카이검색', description='세카이에 관한 정보 명령어 모음', color = 0x39c5bb)\r\nsk_help.add_field(name='음악', value='세카이에 수록된 곡 정보를 볼 수 있습니다\\nex)```^세카이검색 음악```', inline=False)\r\nsk_help.add_field(name='유닛', value='세카이에 유닛 정보를 볼 수 있습니다\\nex)```^세카이검색 유닛```', inline=False)\r\nsk_help.set_footer(text='Project SEKAI COLOURFUL STAGE! feat.HATSUNE MIKU')\r\nsk_help.set_thumbnail(url=\"https://cdn.discordapp.com/attachments/828959305478832198/828990365247209482/TMa_FBrjseeE0ZBQa0fve-dyW1j0YZHnNUzJeRR692EyKcNh6SQB04_ytzYE---4xgw512.png\")\r\n\r\nun_help = discord.Embed(title='프로젝트 세카이 유닛', description='유닛 목록',color=0x39c5bb)\r\nun_help.add_field(name='VIRTURE SINGER', value='ㅤ', inline=False)\r\nun_help.add_field(name='MORE MORE JUMP!', value='ㅤ', inline=False)\r\nun_help.add_field(name='Leo/need', value='ㅤ', inline=False)\r\nun_help.add_field(name='Vivid BAD SQUAD', value='ㅤ', inline=False)\r\nun_help.add_field(name='원더랜즈×쇼타임', value='ㅤ', inline=False)\r\nun_help.add_field(name='25시, 나이트코드에서.', value='ㅤ', inline=False)\r\nun_help.add_field(name='명령어', value='ex)```^세카이검색 유닛 모모점```', inline=False)\r\nun_help.set_image(url=\"https://cdn.discordapp.com/attachments/857996994676916234/858001981301850122/65319eabc477e721e6d5dde19508daac108bf74817f79b9061fe00e593d772fcbe7ad1ff333ccf07c36a4f695380d3feee0d.png\")\r\n\r\nms_help = discord.Embed(title='프로젝트 세카이 음악', description='ㅤ', color=0x39c5bb)\r\nms_help.add_field(name='검색하시면 곡의 정보가 나옵니다', value='일본어 검색은 안되요ㅠㅠ', inline=False)\r\nms_help.add_field(name='명령어', value='ex)```^세카이검색 음악 멜트```', inline=False)\r\nms_help.set_image(url=\"https://cdn.discordapp.com/attachments/857996994676916234/858001981301850122/65319eabc477e721e6d5dde19508daac108bf74817f79b9061fe00e593d772fcbe7ad1ff333ccf07c36a4f695380d3feee0d.png\")","sub_path":"help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"166437327","text":"from datetime import datetime\nfrom decimal import Decimal\nfrom typing import TypedDict, List, Tuple, Dict\n\nfrom peewee import fn, Case, Tuple as DBTuple\n\nfrom cockroachdb.modules.models import Customer, Item, Order, OrderLine\nfrom cockroachdb.modules.transactions.base import BaseTransaction\n\n\nclass PopularItemsOutput(TypedDict):\n \"\"\"\n Popular items output dict representation\n \"\"\"\n\n order_id: int\n entry_date: datetime\n first_name: str\n middle_name: str\n last_name: str\n quantity: Decimal\n item_id: int\n item_name: str\n\n\nclass OrderOutput(TypedDict):\n \"\"\"\n Order output dict representation\n \"\"\"\n\n order_id: int\n entry_date: datetime\n customer_name: str\n popular_items: List[str]\n\n\nclass ItemOutput(TypedDict):\n \"\"\"\n Item output dict representation\n \"\"\"\n\n name: str\n orders: set\n\n\nclass PopularItemsTransaction(BaseTransaction):\n \"\"\"\n Transaction for querying popular items\n\n Example:\n popular_items = PopularItemsTransaction(1, 1, 10)\n popular_items.run()\n \"\"\"\n\n def __init__(\n self, warehouse_id: int, district_id: int, orders_to_examine: int\n ):\n \"\"\"\n Initiate a transaction for retrieving popular items\n :param warehouse_id: warehouse identifier\n :param district_id: district identifier\n :param orders_to_examine: number of items to examine\n \"\"\"\n super().__init__()\n self.warehouse_id = warehouse_id\n self.district_id = district_id\n self.orders_to_examine = orders_to_examine\n\n def _execute(self) -> Tuple[List[PopularItemsOutput]]:\n \"\"\"\n Execute new payment transaction\n :return: relevant output information\n \"\"\"\n # Get order table joined with customer table\n order_customer_query = (\n Order.select(\n Order.id.alias(\"order_id\"),\n Order.district_id.alias(\"district_id\"),\n Order.warehouse_id.alias(\"warehouse_id\"),\n Order.entry_date.alias(\"entry_date\"),\n Customer.middle_name.alias(\"middle_name\"),\n Customer.first_name.alias(\"first_name\"),\n Customer.last_name.alias(\"last_name\"),\n )\n .join(\n Customer,\n on=(\n (Order.warehouse_id == Customer.warehouse_id)\n & (Order.district_id == Customer.district_id)\n & (Order.customer_id == Customer.id)\n ),\n )\n .where(\n (Order.warehouse_id == self.warehouse_id)\n & (Order.district_id == self.district_id)\n )\n .order_by(Order.entry_date.desc())\n .limit(self.orders_to_examine)\n .cte(\"order_customer_query\")\n )\n\n # Get order lines with maximum quantity, joined with item table\n OrderLineInner: OrderLine = OrderLine.alias()\n order_line_sum_qty_query = (\n OrderLineInner.select(\n OrderLineInner.warehouse_id.alias(\"warehouse_id\"),\n OrderLineInner.district_id.alias(\"district_id\"),\n OrderLineInner.order_id.alias(\"order_id\"),\n fn.SUM(OrderLineInner.quantity).alias(\"sum_qty\"),\n )\n .where(\n (OrderLineInner.warehouse_id == self.warehouse_id)\n & (OrderLineInner.district_id == self.district_id)\n )\n .group_by(\n OrderLineInner.warehouse_id,\n OrderLineInner.district_id,\n OrderLineInner.order_id,\n OrderLineInner.item_id,\n )\n .cte(\"order_line_sum_qty_query\")\n )\n order_line_max_qty_query = (\n order_line_sum_qty_query.select(\n order_line_sum_qty_query.c.order_id,\n fn.MAX(order_line_sum_qty_query.c.sum_qty),\n )\n .group_by(\n order_line_sum_qty_query.c.warehouse_id,\n order_line_sum_qty_query.c.district_id,\n order_line_sum_qty_query.c.order_id,\n )\n .with_cte(order_line_sum_qty_query)\n )\n\n customer_name_field = Case(\n None,\n (\n (\n order_customer_query.c.middle_name.is_null(),\n fn.CONCAT(\n order_customer_query.c.first_name,\n \" \",\n order_customer_query.c.last_name,\n ),\n ),\n ),\n fn.CONCAT(\n order_customer_query.c.first_name,\n order_customer_query.c.middle_name,\n order_customer_query.c.last_name,\n ),\n ).alias(\"customer_name\")\n\n popular_items_query = (\n OrderLine.select(\n order_customer_query.c.order_id,\n order_customer_query.c.entry_date,\n customer_name_field,\n fn.SUM(OrderLine.quantity).alias(\"quantity\"),\n Item.id.alias(\"item_id\"),\n Item.name.alias(\"item_name\"),\n )\n .join(\n order_customer_query,\n on=(\n (\n OrderLine.warehouse_id\n == order_customer_query.c.warehouse_id\n )\n & (\n OrderLine.district_id\n == order_customer_query.c.district_id\n )\n & (OrderLine.order_id == order_customer_query.c.order_id)\n ),\n )\n .join(Item, on=(OrderLine.item_id == Item.id))\n .group_by(\n order_customer_query.c.order_id,\n order_customer_query.c.entry_date,\n customer_name_field,\n Item.id,\n Item.name,\n )\n .having(\n DBTuple(\n order_customer_query.c.order_id, fn.SUM(OrderLine.quantity)\n ).in_(order_line_max_qty_query)\n )\n .order_by(\n order_customer_query.c.order_id.desc(),\n fn.SUM(OrderLine.quantity).desc(),\n )\n .with_cte(order_customer_query)\n )\n\n # Process query output\n return ([result for result in popular_items_query.dicts()],)\n\n def _output_result(self, popular_items: List[PopularItemsOutput]):\n \"\"\"\n Output execution result\n :param popular_items: list of popular items in PopularItemsOutput format\n :return: None\n \"\"\"\n\n def format_popular_item(name: str, quantity: Decimal):\n \"\"\"\n Format popular item to be printed in console\n :param name: item name\n :param quantity: item quantity\n :return: formatted popular item string\n \"\"\"\n return f\"{name} (QTY: {quantity})\"\n\n self.print(\n f\"Popular Items Summary from {self.orders_to_examine} Orders from Warehouse {self.warehouse_id}, District {self.district_id}:\",\n is_heading=True,\n )\n\n order_table_rows = []\n item_table_rows = []\n\n orders: Dict[int, OrderOutput] = {}\n items: Dict[int, ItemOutput] = {}\n for order_line in popular_items:\n order_id = order_line[\"order_id\"]\n item_id, item_name, item_qty = (\n order_line[\"item_id\"],\n order_line[\"item_name\"],\n order_line[\"quantity\"],\n )\n if item_id not in items.keys():\n items[item_id] = {\"orders\": set(), \"name\": item_name}\n if order_id not in orders.keys():\n orders[order_id] = {\n **order_line,\n \"popular_items\": [\n format_popular_item(item_name, item_qty)\n ],\n }\n else:\n orders[order_id][\"popular_items\"].append(\n format_popular_item(item_name, item_qty)\n )\n items[item_id][\"orders\"].add(order_id)\n\n for order in orders.values():\n order = order\n order_table_rows.append(\n [\n str(order[\"order_id\"]),\n order[\"entry_date\"].strftime(\"%b %d, %Y, %X (UTC)\"),\n order[\"customer_name\"],\n \"\\n\".join(order[\"popular_items\"]),\n ]\n )\n\n for item_id, item_output in sorted(\n items.items(),\n key=lambda item: len(item[1][\"orders\"]) * 1.0 / len(orders),\n reverse=True,\n ):\n percentage = len(item_output[\"orders\"]) * 1.0 / len(orders)\n item_table_rows.append(\n [\n str(item_id),\n item_output[\"name\"],\n \"{:2.2%}\".format(percentage),\n ]\n )\n\n self.print_table(\n columns=[\n {\"header\": \"Order Number\"},\n {\"header\": \"Order Date\"},\n {\"header\": \"Customer Name\"},\n {\"header\": \"Popular Items\"},\n ],\n rows=order_table_rows,\n )\n self.print_table(\n columns=[\n {\"header\": \"Item ID\"},\n {\"header\": \"Item Name\"},\n {\"header\": \"Percentage of Orders Containing This Item\"},\n ],\n rows=item_table_rows,\n )\n\n @property\n def transaction_name(self):\n \"\"\"\n Transaction name\n :return: transaction name\n \"\"\"\n return \"popular_items\"\n","sub_path":"cockroachdb/modules/transactions/popular_item.py","file_name":"popular_item.py","file_ext":"py","file_size_in_byte":9724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"57684126","text":"import discord\nfrom discordbot import betterbot, client\nfrom discord.ext import commands\nimport os\nimport random\nimport re\nimport asyncio\nfrom config import EDITOR_IDS, BASE_URL, ADMIN_IDS, BLACKLIST_IDS\nimport database\nimport utils\nblacklist_wait = 5\n# ACTUAL COMMANDS START HERE\n\n@betterbot.command(name='help',allowed=True)\nasync def help(message, *args):\n\tif message.message.author.id in BLACKLIST_IDS:\n\t\tawait asyncio.sleep(blacklist_wait)\n\tcommands = {\n\t\t'search ': 'Finds entries that match the query',\n\t\t'entry ': 'Shows the matching entry',\n\t\t'random': 'Gets a random entry',\n\t\t'request ': 'Lets noneditors request a Repldex entry',\n\t\t'selfentry': 'Gets your own entry if you have one.'\n\t}\n\tif message.author.id in EDITOR_IDS:\n\t\tcommands['selfentry '] = 'Links you to your entry (editor only)'\n\t\tcommands['newentry '] = 'Sends link to write new entry (editor only)'\n\t\tif message.author.id in ADMIN_IDS:\n\t\t\tcommands['link '] = 'Manually link non-editors to entries (admin only)'\n\t\t\tcommands['view_selfentry '] = 'View a users selfentry (admin only)'\n\t\t\tcommands['who_is_the_leader'] = 'tells you who the supreme leader is (admin only)'\n\t\t\tcommands['userinfo '] = 'get info on the mentioned user (admin only)'\n\t\t\tcommands['unlist '] = 'Toggles unlisting of entry (admin only)'\n\t\t\t#commands['neweditor '] = 'Make user editor (admin only)'\n\tcontent = []\n\tprefix = message.prefix\n\tfor command in commands:\n\t\tcontent.append(\n\t\t\tf'{prefix}**{command}** - {commands[command]}'\n\t\t)\n\n\tembed = discord.Embed(\n\t\ttitle='Commands',\n\t\tdescription='\\n'.join(content)\n\t)\n\tawait message.send(embed=embed)\n\nasync def create_entry_embed(entry_data, author_id=None,raw_entry=False):\n\tif(not raw_entry):\n\t\thtml = entry_data['content']\n\t\tcontent = utils.html_to_markdown(html)\n\t\n\t\tcontent_ending = ''\n\t\n\t\tif len(content) > 2048:\n\t\t\tcontent = content[:2045 - len(content_ending)] + '...'\n\t\tcontent += content_ending\n\t\ttitle = utils.url_title(entry_data['title'])\n\t\tview_url = f'{BASE_URL}/entry/{title}'\n\t\tview_url = view_url\n\t\tembed = discord.Embed(\n\t\t\ttitle=entry_data['title'],\n\t\t\tdescription=content,\n\t\t\turl=view_url\n\t\t)\n\t\tif entry_data.get('image'):\n\t\t\tembed.set_thumbnail(url=entry_data['image']['src'])\n\t\n\t\treturn embed\n\telse:\n\t\tentry_data = dict(entry_data)\n\t\tcontent = entry_data['nohtml_content']\n\t\tcontent_ending = ''\n\t\tif len(content) > 1024:\n\t\t\tcontent = content[:1021 - len(content_ending)] + '...'\n\t\ttry: del entry_data['image']\n\t\texcept: pass\n\t\tentry_data['nohtml_content'] = content\n\t\tdel entry_data['content']\n\t\tdel entry_data['history']\n\t\treturn utils.embed_from_dict(entry_data,color=0x00ff00,title=\"raw entry data\")\n\n@betterbot.command(name='search')\nasync def search_entries(message, *args):\n\tnumbers = (\n\t\t'1️⃣',\n\t\t'2️⃣',\n\t\t'3️⃣',\n\t\t'4️⃣',\n\t\t'5️⃣',\n\t\t'6️⃣',\n\t\t'7️⃣',\n\t\t'8️⃣',\n\t\t'9️⃣',\n\t\t'🔟'\n\t)\n\tsearch_query = ' '.join(args)\n\tfound = await database.search_entries(search_query)\n\tif found:\n\t\tcontent = []\n\t\tfor i, result in enumerate(found, 1):\n\t\t\ttitle = result['title']\n\t\t\tcontent.append(f'{i}) {title}')\n\t\tcontent = '\\n'.join(content)\n\telse:\n\t\tcontent = 'No results'\n\tembed = discord.Embed(\n\t\ttitle=f'Results for {search_query}',\n\t\tdescription=content\n\t)\n\t# if found:\n\t# \tembed.set_footer(text=f'React with {one_emoji} to get the first result')\n\tmsg = await message.send(embed=embed)\n\tif found:\n\t\tfor emoji in numbers[:len(found)]:\n\t\t\tawait msg.add_reaction(emoji)\n\t\tdef check(reaction, user):\n\t\t\tmessage_matches = reaction.message.id == msg.id\n\t\t\tuser_matches = user == message.author\n\t\t\temoji_matches = str(reaction.emoji) in numbers\n\t\t\treturn message_matches and user_matches and emoji_matches\n\t\treaction, _ = await client.wait_for('reaction_add', check=check)\n\t\temoji = str(reaction.emoji)\n\t\temoji_pos = numbers.index(emoji)\n\t\tembed = await create_entry_embed(found[emoji_pos], author_id=message.author.id)\n\t\tawait message.send(embed=embed)\n\n@betterbot.command(name='entry', allowed=True)\nasync def show_entry(message, *args):\n\tif message.message.author.id in BLACKLIST_IDS:\n\t\tawait asyncio.sleep(blacklist_wait)\n\tsearch_query = ' '.join(args)\n\tfound = await database.search_entries(search_query, limit=1)\n\tif found:\n\t\tembed = await create_entry_embed(found[0], author_id=message.author.id)\n\t\tawait message.send(embed=embed)\n\telse:\n\t\tembed = discord.Embed(\n\t\t\ttitle=\"This entry doesn't exist\"\n\t\t)\n\t\tsearch_query_url_encoded = utils.url_title(search_query)\n\t\tedit_url = f'{BASE_URL}/edit?title={search_query_url_encoded}'\n\t\tedit_url = edit_url\n\t\tif message.author.id in EDITOR_IDS:\n\t\t\tembed.description = f'[Click here to write it!]({edit_url})'\n\t\tawait message.send(embed=embed)\n\n@betterbot.command(name='raw_entry')\nasync def show_raw_entry(message, *args):\n\tif message.author.id not in ADMIN_IDS: return\n\tsearch_query = ' '.join(args)\n\tfound = await database.search_entries(search_query, limit=1)\n\tif found:\n\t\tdata = await create_entry_embed(found[0], author_id=message.author.id, raw_entry=True)\n\t\tawait message.send(embed=data)\n\telse:\n\t\tembed = discord.Embed(\n\t\t\ttitle=\"This entry doesn't exist\"\n\t\t)\n\t\tawait message.send(embed=embed)\n\n\n\n@betterbot.command(name='selfentry')\nasync def personal_entry(message, *args):\n\tsearch_query = ' '.join(args)\n\tif not search_query:\n\t\tentry_id = await database.get_personal_entry(message.author.id)\n\t\tif not entry_id:\n\t\t\tif message.author.id not in EDITOR_IDS: \n\t\t\t\treturn await message.send(\"You don't have a personal entry set yet. An admin needs to set one for you\")\n\t\t\telse:\n\t\t\t\treturn await message.send(\"You haven't set a personal entry yet\")\n\t\tentry = await database.get_entry(entry_id)\n\t\tembed = await create_entry_embed(entry, author_id=message.author.id)\n\t\treturn await message.send(embed=embed)\n\tif message.author.id not in EDITOR_IDS: \n\t\treturn await message.send(\"Only editors can set personal entries\")\n\tfound = await database.search_entries(search_query, limit=1)\n\tif found:\n\t\tentry = found[0]\n\t\ttitle = entry['title']\n\t\tentry_id = entry['_id']\n\t\tawait database.set_personal_entry(message.author.id, entry_id)\n\t\tawait message.send(f'Set your personal entry to `{title}`')\n\telse:\n\t\tawait message.send('Invalid entry')\n\n@betterbot.command(name='userinfo')\nasync def user_info(message,member:utils.Member):\n\tif message.author.id not in ADMIN_IDS: return\n\tembed = discord.Embed(title='user info',description=f'info on <@{member.id}>',color=0x00ff00)\n\teditor = False\n\tif(member.id in EDITOR_IDS):\n\t\teditor = True\n\tadmin = False\n\tif(member.id in ADMIN_IDS):\n\t\tadmin = True\n\t\n\tentry_id = await database.get_personal_entry(member.id)\n\t\n\tif(entry_id==None):\n\t\tselfentry='None'\n\telse:\n\t\tentry = await database.get_entry(entry_id)\n\t\tselfentry=entry['title']\n\tembed.add_field(name='editor',value=str(editor),inline=True)\n\tembed.add_field(name='admin',value=str(editor),inline=True)\n\tembed.add_field(name='selfentry',value=f'`{selfentry}`',inline=False)\n\tawait message.send(embed=embed)\n\n@betterbot.command(name='view_selfentry')\nasync def view_self_entry(message,member: utils.Member):\n\tif message.author.id not in ADMIN_IDS: return\n\tentry_id = await database.get_personal_entry(member.id)\n\tentry = await database.get_entry(entry_id)\n\ttry:\n\t\tembed = await create_entry_embed(entry, author_id=message.author.id)\n\texcept:\n\t\treturn await message.send(\"no selfentry exists for dis person\")\n\treturn await message.send(embed=embed)\n\t\n@betterbot.command(name='who_is_the_leader')\nasync def leader(message, *args):\n\tif(message.channel.id in utils.auto_delete_channels): return\n\tif message.author.id not in ADMIN_IDS: return\n\tawait message.send('PRUSSIA IS THE SUPREME LEADER')\n\tpass\n\n@betterbot.command(name='request')\nasync def suggest(ctx, *args):\n\tsuggestions_channel = client.get_channel(753331575034347642)\n\tif args != tuple():\n\t\tembed = discord.Embed(\n\t\t\ttitle=\"Entry Suggestion\",\n\t\t\tdescription=' '.join(args)\n\t\t)\n\t\tembed.set_footer(text='Requested by {}'.format(ctx.message.author.name))\n\t\tawait ctx.send(\"Suggestion sent.\")\n\t\treturn await suggestions_channel.send(embed=embed)\n\treturn await ctx.send(\"No suggestion was given\")\n\n'''@betterbot.command(name='role')\nasync def role(message, role):\n\tif message.author.id not in ADMIN_IDS: return\n\tuser = message.author\n\trole = message.guild.get_role(int(role))\n\tawait role.delete()\n\t#await user.remove_roles(role)'''\n\n@betterbot.command(name='unlist')\nasync def unlist(message,entry_id):\n\tif message.author.id not in ADMIN_IDS: return\n\tentry_data = await database.get_entry(entry_id)\n\tif(entry_data==None): return\n\tunlist = not entry_data['unlisted']\n\tawait database.edit_entry(\n\t\ttitle=entry_data['title'],\n\t\tentry_id=entry_id,\n\t\tcontent=entry_data['content'],\n\t\tunlisted=unlist\n\t)\n\tembed = discord.Embed(title='toggle unlist',description='toggling entry being listed/unlisted',color=0x00ff00)\n\tembed.add_field(name='entry name',value=entry_data['title'],inline=True)\n\tembed.add_field(name='entry id',value=entry_id,inline=True)\n\tembed.add_field(name='entry link',value=BASE_URL+'/entry/'+entry_id,inline=True)\n\tembed.add_field(name='unlisted',value=str(unlist),inline=False)\n\tawait message.send(embed=embed)\n\t\n\t\n\n@betterbot.command(name='link')\nasync def link_entry(ctx, *args):\n\tif ctx.message.author.id not in ADMIN_IDS: return\n\ttry:\n\t\tmember = ctx.message.mentions[0]\n\texcept:\n\t\treturn ctx.send('No mentions in command')\n\targs = list(args)\n\tdel args[0]\n\tentry_name = tuple(args)\n\tsearch_query = ' '.join(entry_name)\n\tfound = await database.search_entries(search_query, limit=1)\n\tif found:\n\t\tentry = found[0]\n\t\ttitle = entry['title']\n\t\tentry_id = entry['_id']\n\t\tawait database.set_personal_entry(member.id, entry_id)\n\t\tawait ctx.send(\n\t\t\tembed=discord.Embed(\n\t\t\t\tdescription=f'Set {member.mention} personal entry to `{title}`'\n\t\t\t)\n\t\t)\n\telse:\n\t\tawait ctx.send('Invalid entry')\n\t\t\n@betterbot.command(name='newentry')\nasync def new_entry(message, *args):\n\tsearch_query = ' '.join(args)\n\tsearch_query_url_encoded = utils.url_title(search_query)\n\tedit_url = f'{BASE_URL}/edit?title={search_query_url_encoded}'\n\tedit_url = edit_url\n\tif message.author.id in EDITOR_IDS:\n\t\tembed = discord.Embed(\n\t\ttitle=\"Write \"+search_query,\n\t\tdescription=f'[Click here to write it!]({edit_url})'\n\t\t)\n\t\tfound = await database.search_entries(search_query, limit=1)\n\t\tif found:\n\t\t\tembed.set_footer(text='Alert: There may be an entry with the same/similar name or topic.') \n\telse:\n\t\tembed = discord.Embed(\n\t\t\ttitle=\"This command is editor only\"\n\t\t)\n\tawait message.send(embed=embed)\n\t\t\n@betterbot.command(name='random')\nasync def random_entry(message, *args):\n\tentry = await database.get_random_entry()\n\n\tembed = await create_entry_embed(entry, author_id=message.author.id)\n\tawait message.send(embed=embed)\n\n'''@betterbot.command(name=\"neweditor\")\nasync def new_editor(message, member: utils.Member):\n\tprint('new editor command')\n\tif message.author.id not in ADMIN_IDS: return\n\n\twith open(\"editors.txt\") as editors:\n\t\tif str(member.id) in editors.read().split(\"\\n\"):\n\t\t\tawait message.send(embed=discord.Embed(\n\t\t\t\tdescription=\"This user is already an editor!\",\n\t\t\t\tcolour=discord.Colour.red()\n\t\t\t))\n\t\t\treturn\n\n\twith open(\"editors.txt\",\"a\") as editors:\n\t\teditors.write(\"\\n\")\n\t\teditors.write(str(member.id))\n\t\tEDITOR_IDS.append(member.id)\n\t\tawait message.send(embed=discord.Embed(\n\t\t\tdescription=f\"Added {member.mention} as an editor!\",\n\t\t\tcolour=discord.Colour.green()\n\t\t))\n\n@betterbot.command(name=\"removeeditor\")\nasync def new_editor(message, member: utils.Member):\n\tprint('remove editor command')\n\tif message.author.id not in ADMIN_IDS: return\n\n\twith open(\"editors.txt\") as editors:\n\t\teditorlist=editors.read().split(\"\\n\")\n\t\tif str(member.id) not in editorlist:\n\t\t\tawait message.send(embed=discord.Embed(\n\t\t\t\tdescription=\"This user is not an editor!\",\n\t\t\t\tcolour=discord.Colour.red()\n\t\t\t))\n\t\t\treturn\n\n\teditorlist.remove(str(member.id))\n\twith open(\"editors.txt\",\"w\") as editors:\n\t\teditors.write(\"\\n\".join(editorlist))\n\t\tEDITOR_IDS.remove(member.id)\n\t\tawait message.send(embed=discord.Embed(\n\t\t\tdescription=f\"Removed {member.mention} from editors!\",\n\t\t\tcolour=discord.Colour.green()\n\t\t))'''\n","sub_path":"commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":12121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"518965053","text":"import argparse\nimport sqlite3\n\nfrom redminelib import Redmine, exceptions\nfrom telegram import Bot, error\nfrom datetime import datetime, timedelta\n\nimport config\n\nDB_PATH = \"database/data.db\"\nMESSAGE_1 = \"Your {0} project debt is {1:.1f} hours!\"\nMESSAGE_2 = \"{0} debts on the {1} project {2:.1f} hours!\"\n\n\ndef hours(info_var):\n return round(sum([h.hours for h in info_var]), 1)\n\n\nparser = argparse.ArgumentParser(description=\"Launch python bot.\")\nparser.add_argument(\"-r\", action=\"store_true\")\nmain_token = parser.parse_args()\nif main_token.r:\n bot = Bot(token=config.main_token)\nelse:\n bot = Bot(token=config.test_token)\n\nconn = sqlite3.connect(DB_PATH)\nc = conn.cursor()\nc.execute(\"SELECT username, password FROM users\")\nusers = c.fetchall()\ninfo = {}\nproject_id = int()\nbad_usernames = []\nfor user in users:\n redmine = Redmine(\"https://ximc.ru\", key=user[1])\n try:\n rm_user = redmine.auth()\n except exceptions.AuthError:\n bad_usernames.append(user[0])\n continue\n c.execute(\"SELECT project, percent, log_id FROM requirements WHERE username='{0}'\".format(user[0]))\n reqs = c.fetchall()\n if reqs is not None:\n debts = {}\n for req in reqs:\n c.execute(\"SELECT date FROM log WHERE id={0}\".format(req[2]))\n date = datetime.strptime(\"{0}\".format(c.fetchone()), \"('%Y-%m-%d %H:%M',)\")\n for project in redmine.project.all():\n if req[0] == project.name:\n project_id = project.id\n info_all = redmine.time_entry.filter(user_id=rm_user.id, from_date=date)\n info_proj = redmine.time_entry.filter(user_id=rm_user.id, from_date=date,\n project_id=\"{0}\".format(project_id))\n info_yesterday = redmine.time_entry.filter(user_id=rm_user.id, from_date=datetime.today() - timedelta(2))\n try:\n hours_all = hours(info_all)\n hours_proj = hours(info_proj)\n hours_yesterday = hours(info_yesterday)\n except exceptions.ForbiddenError:\n continue\n else:\n if hours_yesterday > 1:\n if (hours_all * req[1] / 100) > hours_proj:\n debt = hours_all * req[1] / 100 - hours_proj\n debts[req[0]] = debt\n info[user[0]] = debts.copy()\n for i in range(0, len(debts)):\n debt = debts.popitem()\n c.execute(\"SELECT telegram_id FROM users WHERE username='{0}'\".format(user[0]))\n user_id = c.fetchone()[0]\n try:\n bot.send_message(chat_id=user_id, text=MESSAGE_1.format(debt[0], debt[1]))\n except error.BadRequest:\n bad_usernames.append(user[0])\n continue\n else:\n continue\n\nc.execute(\"SELECT username, subs FROM users\")\nsubs_info = c.fetchall()\nfor user in subs_info:\n if user[0] in bad_usernames:\n continue\n elif user[1] is not None:\n for sub in user[1].split():\n if sub in bad_usernames:\n continue\n else:\n debts = info[sub].copy()\n for i in range(0, len(debts)):\n debt = debts.popitem()\n c.execute(\"SELECT telegram_id FROM users WHERE username='{0}'\".format(user[0]))\n user_id = c.fetchone()[0]\n try:\n bot.send_message(chat_id=user_id, text=MESSAGE_2.format(sub, debt[0], debt[1]))\n except error.BadRequest:\n continue\n","sub_path":"dept_count.py","file_name":"dept_count.py","file_ext":"py","file_size_in_byte":3606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"159681976","text":"# -*- coding: utf-8 -*-\nimport unittest\nimport numpy as np\n\nimport turret\nimport turret.layers as L\n\nfrom util import execute_inference\n\n\nclass ReduceTest(unittest.TestCase):\n def test_sum(self):\n N, C, H, W = 3, 5, 7, 11\n input = np.random.rand(N, C, H, W).astype(np.float32)\n\n def build_network(network):\n h = network.add_input(\"input\", turret.DataType.FLOAT,\n turret.Dimensions.CHW(C, H, W))\n h = L.reduce(h, turret.ReduceOperation.SUM, axes=(0, 1))\n network.mark_output(\"output\", h)\n actual = execute_inference({\"input\": input}, build_network)\n\n expect = np.sum(input, axis=(1, 2), keepdims=False)\n self.assertEqual(expect.shape, actual.shape)\n self.assertTrue(np.allclose(expect, actual))\n","sub_path":"tests/layers/reduce_test.py","file_name":"reduce_test.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"120743037","text":"# Copyright 2018 Jiří Janoušek \n# Licensed under BSD-2-Clause license - see file LICENSE for details.\n\nimport json\nfrom typing import List, Any, Optional, Dict, Type, ClassVar\nimport os\nimport shutil\n\nfrom fxwebgen import imaging\nfrom fxwebgen.context import Context\nfrom fxwebgen.objects import Thumbnail\nfrom fxwebgen.pages import MarkdownPage, HtmlPage, Page\nfrom fxwebgen.postprocessor import PostProcessor\nfrom fxwebgen.resources import ResourceManager\n\nFORCE_ALL = 'all'\nFORCE_PAGES = 'pages'\nFORCE_THUMBNAILS = 'thumbnails'\nFORCE_STATIC_FILES = 'static_files'\nFORCE_TEMPLATE = 'template'\nFORCE_REBUILD_CHOICES: List[str] = [FORCE_ALL, FORCE_PAGES, FORCE_THUMBNAILS, FORCE_STATIC_FILES, FORCE_TEMPLATE]\n\n\nclass Generator:\n ctx: Context\n post_processor: PostProcessor\n page_factories: ClassVar[List[Type[Page]]] = [MarkdownPage, HtmlPage]\n thumbnails: Dict[str, Dict[str, Thumbnail]]\n resources: ResourceManager\n\n def __init__(self, ctx: Context, *,\n post_processor: Optional[PostProcessor] = None,\n resources: Optional[ResourceManager] = None) -> None:\n self.ctx = ctx\n self.post_processor = post_processor or PostProcessor()\n self.thumbnails = {}\n self.resources = resources or ResourceManager()\n self.pages_kind = self.resources.add_kind('pages')\n self.static_files_kind = self.resources.add_kind('static_files')\n self.thumbnails_kind = self.resources.add_kind('thumbnails')\n\n def purge(self) -> None:\n if os.path.isdir(self.ctx.output_dir):\n shutil.rmtree(self.ctx.output_dir, ignore_errors=True)\n\n def build(self, force: Optional[List[str]] = None) -> None:\n if force is None:\n force = []\n elif FORCE_ALL in force:\n force = FORCE_REBUILD_CHOICES\n self.before_building_pages()\n if FORCE_TEMPLATE in force:\n self.ctx.templater.clear_cache()\n force.append(FORCE_PAGES)\n self.build_pages(force=FORCE_PAGES in force)\n self.after_building_pages()\n self.generate_thumbnails(force=FORCE_THUMBNAILS in force)\n self.copy_static_files(force=FORCE_STATIC_FILES in force)\n self.remove_stale_files()\n\n def before_building_pages(self) -> None:\n pass\n\n def after_building_pages(self) -> None:\n pass\n\n def build_pages(self, *, force: bool = False) -> None:\n kind = self.pages_kind\n old_pages = {item.source: item for item in kind.resources}\n old_thumbnails = self.thumbnails\n self.thumbnails = {}\n self.resources.remove_by_kind(kind)\n assert self.ctx.pages_dir\n for root, _dirs, files in os.walk(self.ctx.pages_dir):\n for path in files:\n if path.endswith(('.md', '.html', '.html')):\n path = os.path.join(root, path)\n resource = old_pages.get(path)\n if not force and resource and resource.fresh:\n self.thumbnails[path] = old_thumbnails.get(path, {})\n self.resources.add(kind, resource.source, resource.target)\n else:\n default_path = path[len(self.ctx.pages_dir):]\n page = self.parse_page(path, default_path)\n self.thumbnails[page.source] = page.thumbnails\n assert page.target\n resource = self.resources.add(kind, page.source, page.target)\n if force or not resource.fresh:\n self.build_page(page)\n\n def parse_page(self, source: str, default_path: str) -> Page:\n page = self._process_source(source, default_path)\n self._process_metadata(page)\n return page\n\n def build_page(self, page: Page) -> Page:\n self._load_datasets_for_page(page)\n self._process_page(page)\n self._write_page(page)\n return page\n\n def _process_source(self, source: str, default_path: str) -> Page:\n page = None\n for factory in self.page_factories:\n if factory.test(source):\n page = factory(self.ctx, source, default_path)\n break\n assert page, f'No page factory for \"{source}\".'\n page.process()\n return page\n\n def _process_metadata(self, page: Page) -> None:\n path_prefix = self.ctx.path_prefix\n meta = page.metadata\n meta.setdefault('title', os.path.splitext(os.path.basename(page.source))[0])\n meta.setdefault('template', self.ctx.default_template)\n\n url_deprecated = None\n if 'url' in meta:\n url_deprecated = meta['url']\n print(f'Warning: \"URL: {url_deprecated}\" meta directive is deprecated.')\n if not url_deprecated.startswith('/'):\n url_deprecated = '/' + url_deprecated\n\n save_as_deprecated = None\n if 'save_as' in meta:\n save_as_deprecated = meta['save_as']\n print(f'Warning: \"save_as: {save_as_deprecated}\" meta directive is deprecated.')\n\n path = meta.get('path', url_deprecated or page.default_path)\n if not path.startswith('/'):\n path = '/' + path\n if not path.endswith(('/', '.html', '.htm')):\n path += '/'\n meta['canonical_path'] = meta['path'] = '/' + path_prefix + path if path_prefix else path\n\n if save_as_deprecated:\n filename = save_as_deprecated\n else:\n filename = (path + 'index.html' if path.endswith('/') else path)[1:]\n\n root = ('../' * filename.count('/')).rstrip('/') or '.'\n meta['filename'] = filename\n meta['webroot'] = root\n meta['path_prefix'] = '/' + path_prefix if path_prefix else ''\n page.target = os.path.join(self.ctx.output_dir, page.filename)\n\n def _load_datasets_for_page(self, page: Page) -> None:\n meta = page.metadata\n\n datasets = {}\n for name in meta.get('datasets', '').split(','):\n name = name.strip()\n if name:\n name = name.lower().replace(' ', '_').replace('-', '_')\n datasets[name] = self.get_dataset(name)\n meta['datasets'] = datasets\n\n snippets: Dict[str, str] = {}\n if self.ctx.enable_snippets:\n for original_name in meta.get('snippets', '').split(','):\n original_name = original_name.strip()\n normalized_name = original_name.lower().replace(' ', '_').replace('-', '_')\n if original_name and normalized_name not in snippets:\n snippets[original_name] = snippets[normalized_name] = self.ctx.templater.render(\n [f'snippets/{normalized_name}.html'], meta)\n meta['snippets'] = snippets\n\n def _process_page(self, page: Page) -> None:\n meta = page.metadata\n body = page.body or ''\n if self.ctx.enable_snippets:\n snippets: Dict[str, str] = meta['snippets']\n for name, content in snippets.items():\n body = body.replace(f'[Snippet: {name}]', content)\n body = body.replace(f'[snippet: {name}]', content)\n page.body = body\n self.post_processor.process_page(self.ctx, page)\n\n def _write_page(self, page: Page) -> None:\n template = page.metadata['template']\n target = page.target\n assert target\n print(f'Page: \"{page.source}\" → \"{target}\" = {page.path} {page.webroot}')\n variables = {}\n variables.update(page.metadata)\n variables['body'] = page.body\n variables['toc'] = page.toc\n os.makedirs(os.path.dirname(target), exist_ok=True)\n with open(target, \"wt\") as fh:\n fh.write(self.ctx.templater.render(template + '.html', variables))\n\n def copy_static_files(self, *, force: bool = False) -> None:\n kind = self.static_files_kind\n self.resources.remove_by_kind(kind)\n for static_dir in self.ctx.static_dirs:\n target_dir = os.path.join(self.ctx.output_dir, os.path.basename(static_dir))\n print(f'Dir: \"{static_dir}\" → \"{target_dir}\"')\n os.makedirs(target_dir, exist_ok=True)\n prefix_len = len(static_dir) + 1\n for source_root, dirs, files in os.walk(static_dir):\n target_root = os.path.join(target_dir, source_root[prefix_len:])\n for path in files:\n source = os.path.join(source_root, path)\n target = os.path.join(target_root, path)\n resource = self.resources.add(kind, source, target)\n if force or not resource.fresh:\n shutil.copy2(source, target)\n for path in dirs:\n target = os.path.join(target_root, path)\n os.makedirs(target, exist_ok=True)\n\n def get_dataset(self, name: str) -> Any:\n try:\n return self.ctx.datasets[name]\n except KeyError:\n if self.ctx.datasets_dir:\n path = os.path.join(self.ctx.datasets_dir, name + \".json\")\n with open(path) as fh:\n dataset = json.load(fh)\n else:\n dataset = None\n self.ctx.datasets[name] = dataset\n return dataset\n\n def generate_thumbnails(self, *, force: bool = False) -> None:\n kind = self.thumbnails_kind\n self.resources.remove_by_kind(kind)\n static_dirs = self.ctx.static_dirs\n output_dir = self.ctx.output_dir\n for thumbnails in self.thumbnails.values():\n for thumbnail in thumbnails.values():\n for static_dir in static_dirs:\n prefix = os.path.basename(static_dir) + '/'\n if thumbnail.original_url.startswith(prefix):\n source = os.path.join(static_dir, thumbnail.original_url[len(prefix):])\n target = os.path.join(output_dir, thumbnail.filename)\n resource = self.resources.add(kind, source, target)\n if force or not resource.fresh:\n print(f'Thumbnail: {source} → {target}.')\n os.makedirs(os.path.dirname(target), exist_ok=True)\n imaging.create_thumbnail(source, target, thumbnail.width, thumbnail.height)\n break\n else:\n raise ValueError(f'Cannot find {thumbnail.original_url}.')\n\n def remove_stale_files(self) -> None:\n self.resources.remove_stale_files(self.ctx.output_root)\n","sub_path":"fxwebgen/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":10662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"166766648","text":"# valuefy/method4-shell.py\n# Creates a file named method4.txt containing a list of internal URLs\n\nfrom subprocess import check_output, CalledProcessError\nfrom valuefy import URL, write_to_file\n\nset_of_urls = set()\n\n\ndef run_command(url):\n\n \"\"\"\n This is a recursive function which runs the 'lynx' shell command\n for a URL and returns the standard output as a list.\n \"\"\"\n\n command = 'lynx -dump -listonly \"{}\" | grep -o \"https:.*\"' \\\n '| sort -u | grep -vwE \"(osd.xml|plus.google.com)\"'.format(url)\n std_out = check_output(command, shell=True)\n\n return std_out.decode().split('\\n')\n\n\ndef internal_url_scraper(url):\n\n \"\"\"\n This function recursively calls itself for each unique URL returned\n by the run_command() function.\n \"\"\"\n\n global set_of_urls\n\n # stopping condition\n if len(set_of_urls) > 100:\n return\n\n try:\n urls = run_command(url)\n for _url in urls:\n\n if _url not in set_of_urls:\n\n set_of_urls.add(_url)\n write_to_file('method4.txt', _url)\n\n if 'medium.com' in _url:\n internal_url_scraper(_url)\n\n except CalledProcessError:\n pass\n\nif __name__ == '__main__':\n\n internal_url_scraper(URL)\n","sub_path":"scraper/method4-shell.py","file_name":"method4-shell.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"124120623","text":"fname=input(\"enter file name\")\ntry_count=3\nwith open(fname) as file:\n lines = file.readlines()\n lines = [line.rstrip() for line in lines]\nwhile(try_count):\n line_no=int(input(\"Enter line number to read \"))\n try:\n print(lines[line_no-1])\n try_count=0\n except:\n print('Line number exceeded length of file')\n try_count-=1\nfreq={}\nfor i in lines:\n words=i.split(\" \")\n for word in words:\n if (word in freq):\n freq[word]+=1\n else:\n freq[word]=1\ngoing=True\nwhile(going):\n check=input(\"Enter word to see frequency \")\n try:\n print(freq[check])\n going=False\n except:\n print(\"Word in not available in file\")\n finally:\n still_going=\"Y\"\n if(going):\n still_going=input(\"Do you want to continue irrespective of the error? Y/N? \")\n if(still_going==\"N\"):\n going=False\n \n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"637913458","text":"\n\nfrom xai.brain.wordbase.nouns._ligament import _LIGAMENT\n\n#calss header\nclass _LIGAMENTS(_LIGAMENT, ):\n\tdef __init__(self,): \n\t\t_LIGAMENT.__init__(self)\n\t\tself.name = \"LIGAMENTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"ligament\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_ligaments.py","file_name":"_ligaments.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"98644482","text":"from typing import Dict, List\n\nfrom jina.executors.rankers import Match2DocRanker\nfrom jina.executors.decorators import batching\n\n\nclass DummyRanker(Match2DocRanker):\n \"\"\"\n :class:`LevenshteinRanker` Computes the negative Levenshtein distance\n between a query and its matches. The distance is negative, in order to\n achieve a bigger=better sorting in the respective driver.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.match_required_keys = ['tags__dummy_score']\n\n @batching(slice_nargs=3)\n def score(\n self,\n old_match_scores: List[Dict],\n queries_metas: List[Dict],\n matches_metas: List[List[Dict]],\n ) -> List[List[float]]:\n return [\n [m['tags__dummy_score'] for m in match_meta] for match_meta in matches_metas\n ]\n","sub_path":"tests/integration/evaluation/rank/yaml/dummy_ranker.py","file_name":"dummy_ranker.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"273939001","text":"#!/usr/bin/python\n\nimport heapq\nimport math \nimport numpy as np\nimport rtreelib\nimport time\n\n \nclass SingleDimensionalQuery():\n \"\"\"The 'Single Dimensional Query Intervals' algorithm\"\"\"\n\n def __init__(self, query_start, query_end, dimension, rtree, logfile):\n \"\"\"\n The constructor of the class\n\n Parameters: query_start -> [x, y]\n query_end -> [x, y]\n dimension -> int that refers to the dimension the query took place\n rtree -> reference to the implementation of the Rtree with the \n data points\n logfile -> reference to the logfile object\n \"\"\"\n \n self.qs = query_start\n self.qe = query_end\n self.dim = dimension\n self.rtree = rtree\n self.logfile = logfile\n # Range Skyline Set\n self.RSS = []\n \n # The priority heaps\n self.main = []\n self.secondary = [] \n\n self.garbage_time = 0\n self.maximum_main_size = 0\n self.maximum_secondary_size = 0\n self.domination_checks = 0\n \n\n def range_skyline_computation(self):\n \"\"\"\n The backbone of the algorithms implementation\n \"\"\"\n\n # Get the Root node's entries\n for entry in self.rtree.root.entries:\n segment = [self.qs, self.qe]\n self.insert_into_main_heap(entry, segment)\n\n if len(self.main) > self.maximum_main_size:\n self.maximum_main_size = len(self.main)\n \n secondary_heap_empty = False\n while not secondary_heap_empty:\n while len(self.main) != 0:\n e, Le = self.remove_top_entry(self.main)\n \n e_mbr_mindist = self.get_mbr_mindist(e)\n Lee = self.iterate_RSS_for_nonDomination_segment(e_mbr_mindist, Le)\n try: \n # Different starting points\n if Lee[0] != Le[0]:\n # Check if data point or mbr and insert analogously\n if e.is_leaf:\n # Data Point\n self.insert_into_secondary_heap(e, Lee)\n else:\n # MBR\n #self.insert_into_secondary_heap(e, Le)\n for ee in e.child.entries:\n self.insert_into_secondary_heap(ee, Le)\n # Check maximum heap size\n if len(self.secondary) > self.maximum_secondary_size:\n self.maximum_secondary_size = len(self.secondary)\n \n # Same starting points\n else:\n # MBR \n if not e.is_leaf: \n Lee = Le\n for ee in e.child.entries:\n ee_mbr_mindist = self.get_mbr_mindist(ee)\n Leee = self.iterate_RSS_for_nonDomination_segment(ee_mbr_mindist, Lee)\n try: \n # Different starting points\n if Leee[0] != Lee[0]:\n if ee.is_leaf:\n # Data Point\n self.insert_into_secondary_heap(ee, Leee)\n else:\n # MBR\n #self.insert_into_secondary_heap(ee, Lee)\n for eee in ee.child.entries:\n self.insert_into_secondary_heap(eee, Lee)\n # Check maximum heap size\n if len(self.secondary) > self.maximum_secondary_size:\n self.maximum_secondary_size = len(self.secondary)\n else:\n if ee.is_leaf:\n # Data Point\n self.insert_into_main_heap(ee, Leee)\n else:\n # MBR\n #self.insert_into_main_heap(ee, Lee)\n for eee in ee.child.entries:\n self.insert_into_main_heap(eee, Lee)\n # Check maximum heap size\n if len(self.main) > self.maximum_main_size:\n self.maximum_main_size = len(self.main)\n except TypeError:\n pass\n # Leaf - Data Point\n else:\n for index, rss_entry in enumerate(self.RSS):\n rss_point, Lp = rss_entry[0], rss_entry[1]\n # Check for intersection\n Lp_inter_Lee = self.segment_intersection(Lp, Lee)\n if Lp_inter_Lee != None:\n Lpp = self.point_domination(e.data, rss_point, Lp_inter_Lee) \n if Lpp != None:\n # Lp - Lpp\n new_Lp = self.segment_difference(Lp, Lpp)\n self.RSS[index] = [rss_point, new_Lp]\n # Insert the new entry into RSS\n self.RSS.append([e.data, Lee])\n # Clean entries with None as rectangle area\n self.RSS = self.clean_RSS(self.RSS)\n except TypeError:\n pass\n \n if len(self.secondary) == 0:\n secondary_heap_empty = True\n else:\n # Move entries from secondary into main\n self.push_to_main()\n\n\n def priority_main(self, e_mindist, e_segment) -> float:\n \"\"\"\n Calculate the priority of an Rtree entry for the main heap.\n The priority is the distance between the mindist point of Rtree entry\n and the left most point of entry's non dominational segment.\n\n Parameters: e_mindist -> point (x, y)\n e_segment -> segment [(x1, y1), (x2, y2)]\n \n Output: float \n \"\"\"\n \n # Euclidean distance\n x, y = e_mindist[0], e_mindist[1]\n x1, y1 = e_segment[0][0], e_segment[0][1]\n\n return math.sqrt((x-x1)**2 + (y-y1)**2)\n\n\n def priority_secondary(self, segment) -> float:\n \"\"\"\n Calculate the priority of an Rtree entry for the secondary heap.\n The priority is the distance of segment's left starting point (qes)\n from query's left starting point (qs)\n\n Parameters: segment -> line segment [(qes_x, qes_y), (qee_x, qee_y)]\n\n Output : float\n \"\"\"\n\n # The non dominational segment and the query segment are the same segments\n # with the only difference that the non dominational segment might be smaller\n # if a dominational segment has been found previously\n # Therefore the distance of the starting points is the difference qes - qs\n # on the axes the query has taken place\n seg_start = segment[0]\n return seg_start[self.dim - 1] - self.qs[self.dim - 1] \n\n\n def get_mbr_mindist(self, entry) -> (float, float):\n \"\"\"\n Every Rtree Entry represents an MBR.\n The mindist point of an MBR is the point with the \n minimum distance from query's start point qs.\n\n Parameters: entry -> RTreeEntry object, \n entry.rect -> Represents the MBR, \n rect.min_x & rect.min_y is the lower left corner\n rect.max_x & rect.max_y is the top right corner\n \n Output: Point, (x,y)\n \"\"\"\n \n # Query's start point\n qs_x, qs_y = (self.qs[0], self.qs[1])\n # MBR lower left and top right corners\n min_x, min_y = entry.rect.min_x, entry.rect.min_y\n max_x, max_y = entry.rect.max_x, entry.rect.max_y\n\n # Find the relative position of qs to the MBR\n is_top = qs_y > max_y\n is_bottom = qs_y < min_y\n is_left = qs_x < min_x\n is_right = qs_x > max_x\n\n # Return the qs's projection onto the MBR\n if is_top and is_left:\n return [min_x, max_y]\n elif is_top and is_right:\n return [max_x, max_y]\n elif is_bottom and is_left:\n return [min_x, min_y]\n elif is_bottom and is_right:\n return [max_x, min_y]\n elif is_top:\n return [qs_x, max_y]\n elif is_bottom:\n return [qs_x, min_y]\n elif is_left:\n return [min_x, qs_y]\n elif is_right:\n return [max_x, qs_y]\n else:\n # Inside the MBR\n return [qs_x, qs_y]\n\n\n def insert_into_main_heap(self, entry, segment):\n \"\"\"\n Insert into the main heap a new entry \n\n Parameters: entry -> RTreeEntry object\n segment -> segment [(x1, y1), (x2, y2)]\n \"\"\"\n\n mindist_point = self.get_mbr_mindist(entry)\n priority = self.priority_main(mindist_point, segment)\n\n # Use id() in case of priority collision\n heapq.heappush(self.main, [priority, id(entry), entry, segment])\n\n\n def insert_into_secondary_heap(self, entry, segment):\n \"\"\"\n Insert into the secondary heap a new entry\n\n Parameters: entry -> RTreeEntry object\n segment -> segment [(x1,y1), (x2,y2)]\n \"\"\"\n\n priority = self.priority_secondary(segment)\n\n # Use id() in case of priority collision\n heapq.heappush(self.secondary, [priority, id(entry), entry, segment])\n\n\n def remove_top_entry(self, heap) -> [rtreelib.rtree.RTreeEntry , [(float,float),(float,float)]]:\n \"\"\"\n Return the RTreeEntry object and the segment and\n exclude the priority and the id()\n\n Parameters: heap -> list with heap framework\n\n Output: list -> [RTreeEntry, segment]\n segment -> [(x1,y1), (x2,y2)]\n \"\"\"\n \n heap_top_entry = heapq.heappop(heap)\n # Keep only the RtreeEntry and the segment\n return heap_top_entry[2:]\n\n\n def iterate_RSS_for_nonDomination_segment(self, r_point, r_segm) -> [(float,float),(float,float)]:\n \"\"\"\n Checks if there is a non dominational sub segment for r_point, \n in comparison to every point of RSS\n\n Parameters: r_point -> (xr,yr) \n r_segm -> [(xs,ys), (xe,ye)]\n\n Output: segment -> [(x1,y1), (x2,y2)] or None\n \"\"\"\n \n for rss_entry in self.RSS:\n rss_point, rss_segm = rss_entry[0], rss_entry[1]\n\n # I have to check if the r_nonDomination_segm is not None, due to previous function call\n # if it is not I call again the funtion\n # if it is None the for the rest of RSS points I will not process further\n if r_segm != None:\n r_nonDomination_seg = self.nonDomination_segment(rss_point, r_point, rss_segm, r_segm)\n r_segm = r_nonDomination_seg\n else:\n pass\n\n return r_segm\n\n \n def nonDomination_segment(self, p_point, r_point, p_segm, r_segm) -> [(float,float),(float,float)]:\n \"\"\"\n The non domination segment is the current r_segm differentiated by the\n domination segment of p to r in relation to p_segm \n\n Parameters: p_point -> (xp,yp)\n r_point -> (xr,yr)\n p_segm -> [(xp_s,yp_s),(xp_e,yp_e)]\n r_segm -> [(xr_s,yr_s),(xr_e,yr_e)]\n\n Output: segment -> [(x1,y1),(x2,y2)] or None\n \"\"\"\n \n domination_segment = self.point_domination(p_point, r_point, p_segm)\n # To differentiate, the domination_segment has to be != None\n if domination_segment != None:\n non_domination_segment = self.segment_difference(r_segm, domination_segment)\n else:\n non_domination_segment = r_segm\n\n return non_domination_segment\n\n\n def point_domination(self, p_point, r_point, ref_segm) -> [(float,float),(float,float)]:\n \"\"\"\n Calculate the domination segment and if the non query dimensions\n meet the requirements for domination\n\n Parameters: p -> [x1,y1] \n r -> [x2,y2]\n ref_seg -> [(qs_x, qs_y), (qe_x,qe_y)]\n\n Output: Line segment -> [(x, y), (x, y)] or None\n \"\"\"\n # Add a domination check\n self.domination_checks += 1\n \n # Get the dominational segment\n dominational_segm = self.domination_segment(p_point, r_point, ref_segm)\n\n domination = True\n # Check if the domination holds for the rest dimensions\n for indx in range(len(p_point)):\n # Do not take into account the query dimension\n if indx != self.dim -1:\n p_point_dist = abs(self.qs[indx] - p_point[indx])\n r_point_dist = abs(self.qs[indx] - r_point[indx])\n if r_point_dist < p_point_dist:\n domination = False\n \n # Return\n if (dominational_segm != None) and (domination):\n return dominational_segm\n else:\n return None\n\n\n def domination_segment(self, p_point, r_point, ref_segm) -> [(float,float),(float,float)]: \n \"\"\"\n Specifying the range of the coordinate values on the i-axis \n of all the points q that belong to hte ref_seg in relation\n to which p dominates r\n\n Input: p -> [x1,y1] \n r -> [x2,y2]\n ref_seg -> [(qs_x, qs_y), (qe_x,qe_y)]\n\n Output: Line segment -> [(x1, y1), (x2, y2)] or None\n \"\"\"\n \n # Get the points' values on the axis the query took place\n p_val = list(p_point).pop(self.dim - 1)\n r_val = list(r_point).pop(self.dim - 1)\n qs_val = list(ref_segm[0]).pop(self.dim - 1)\n qe_val = list(ref_segm[1]).pop(self.dim - 1)\n\n # Find the relative position of the values\n range_values= None\n if (p_val < r_val):\n # No.2\n if (p_val <= qs_val <= r_val <= qe_val) and (2*qs_val <= p_val + r_val):\n range_values= [qs_val, (p_val+r_val)/2.0]\n # No.3\n elif (p_val <= qs_val <= qe_val <= r_val):\n if (2*qs_val <= p_val + r_val <= 2*qe_val):\n range_values= [qs_val, (p_val+r_val)/2.0]\n elif (2*qe_val <= p_val+r_val):\n range_values= [qs_val, qe_val]\n # No.4\n elif (qs_val <= p_val <= qe_val <= r_val):\n if (p_val+r_val <= 2*qe_val):\n range_values= [qs_val, (p_val+r_val)/2.0]\n else:\n range_values= [qs_val, qe_val]\n # No.5\n elif (qs_val <= p_val < r_val <= qe_val):\n range_values= [qs_val, (p_val+r_val)/2.0]\n # No.6\n elif (qs_val <= qe_val <= p_val < r_val):\n range_values= [qs_val, qe_val]\n elif (r_val < p_val):\n # No.7\n if (r_val < p_val <= qs_val <= qe_val):\n range_values= [qs_val, qe_val]\n # No.8\n elif (r_val <= qs_val <= p_val <= qe_val):\n if ( 2*qs_val <= p_val+r_val):\n range_values= [(p_val+r_val)/2.0, qe_val]\n else:\n range_values= [qs_val, qe_val]\n # No.9\n elif (r_val <= qs_val <= qe_val <= p_val):\n if (2*qe_val <= p_val+r_val):\n pass\n elif (2*qs_val <= p_val+r_val <= 2*qe_val):\n range_values= [(p_val+r_val)/2.0, qe_val]\n else:\n range_values= [qs_val, qe_val]\n # No.10\n elif (qs_val <= r_val <= qe_val <= p_val) and (p_val+r_val <= 2*qe_val):\n range_values= [(p_val+r_val)/2.0, qe_val]\n # No.11\n elif (qs_val <= r_val < p_val <= qe_val):\n range_values= [(p_val+r_val)/2.0, qe_val]\n elif (r_val == p_val):\n range_values= [qs_val, qe_val]\n \n # Construct the segment by adding the other dimensions\n if range_values!= None:\n segment = []\n # range(2), cause start and end points\n for indx1 in range(2):\n segment_point = []\n for indx2 in range(len(self.qs)):\n if indx2 != self.dim - 1:\n segment_point.append(self.qs[indx2])\n else:\n segment_point.append(range_values[indx1])\n segment.append(tuple(segment_point))\n else:\n segment = None\n\n # Return the segment\n return segment\n\n\n def segment_difference(self, segm_a, segm_b) -> [(float,float),(float,float)]:\n \"\"\"\n Given two segments, the difference between segm_a and segm_b is \n segm_a - segm_b\n\n Parameters: segm_a -> [(xa1,ya1),(xa2,ya2)]\n segm_b -> [(xb1,yb1),(xb2,yb2)]\n \n Output: segment -> [(x1,y1),(x2,y2)]\n \"\"\"\n\n # Garbage time\n start_time = time.time()\n\n # Take the values on the axis that the query took place\n segm_a_start = segm_a[0][self.dim - 1]\n segm_a_end = segm_a[1][self.dim - 1]\n segm_b_start = segm_b[0][self.dim - 1]\n segm_b_end = segm_b[1][self.dim - 1]\n\n # Create a range from start to end for the segments\n segm_a_range = [round(float(item), 3) for item in np.arange(segm_a_start, segm_a_end + 0.001, 0.001) if round(float(item), 3) <= segm_a_end]\n segm_b_range = [round(float(item), 3) for item in np.arange(segm_b_start, segm_b_end + 0.001, 0.001) if round(float(item), 3) <= segm_b_end]\n\n # Take the difference of the two ranges/segments\n diff = list(set(segm_a_range) - set(segm_b_range))\n # Sort the difference\n diff.sort()\n\n # Construct the new segment\n if diff:\n # Keep only the first and last element\n diff = [diff[0], diff[len(diff)-1]]\n final_segment = []\n for indx1 in range(2):\n segment_point = []\n for indx2 in range(len(self.qs)):\n if indx2 != self.dim - 1:\n segment_point.append(self.qs[indx2])\n else:\n segment_point.append(diff[indx1])\n final_segment.append(tuple(segment_point))\n else:\n final_segment = None\n \n self.garbage_time += time.time() - start_time\n\n # Return\n return final_segment\n\n\n def segment_intersection(self, segm_a, segm_b) -> [(float,float),(float,float)]:\n \"\"\"\n Calculate the intersection of two segments\n\n Parameters: segm_a -> [(xa1,ya1),(xa2,ya2)]\n segm_b -> [(xb1,yb1),(xb2,yb2)]\n \n Output: segment -> [(x1,y1),(x2,y2)] \n \"\"\"\n\n # Garbage time\n start_time = time.time()\n\n # Take the values on the axis that the query took place\n segm_a_start = segm_a[0][self.dim - 1]\n segm_a_end = segm_a[1][self.dim - 1]\n segm_b_start = segm_b[0][self.dim - 1]\n segm_b_end = segm_b[1][self.dim - 1]\n \n # Create a range from start to end for the segments\n segm_a_range = [round(float(item), 3) for item in np.arange(segm_a_start, segm_a_end + 0.001, 0.001) if round(float(item), 3) <= segm_a_end]\n segm_b_range = [round(float(item), 3) for item in np.arange(segm_b_start, segm_b_end + 0.001, 0.001) if round(float(item), 3) <= segm_b_end]\n\n # Take the difference of the two ranges/segments\n diff = list(set(segm_a_range) & set(segm_b_range))\n # Sort the difference\n diff.sort()\n\n # Construct the new segment\n if diff:\n # Keep only the first and last element\n diff = [diff[0], diff[len(diff)-1]]\n final_segment = []\n for indx1 in range(2):\n segment_point = []\n for indx2 in range(len(self.qs)):\n if indx2 != self.dim - 1:\n segment_point.append(self.qs[indx2])\n else:\n segment_point.append(diff[indx1])\n final_segment.append(tuple(segment_point))\n else:\n final_segment = None\n \n self.garbage_time += time.time() - start_time\n\n # Return\n return final_segment\n\n\n def push_to_main(self):\n \"\"\"\n Pushes the entries with higher priority into the queue from the secondary heap \n to the main heap\n \"\"\"\n\n # Take top entry \n rtree_entry, segment = self.remove_top_entry(self.secondary)\n self.insert_into_main_heap(rtree_entry, segment)\n\n backup_list = []\n for index in range(len(self.secondary)):\n next_rtree_entry, next_segment = self.remove_top_entry(self.secondary)\n if next_segment[0] == segment[0]:\n self.insert_into_main_heap(next_rtree_entry, next_segment)\n else:\n backup_list.append([next_rtree_entry, next_segment])\n\n # Put back to secondary heap \n for pair in backup_list:\n self.insert_into_secondary_heap(pair[0], pair[1]) \n\n # Check maximum heap size\n if len(self.main) > self.maximum_main_size:\n self.maximum_main_size = len(self.main)\n if len(self.secondary) > self.maximum_secondary_size:\n self.maximum_secondary_size = len(self.secondary)\n\n\n def clean_RSS(self, RSS) -> list:\n \"\"\"\n Takes away the entries that have None as a rectangle area\n\n Parameters: list -> [ [point, rectangle area], [point, None], ... ]\n\n Output: list -> [ [point1, rectangle area1], [point2, rectangle area2], ...]\n \"\"\"\n clean_RSS = []\n for item in RSS:\n rectangle_area = item[1]\n if rectangle_area != None:\n clean_RSS.append(item)\n \n # Return\n return clean_RSS","sub_path":"implementation/algorithms/algos_without_logs/single_dimensional_query.py","file_name":"single_dimensional_query.py","file_ext":"py","file_size_in_byte":23048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"616191867","text":"import random\r\n\r\n#Variables\r\n#Main game loop\r\nplayingGame = 1\r\n\r\n#Tictactoe game loop\r\nstartingGame = 0\r\n\r\n#Tictactoe board array\r\nboardArr = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]\r\n\r\n#Player Turn\r\nplayerTurn = 1\r\n\r\n#Check if players action is correct\r\nswitchPlayer = -1\r\n\r\n#Total turns of all players\r\ntotalPlayerTurns = 0\r\n\r\n#Error checks in choosing human or computer\r\nerrorTypeCheck1 = 0\r\n\r\n#Functions\r\ndef showBoard():\r\n #Start counting from the first index of the array\r\n sType = 1\r\n while sType <= 9:\r\n print(boardArr[sType-1],\"|\", end='') #Print the boxes, sType-1 since array starts with 0\r\n if(sType % 3 == 0): #If the counting is divisible by 3 then add a new line(since the are only 3 boxes per row)\r\n print(\"\")\r\n print(\"---------\")\r\n sType += 1 #proceed to the next index of the array\r\n\r\ndef placeTurn(loc, player): #Give the function the location of the turn and the player\r\n if loc.isdigit():\r\n #check if the numbers are between 1-9\r\n loc = int(loc)\r\n if loc > 9 or loc < 1:\r\n print(\"Please enter numbers between 1-9\")\r\n global switchPlayer\r\n switchPlayer = -1\r\n return\r\n else:\r\n #check if the entered value is an integer\r\n print(\"Please enter numbers between 1-9\")\r\n switchPlayer = -1\r\n return\r\n \r\n #If the choosen location has already a place\r\n if boardArr[loc-1] == \"X\" or boardArr[loc-1] == \"O\":\r\n print(\"Place already set! Please choose another number!\")\r\n switchPlayer = -1\r\n else:\r\n #if no errors then place the turn\r\n switchPlayer = 0\r\n if player == 1:\r\n boardArr[loc-1] = \"X\"\r\n else:\r\n boardArr[loc-1] = \"O\"\r\n global totalPlayerTurns\r\n totalPlayerTurns += 1 #add the total player turns\r\n\r\ndef checkWin():\r\n #if playerWinner is 0, it is tie\r\n #if playerWinner is 1, then player 1 wins\r\n #if 2 then player 2 wins\r\n \r\n playerWinner = 0\r\n \r\n #Player 1\r\n shape = \"X\"\r\n \r\n #Horizontal Win Check\r\n if boardArr[0] == shape and boardArr[1] == shape and boardArr[2] == shape: playerWinner = 1\r\n if boardArr[3] == shape and boardArr[4] == shape and boardArr[5] == shape: playerWinner = 1\r\n if boardArr[6] == shape and boardArr[7] == shape and boardArr[8] == shape: playerWinner = 1\r\n\r\n #Vertical Win Check\r\n if boardArr[0] == shape and boardArr[3] == shape and boardArr[6] == shape: playerWinner = 1\r\n if boardArr[1] == shape and boardArr[4] == shape and boardArr[7] == shape: playerWinner = 1\r\n if boardArr[2] == shape and boardArr[5] == shape and boardArr[8] == shape: playerWinner = 1\r\n\r\n #Diagonal Win Check\r\n if boardArr[0] == shape and boardArr[4] == shape and boardArr[8] == shape: playerWinner = 1\r\n if boardArr[2] == shape and boardArr[4] == shape and boardArr[6] == shape: playerWinner = 1\r\n\r\n #Player 2\r\n shape = \"O\"\r\n \r\n #Horizontal Win Check\r\n if boardArr[0] == shape and boardArr[1] == shape and boardArr[2] == shape: playerWinner = 2\r\n if boardArr[3] == shape and boardArr[4] == shape and boardArr[5] == shape: playerWinner = 2\r\n if boardArr[6] == shape and boardArr[7] == shape and boardArr[8] == shape: playerWinner = 2\r\n\r\n #Vertical Win Check\r\n if boardArr[0] == shape and boardArr[3] == shape and boardArr[6] == shape: playerWinner = 2\r\n if boardArr[1] == shape and boardArr[4] == shape and boardArr[7] == shape: playerWinner = 2\r\n if boardArr[2] == shape and boardArr[5] == shape and boardArr[8] == shape: playerWinner = 2\r\n\r\n #Diagonal Win Check\r\n if boardArr[0] == shape and boardArr[4] == shape and boardArr[8] == shape: playerWinner = 2\r\n if boardArr[2] == shape and boardArr[4] == shape and boardArr[6] == shape: playerWinner = 2\r\n\r\n global startingGame\r\n if playerWinner == 1:\r\n print(\"PLAYER 1 WINS!\")\r\n showBoard()\r\n startingGame = 0 #End the game\r\n if playerWinner == 2:\r\n print(\"PLAYER 2 WINS!\")\r\n showBoard()\r\n startingGame = 0 #End the game\r\n \r\n #if all the board is placed and there is no winner, then it is a tie\r\n if totalPlayerTurns == 9 and playerWinner == 0:\r\n print(\"Its a tie!!\")\r\n showBoard()\r\n startingGame = 0 #End the game\r\n\r\ndef resetVariables():\r\n global playingGame, startingGame, boardArr, playerTurn, switchPlayer, totalPlayerTurns, errorTypeCheck1\r\n playingGame = 1\r\n startingGame = 0\r\n boardArr = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]\r\n playerTurn = 1\r\n switchPlayer = -1\r\n totalPlayerTurns = 0\r\n errorTypeCheck1 = 0\r\n\r\n#Main Loop\r\nwhile playingGame == 1:\r\n\r\n #if playerType is 0, human vs human\r\n #if 1, comp vs human\r\n playerType = -1\r\n\r\n #the selected place turn of the player\r\n playerChoose = -1\r\n \r\n print(\"Tic-tac-toe Game\")\r\n playerType = input(\"Enter 0 for human vs human and 1 for Computer vs human: \")\r\n \r\n if playerType == \"0\":\r\n errorTypeCheck1 = 0\r\n startingGame = 1\r\n print(\"Human vs Human\")\r\n \r\n while startingGame == 1: #Nested loop\r\n showBoard()\r\n print(\"Player\", playerTurn, \": \")\r\n #Ask for the turn\r\n playerChoose = input(\"Please choose a number to place your mark: \")\r\n placeTurn(playerChoose, playerTurn)\r\n\r\n #If the player is good to switch turn with player 2 or 1, then switch\r\n if switchPlayer == 0:\r\n if playerTurn == 1:\r\n playerTurn = 2\r\n elif playerTurn == 2:\r\n playerTurn = 1\r\n checkWin()\r\n \r\n elif playerType == \"1\":\r\n errorTypeCheck1 = 0\r\n startingGame = 1\r\n print(\"Computer vs Human\")\r\n \r\n while startingGame == 1: #Nested loop\r\n showBoard()\r\n print(\"Player\", playerTurn, \": \", end='')\r\n\r\n if playerTurn == 1:\r\n playerChoose = input(\"Please choose a number to place your mark: \")\r\n else:\r\n playerChoose = str(random.randint(1,9)) #computer will choose a number between 1-9, convert it to string since there will be a checker and str to int converter\r\n print(playerChoose)\r\n #if the random number has already a place, then continue to choose a random number until there is none placed on the selected place\r\n while boardArr[int(playerChoose)-1] == \"X\" or boardArr[int(playerChoose)-1] == \"O\":\r\n playerChoose = str(random.randint(1,9))\r\n \r\n placeTurn(playerChoose, playerTurn)\r\n \r\n #If the player is good to switch turn with player 2 or 1, then switch\r\n if switchPlayer == 0:\r\n if playerTurn == 1:\r\n playerTurn = 2\r\n elif playerTurn == 2:\r\n playerTurn = 1\r\n checkWin()\r\n else:\r\n print(\"Please enter 0 or 1.\")\r\n errorTypeCheck1 = 1\r\n\r\n #If no errors\r\n if errorTypeCheck1 == 0:\r\n #Game End\r\n playAgain = input(\"Do you want to play again? y/n: \")\r\n \r\n if playAgain == \"n\" or playAgain == \"N\":\r\n print(\"Thank you for playing! Goodbye!\")\r\n playingGame = 0 #End the main loop\r\n \r\n if playAgain == \"y\" or playAgain == \"Y\":\r\n resetVariables()\r\n startingGame == 1 #Start again the nested loop\r\n","sub_path":"Tictactoe_Game.py","file_name":"Tictactoe_Game.py","file_ext":"py","file_size_in_byte":7473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"597473390","text":"import torch\nimport torch.nn as nn\nimport numpy as np\nfrom torch.utils.data import DataLoader, Dataset, random_split\nfrom sklearn.preprocessing import QuantileTransformer, StandardScaler, MinMaxScaler\nimport pytorch_lightning as pl\nimport pickle\nfrom random import randint, sample\nfrom ExpressiveDataset import ExpressiveDataset\nfrom utils import *\n\n\nclass LinearBlock(nn.Module):\n def __init__(self, in_size, out_size, norm=True, act=True):\n super().__init__()\n self.linear = nn.Linear(in_size, out_size)\n self.norm = nn.LayerNorm(out_size) if norm else None\n self.act = act\n\n def forward(self, x):\n x = self.linear(x)\n if self.norm is not None:\n x = self.norm(x)\n if self.act:\n x = nn.functional.leaky_relu(x)\n return x\n\n\nclass ModelCategorical(pl.LightningModule):\n def __init__(self, in_size, hidden_size, out_size, scalers):\n super().__init__()\n self.save_hyperparameters()\n self.scalers = scalers\n self.loudness_nbins = 30\n self.ddsp = torch.jit.load(\"results/ddsp_debug_pretrained.ts\").eval()\n\n self.pre_lstm = nn.Sequential(\n LinearBlock(in_size, hidden_size),\n LinearBlock(hidden_size, hidden_size),\n )\n\n self.lstm = nn.GRU(\n hidden_size,\n hidden_size,\n num_layers=1,\n batch_first=True,\n )\n\n self.post_lstm = nn.Sequential(\n LinearBlock(hidden_size, hidden_size),\n LinearBlock(\n hidden_size,\n out_size,\n norm=False,\n act=False,\n ),\n )\n\n def configure_optimizers(self):\n return torch.optim.Adam(\n self.parameters(),\n lr=1e-4,\n weight_decay=.01,\n )\n\n def forward(self, x):\n x = self.pre_lstm(x)\n x = self.lstm(x)[0]\n x = self.post_lstm(x)\n return x\n\n def split_predictions(self, prediction):\n pred_f0 = prediction[..., :100]\n pred_cents = prediction[..., 100:200]\n pred_loudness = prediction[..., 200:]\n return pred_f0, pred_cents, pred_loudness\n\n def cross_entropy(self, pred_f0, pred_cents, pred_loudness, target_f0,\n target_cents, target_loudness):\n pred_f0 = pred_f0.permute(0, 2, 1)\n pred_cents = pred_cents.permute(0, 2, 1)\n pred_loudness = pred_loudness.permute(0, 2, 1)\n\n target_f0 = target_f0.squeeze(-1)\n target_cents = target_cents.squeeze(-1)\n target_loudness = target_loudness.squeeze(-1)\n\n loss_f0 = nn.functional.cross_entropy(pred_f0, target_f0)\n loss_cents = nn.functional.cross_entropy(pred_cents, target_cents)\n loss_loudness = nn.functional.cross_entropy(\n pred_loudness,\n target_loudness,\n )\n\n return loss_f0, loss_cents, loss_loudness\n\n def training_step(self, batch, batch_idx):\n model_input, target = batch\n prediction = self.forward(model_input.float())\n\n pred_f0, pred_cents, pred_loudness = self.split_predictions(prediction)\n target_f0, target_cents, target_loudness = torch.split(target, 1, -1)\n\n loss_f0, loss_cents, loss_loudness = self.cross_entropy(\n pred_f0,\n pred_cents,\n pred_loudness,\n target_f0,\n target_cents,\n target_loudness,\n )\n\n self.log(\"loss_f0\", loss_f0)\n self.log(\"loss_cents\", loss_cents)\n self.log(\"loss_loudness\", loss_loudness)\n\n return loss_f0 + loss_cents + loss_loudness\n\n def sample_one_hot(self, x):\n n_bin = x.shape[-1]\n sample = torch.distributions.Categorical(logits=x).sample()\n sample = nn.functional.one_hot(sample, n_bin)\n return sample\n\n @torch.no_grad()\n def generation_loop(self, x, infer_pitch=False):\n context = None\n\n for i in range(x.shape[1] - 1):\n x_in = x[:, i:i + 1]\n\n x_out = self.pre_lstm(x_in)\n x_out, context = self.lstm(x_out, context)\n x_out = self.post_lstm(x_out)\n pred_f0, pred_cents, pred_loudness = self.split_predictions(x_out)\n\n if infer_pitch:\n f0 = self.sample_one_hot(pred_f0)\n else:\n f0 = x[:, i + 1:i + 2, :100].float()\n\n cents = self.sample_one_hot(pred_cents)\n loudness = self.sample_one_hot(pred_loudness)\n\n cat = torch.cat([f0, cents, loudness], -1)\n ndim = cat.shape[-1]\n\n x[:, i + 1:i + 2, -ndim:] = cat\n\n pred = x[..., -ndim:]\n pred_f0, pred_cents, pred_loudness = self.split_predictions(pred)\n\n pred_f0 = pred_f0[:, 1:]\n pred_loudness = pred_loudness[:, 1:]\n pred_cents = pred_cents[:, :-1]\n\n out = map(lambda x: torch.argmax(x, -1),\n [pred_f0, pred_cents, pred_loudness])\n\n return list(out)\n\n def apply_inverse_transform(self, x, idx):\n scaler = self.scalers[idx]\n x = x.cpu()\n out = scaler.inverse_transform(x.reshape(-1, 1))\n out = torch.from_numpy(out).to(\"cuda\")\n out = out.unsqueeze(0)\n return out.float()\n\n def get_audio(self, model_input, target):\n\n model_input = model_input.unsqueeze(0).float()\n f0, cents, loudness = self.generation_loop(model_input)\n cents = cents / 100 - .5\n\n f0 = pctof(f0, cents)\n\n loudness = loudness / (self.loudness_nbins - 1)\n f0 = self.apply_inverse_transform(f0.squeeze(0), 0)\n loudness = self.apply_inverse_transform(loudness.squeeze(0), 1)\n y = self.ddsp(f0, loudness)\n return y\n\n def validation_step(self, batch, batch_idx):\n model_input, target = batch\n prediction = self.forward(model_input.float())\n\n pred_f0, pred_cents, pred_loudness = self.split_predictions(prediction)\n target_f0, target_cents, target_loudness = torch.split(target, 1, -1)\n\n loss_f0, loss_cents, loss_loudness = self.cross_entropy(\n pred_f0,\n pred_cents,\n pred_loudness,\n target_f0,\n target_cents,\n target_loudness,\n )\n\n self.log(\"val_loss_f0\", loss_f0)\n self.log(\"val_loss_cents\", loss_cents)\n self.log(\"val_loss_loudness\", loss_loudness)\n self.log(\"val_total\", loss_f0 + loss_cents + loss_loudness)\n\n ## Every 100 epochs : produce audio\n\n if self.current_epoch % 200 == 0:\n\n audio = self.get_audio(model_input[0], target[0])\n # output audio in Tensorboard\n tb = self.logger.experiment\n n = \"Epoch={}\".format(self.current_epoch)\n tb.add_audio(tag=n, snd_tensor=audio, sample_rate=16000)\n\n\nif __name__ == \"__main__\":\n\n trainer = pl.Trainer(\n gpus=1,\n callbacks=[pl.callbacks.ModelCheckpoint(monitor=\"val_total\")],\n max_epochs=50000,\n )\n list_transforms = [\n (Identity, ), # u_f0 \n (MinMaxScaler, ), # u_loudness\n (Identity, ), # e_f0\n (Identity, ), # e_cents\n (MinMaxScaler, ), # e_loudness\n ]\n\n dataset = ExpressiveDataset(n_sample=512, list_transforms=list_transforms)\n val_len = len(dataset) // 20\n train_len = len(dataset) - val_len\n\n train, val = random_split(dataset, [train_len, val_len])\n\n model = ModelCategorical(360, 1024, 230, scalers=dataset.scalers)\n\n trainer.fit(\n model,\n DataLoader(train, 32, True),\n DataLoader(val, 32),\n )\n","sub_path":"models/LSTMCategorical.py","file_name":"LSTMCategorical.py","file_ext":"py","file_size_in_byte":7574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"295195123","text":"'''\nCreated on Oct 24, 2016\n\n@author: Titus\n'''\ndef ui_add_expense(expenses, params):\n ''' \n Adds an expense to the expenses list\n \n Input - expenses : the list of all the expenses\n params : the list of parameters ( sum, category )\n \n Output - \n '''\n day = 0\n sum = int(params[0])\n category = params[1]\n expenses.append(add_expense(day,sum,category))\n\n\ndef ui_insert_expense(expenses, params):\n '''\n Inserts an expense to the expenses list\n \n Input - expenses : the list of all the expenses\n params : the list of parameters ( day, sum, category )\n \n Output - \n '''\n day = int(params[0])\n sum = int(params[1])\n category = params[2]\n expenses.append(add_expense(day,sum,category))\n\n\ndef ui_remove_expense(expenses, params):\n '''\n Removes expenses from the expenses list depending on the parameters\n \n Input - expenses : the list of all the expenses\n params : the list of paramaters ( day ) or ( starting day , ending day ) or ( category )\n \n Output - \n '''\n if len(params) is 1:\n try:\n day = int(params[0])\n remove_day(expenses, day)\n except ValueError:\n category = params[0]\n remove_category(expenses, category)\n if len(params) is 3:\n if params[1] == 'to':\n startDay = int(params[0])\n endDay = int(params[2])\n remove_day_to_day(expenses, startDay, endDay)\n \n\ndef ui_list_expense(expenses, params):\n '''\n Prints the expenses from the expenses list depending on the parameters\n \n Input - expenses : the list of all the expenses\n params : the list of paramaters ( ) or ( category ) or ( category, operand, value )\n \n Output - \n '''\n if len(params) is 0:\n list_all(expenses)\n \n if len(params) is 1:\n category = params[0]\n list_category(expenses, category)\n \n if len(params) is 3:\n category = params[0]\n operant = params[1]\n value = params[2]\n if operant == '<':\n list_category_lower(expenses, category, value)\n if operant == '>':\n list_category_upper(expenses, category, value)\n if operant == '=':\n list_category_equal(expenses, category, value)\n \n \ndef ui_sum_category(expenses, params):\n '''\n Prints the total expense for a given category\n \n Input - expenses : the list of all the expenses\n params : the list of parameters, expected only one ( category )\n \n Output - \n '''\n if len(params) is 1:\n category = params[0]\n print('The total expense for', category, 'is', sum_category(expenses, category))\n\n\ndef ui_max_day(expenses, params):\n pass\n# '''\n# Prints the category with the maximum expenses from the expenses list\n# \n# Input - expenses : the list of all the expenses\n# params : the list of parameters, expected only one ( day )\n# \n# Output - \n# '''\n# if len(params) is 1:\n# day = params[0]\n# print('The category with most expenses for the day', day, 'is', maximum_expense_day(expenses, day))\n\n\ndef ui_sort_expense(expenses, params):\n '''\n Prints the sorted expenses ( by the amount of money spend ) from the expenses list\n depending on the parameters\n \n Input - expenses : the list of all the expenses\n params : the list of parameters ( day ) or ( category )\n \n Output - \n '''\n if len(params) is 1:\n try:\n day = int(params[0])\n sort_expense_day(expenses, day)\n except ValueError:\n category = params[0]\n sort_expense_category(expenses, category)\n \n","sub_path":"2-4/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"490790666","text":"import sys\nimport threading\nfrom NLP import *\nfrom DB import *\nfrom GEO import *\nimport time\n\n\ndef GEOJOB():\n db = DBO()\n maps = GEO()\n table_tweets = Tweets(db)\n table_locations = Locations(db)\n while True:\n places = table_tweets.get_place()\n for place in places:\n (p,) = place\n cordinate = maps.geocode(p)\n if cordinate is not None:\n table_locations.insert(p,cordinate['lat'],cordinate['lng']) \n time.sleep(120)\n\ndef NLPJOB():\n db = DBO()\n nlp = NLPEngine()\n table_tweets = Tweets(db)\n while True:\n tweets = table_tweets.get_tweets_wo_sentiment()\n for tweet in tweets:\n TWTID = tweet[0]\n text = tweet[5]\n score = nlp.sentiment(text)\n place = nlp.place(text)\n table_tweets.update_sentiment(TWTID, score)\n if place is not None:\n table_tweets.update_place(TWTID, place)\n time.sleep(60)\n\ndef main(argv):\n GEOThread = threading.Thread(target = GEOJOB)\n \n NLPThread = threading.Thread(target = NLPJOB)\n GEOThread.start()\n NLPThread.start()\n\n GEOThread.join()\n NLPThread.join()\n \nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"Analyst.py","file_name":"Analyst.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"488948667","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('attendance', '0005_auto_20151231_1702'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ClockRecord',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('time', models.DateTimeField(verbose_name='\\u65f6\\u95f4')),\n ('place', models.ForeignKey(to='attendance.Place')),\n ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': '\\u6253\\u5361\\u8bb0\\u5f55',\n 'verbose_name_plural': '\\u6253\\u5361\\u8bb0\\u5f55',\n },\n ),\n migrations.CreateModel(\n name='Setting',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ],\n options={\n 'verbose_name': '\\u8003\\u52e4\\u8bbe\\u7f6e',\n 'verbose_name_plural': '\\u8003\\u52e4\\u8bbe\\u7f6e',\n },\n ),\n ]\n","sub_path":"Documents/backupCode/allapps/attendance/migrations/0006_clockrecord_setting.py","file_name":"0006_clockrecord_setting.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"456257931","text":"# ballot/controllers.py\n# Brought to you by We Vote. Be good.\n# -*- coding: UTF-8 -*-\n\nfrom .models import BallotItemListManager, OFFICE, CANDIDATE, MEASURE\nfrom candidate.models import CandidateCampaignList\nfrom config.base import get_environment_variable\nfrom exception.models import handle_exception\nfrom measure.models import ContestMeasureList\nfrom office.models import ContestOfficeList\nfrom voter.models import fetch_voter_id_from_voter_device_link\nimport wevote_functions.admin\nfrom wevote_functions.functions import is_voter_device_id_valid, positive_value_exists\n\nlogger = wevote_functions.admin.get_logger(__name__)\n\nGOOGLE_CIVIC_API_KEY = get_environment_variable(\"GOOGLE_CIVIC_API_KEY\")\n\n\ndef voter_ballot_items_retrieve_for_api(voter_device_id, google_civic_election_id):\n \"\"\"\n\n :param voter_device_id:\n :param google_civic_election_id: This variable either was stored in a cookie, or passed in explicitly so we can\n get the ballot items related to that election.\n :return:\n \"\"\"\n # Get voter_id from the voter_device_id so we can figure out which ballot_items to offer\n results = is_voter_device_id_valid(voter_device_id)\n if not results['success']:\n json_data = {\n 'status': 'VALID_VOTER_DEVICE_ID_MISSING',\n 'success': False,\n 'voter_id': 0,\n 'voter_device_id': voter_device_id,\n 'ballot_item_list': [],\n 'google_civic_election_id': google_civic_election_id,\n }\n results = {\n 'success': False,\n 'json_data': json_data,\n 'google_civic_election_id': 0, # Force the clearing of google_civic_election_id\n }\n return results\n\n voter_id = fetch_voter_id_from_voter_device_link(voter_device_id)\n if not positive_value_exists(voter_id):\n json_data = {\n 'status': \"VALID_VOTER_ID_MISSING\",\n 'success': False,\n 'voter_id': voter_id,\n 'voter_device_id': voter_device_id,\n 'ballot_item_list': [],\n 'google_civic_election_id': google_civic_election_id,\n }\n results = {\n 'success': False,\n 'json_data': json_data,\n 'google_civic_election_id': 0, # Force the clearing of google_civic_election_id\n }\n return results\n\n ballot_item_list_manager = BallotItemListManager()\n # If we get here without a google_civic_election_id, we need to choose one from the ballot items that are already\n # stored. If we proceed to retrieve_all_ballot_items_for_voter without a google_civic_election_id, we will get\n # ballot items from a variety of elections.\n # This logic looks for all of the elections we have ballot information for, and displays the most recent election\n # (not counting the test election)\n if not positive_value_exists(google_civic_election_id):\n google_civic_election_id = ballot_item_list_manager.fetch_most_recent_google_civic_election_id()\n\n # If an election id STILL wasn't found, then we probably don't have any ballot items stored locally, so we\n # need to go out to google civic. BUT we will proceed and attempt to retrieve ballot items without an election_id\n\n ballot_item_list = []\n ballot_items_to_display = []\n try:\n results = ballot_item_list_manager.retrieve_all_ballot_items_for_voter(voter_id, google_civic_election_id)\n success = results['success']\n status = results['status']\n ballot_item_list = results['ballot_item_list']\n except Exception as e:\n status = 'FAILED voter_ballot_items_retrieve. ' \\\n '{error} [type: {error_type}]'.format(error=e, error_type=type(e))\n handle_exception(e, logger=logger, exception_message=status)\n success = False\n\n if success:\n for ballot_item in ballot_item_list:\n if ballot_item.contest_office_we_vote_id:\n kind_of_ballot_item = OFFICE\n ballot_item_id = ballot_item.contest_office_id\n we_vote_id = ballot_item.contest_office_we_vote_id\n try:\n candidate_list_object = CandidateCampaignList()\n results = candidate_list_object.retrieve_all_candidates_for_office(ballot_item_id, we_vote_id)\n candidates_to_display = []\n if results['candidate_list_found']:\n candidate_list = results['candidate_list']\n for candidate in candidate_list:\n # This should match values returned in candidates_retrieve_for_api\n one_candidate = {\n 'id': candidate.id,\n 'we_vote_id': candidate.we_vote_id,\n 'ballot_item_display_name': candidate.candidate_name,\n 'candidate_photo_url': candidate.fetch_photo_url(),\n 'order_on_ballot': candidate.order_on_ballot,\n 'kind_of_ballot_item': CANDIDATE,\n }\n candidates_to_display.append(one_candidate.copy())\n except Exception as e:\n # status = 'FAILED candidates_retrieve. ' \\\n # '{error} [type: {error_type}]'.format(error=e.message, error_type=type(e))\n candidates_to_display = []\n one_ballot_item = {\n 'ballot_item_display_name': ballot_item.ballot_item_display_name,\n 'google_civic_election_id': ballot_item.google_civic_election_id,\n 'google_ballot_placement': ballot_item.google_ballot_placement,\n 'local_ballot_order': ballot_item.local_ballot_order,\n 'kind_of_ballot_item': kind_of_ballot_item,\n 'id': ballot_item_id,\n 'we_vote_id': we_vote_id,\n 'candidate_list': candidates_to_display,\n }\n ballot_items_to_display.append(one_ballot_item.copy())\n elif ballot_item.contest_measure_we_vote_id:\n kind_of_ballot_item = MEASURE\n ballot_item_id = ballot_item.contest_measure_id\n we_vote_id = ballot_item.contest_measure_we_vote_id\n one_ballot_item = {\n 'ballot_item_display_name': ballot_item.ballot_item_display_name,\n 'google_civic_election_id': ballot_item.google_civic_election_id,\n 'google_ballot_placement': ballot_item.google_ballot_placement,\n 'local_ballot_order': ballot_item.local_ballot_order,\n 'kind_of_ballot_item': kind_of_ballot_item,\n 'id': ballot_item_id,\n 'we_vote_id': we_vote_id,\n }\n ballot_items_to_display.append(one_ballot_item.copy())\n\n json_data = {\n 'status': 'VOTER_BALLOT_ITEMS_RETRIEVED',\n 'success': True,\n 'voter_device_id': voter_device_id,\n 'ballot_item_list': ballot_items_to_display,\n 'google_civic_election_id': google_civic_election_id,\n }\n else:\n json_data = {\n 'status': status,\n 'success': False,\n 'voter_device_id': voter_device_id,\n 'ballot_item_list': [],\n 'google_civic_election_id': google_civic_election_id,\n }\n results = {\n 'success': success,\n 'google_civic_election_id': google_civic_election_id, # We want to save google_civic_election_id in cookie\n 'json_data': json_data,\n }\n return results\n\n\ndef ballot_item_options_retrieve_for_api(google_civic_election_id=0):\n \"\"\"\n This function returns a normalized list of candidates and measures so we can pre-populate form fields\n :param google_civic_election_id:\n :return:\n \"\"\"\n\n status = \"\"\n try:\n candidate_list_object = CandidateCampaignList()\n results = candidate_list_object.retrieve_all_candidates_for_upcoming_election(google_civic_election_id)\n candidate_success = results['success']\n status += results['status']\n candidate_list = results['candidate_list_light']\n except Exception as e:\n status += 'FAILED ballot_item_options_retrieve_for_api, candidate_list. ' \\\n '{error} [type: {error_type}]'.format(error=e, error_type=type(e))\n handle_exception(e, logger=logger, exception_message=status)\n candidate_list = []\n candidate_success = False\n\n try:\n office_list_object = ContestOfficeList()\n results = office_list_object.retrieve_all_offices_for_upcoming_election(google_civic_election_id)\n office_success = results['success']\n status += ' ' + results['status']\n office_list = results['office_list_light']\n except Exception as e:\n status += 'FAILED ballot_item_options_retrieve_for_api, office_list. ' \\\n '{error} [type: {error_type}]'.format(error=e, error_type=type(e))\n handle_exception(e, logger=logger, exception_message=status)\n office_list = []\n office_success = False\n\n try:\n measure_list_object = ContestMeasureList()\n results = measure_list_object.retrieve_all_measures_for_upcoming_election(google_civic_election_id)\n measure_success = results['success']\n status += ' ' + results['status']\n measure_list = results['measure_list_light']\n except Exception as e:\n status += 'FAILED ballot_item_options_retrieve_for_api, measure_list. ' \\\n '{error} [type: {error_type}]'.format(error=e, error_type=type(e))\n handle_exception(e, logger=logger, exception_message=status)\n measure_list = []\n measure_success = False\n\n ballot_items_to_display = []\n if candidate_success and len(candidate_list):\n for candidate in candidate_list:\n ballot_items_to_display.append(candidate.copy())\n\n if office_success and len(office_list):\n for office in office_list:\n ballot_items_to_display.append(office.copy())\n\n if measure_success and len(measure_list):\n for measure in measure_list:\n ballot_items_to_display.append(measure.copy())\n\n json_data = {\n 'status': status,\n 'success': candidate_success or measure_success,\n 'ballot_item_list': ballot_items_to_display,\n 'google_civic_election_id': google_civic_election_id,\n }\n results = {\n 'status': status,\n 'success': candidate_success or measure_success,\n 'google_civic_election_id': google_civic_election_id, # We want to save google_civic_election_id in cookie\n 'json_data': json_data,\n }\n return results\n","sub_path":"ballot/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":11071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"147118374","text":"\r\nimport numpy as np\r\n\r\nfrom utils import read_variable\r\n\r\n\r\ntest_Y = np.zeros(1183748)\r\nrow_start = 0\r\nrow_end = 0\r\nfor chunk_id in range(1184):\r\n \r\n path = 'final/test_votes_1L/'+str(chunk_id)\r\n votes = read_variable(path)\r\n\r\n chunk_Y_pred = (np.sum(votes,axis=1)>=1).astype(np.int)\r\n print(chunk_id,'1s:',sum(chunk_Y_pred))\r\n \r\n row_end = row_start+len(chunk_Y_pred)\r\n\r\n test_Y[row_start:row_end] = chunk_Y_pred\r\n row_start = row_end\r\n \r\nprint('FINAL 1s:',sum(test_Y))\r\n#%%\r\nimport pandas as pd\r\n# saving to CSV\r\ntest_ids = read_variable('outputs/test_ids.pkl')\r\ntest_y_ids = pd.DataFrame(test_ids,columns=['Id'])\r\ntest_y_y = pd.DataFrame(test_Y,columns=['Response'])\r\ntest_y = pd.concat([test_y_ids,test_y_y],axis=1)\r\ntest_y = test_y.set_index('Id')\r\ntest_y.to_csv('submissions/submission_1130.csv',float_format='%.0f')\r\n\r\n\r\n","sub_path":"10_model_2L_test_SUBMISSION.py","file_name":"10_model_2L_test_SUBMISSION.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"393121600","text":"\"\"\"Main entry point\n\"\"\"\nfrom pyramid.config import Configurator\n\n\ndef main(global_config, **settings):\n config = Configurator(settings=settings)\n config.include(\"cornice\")\n# config.include('pyramid_mako')\n config.add_static_view('static', 'static', cache_max_age=3600)\n config.add_static_view('/index', 'lightapp:templates')\n config.scan(\"lightapp.views\")\n return config.make_wsgi_app()\n","sub_path":"lightapp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"473032289","text":"import sys\nimport os\n\noutput_dir = sys.argv[1]\n\ndef filename(num_duplications):\n return os.path.join(output_dir, \"output_%s.csv\" % (str(num_duplications),))\n\ndef time_for_method(fname):\n with open(fname) as f:\n lines = f.readlines()[1:]\n lines = [line.replace(\"\\n\", \"\").split(\", \") for line in lines]\n lines = [(l[0].strip(), float(l[1].strip())) for l in lines]\n return lines\n\ntimes_for_method = {}\nfor num_duplications in (1, 5, 10, 20, 40, 60, 80, 100, 140, 160, 180, 250, 300, 350, 400):\n fname = filename(num_duplications)\n if os.path.isfile(fname):\n for (method, time) in time_for_method(fname):\n if method not in times_for_method:\n times_for_method[method] = []\n times_for_method[method].append((num_duplications, time))\n\nfor (method, times) in times_for_method.iteritems():\n for (num_duplications, time) in times:\n print(method + \", \" + str(num_duplications) + \", \" + str(time))\n","sub_path":"scripts/evaluation/process_api_performance_files.py","file_name":"process_api_performance_files.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"70684741","text":"#!/usr/bin/env python3\n#-*-coding:utf-8-*-\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nimport mysql\nimport mysql.connector\nimport ast\nimport os\nimport sys\nsys.path.insert(1,\"/Users/joel/Archetype/Tobi\")\nfrom Library.TBook import Tools\nmagicWords = Tools().getModuleData(\"localDbPassword\",\"Tobias\")\n\nUtilisateur=os.environ[\"USER\"]\ndef MyConverter(mydata):\n def cvt(data):\n try : \n return ast.litteral_eval(data)\n except Exception:\n return str(data)\n return tuple(map(cvt,mydata))\n\nclass updateWindow(object):\n\n def LoadData(self):\n mydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n passwd=magicWords,\n )\n\n Command = mydb.cursor()\n Command.execute(\"USE tobiasdb\") \n Command.execute(\"SELECT * FROM knownIps\")\n data = Command.fetchall()\n\n for row in data : \n self.addTable(MyConverter(row))\n\n Command.close()\n \n def addTable(self,columns):\n rowPosition = self.tableWidget.rowCount()\n self.tableWidget.insertRow(rowPosition)\n\n for i, column in enumerate(columns):\n self.tableWidget.setItem(rowPosition, i , QtWidgets.QTableWidgetItem(str(column)))\n\n def stocker(self): \n mydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n passwd=magicWords,\n )\n\n Command=mydb.cursor()\n Command.execute(\"USE tobiasdb\")\n\n Ins=\"INSERT INTO knownIps (id,hostname,address) VALUES (NULL , '{}' , '{}')\".format(self.lineEdit_2.text(),self.lineEdit.text()) \n \n Command.execute(Ins)\n mydb.commit()\n\n def init(self):\n self.LoadData()\n self.stocker()\n self.LoadData()\n \n\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(810, 371)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)\n self.tableWidget.setGeometry(QtCore.QRect(40, 10, 691, 231))\n self.tableWidget.setObjectName(\"tableWidget\")\n self.tableWidget.setRowCount(0)\n self.tableWidget.setColumnCount(3)\n self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)\n self.lineEdit.setGeometry(QtCore.QRect(40, 280, 251, 32))\n self.lineEdit.setObjectName(\"lineEdit\")\n self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)\n self.lineEdit_2.setGeometry(QtCore.QRect(330, 280, 251, 32))\n self.lineEdit_2.setObjectName(\"lineEdit_2\")\n self.pushButton = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(610, 280, 88, 34))\n self.pushButton.setObjectName(\"pushButton\")\n self.pushButton.clicked.connect(self.init)\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 810, 30))\n self.menubar.setObjectName(\"menubar\")\n MainWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"Tobias\\'s Update Hosts Page\"))\n self.lineEdit.setPlaceholderText(_translate(\"MainWindow\", \"Adresse ip à rajouter\"))\n self.lineEdit_2.setPlaceholderText(_translate(\"MainWindow\", \"Nom \"))\n self.pushButton.setText(_translate(\"MainWindow\", \"Update\"))\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n MainWindow = QtWidgets.QMainWindow()\n ui = updateWindow()\n ui.setupUi(MainWindow)\n MainWindow.show()\n sys.exit(app.exec_())\n","sub_path":"Gui/UpdateHosts.py","file_name":"UpdateHosts.py","file_ext":"py","file_size_in_byte":4052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"339383845","text":"import sys\nimport os\nsys.path.insert(0, os.path.abspath(\n os.path.join(os.path.dirname(__file__), '..')))\n\nfrom matplotlib import pyplot as plt # NOQA\nfrom collections import OrderedDict # NOQA\n\nfrom nik_sm.nik_sm_strategy import NikSelfishMining # NOQA\nfrom nik_sm.learning_automata_type import LearningAutomataType # NOQA\nfrom sm1.sm1_strategy import SelfishMiningOne # NOQA\n\niteration_number = 10000\n\ntow_number = 10\nmin_tow_block_number = 4\nmax_tow_block_number = 6\n\nreward_rate = 0.01\npenalty_rate = 0.01\n\nmin_k_1 = 1\nmax_k_1 = 3\nnik_defense_1 = NikSelfishMining(\n tow_number, min_tow_block_number, max_tow_block_number, reward_rate, penalty_rate, min_k_1, max_k_1, LearningAutomataType.AVDHLA, False)\nnik_defense_1.gamma = 0.5\n\nmin_k_2 = 2\nmax_k_2 = 4\nnik_defense_2 = NikSelfishMining(\n tow_number, min_tow_block_number, max_tow_block_number, reward_rate, penalty_rate, min_k_2, max_k_2, LearningAutomataType.AVDHLA, False)\nnik_defense_2.gamma = 0.5\n\nmin_k_3 = 1\nmax_k_3 = 5\nnik_defense_3 = NikSelfishMining(\n tow_number, min_tow_block_number, max_tow_block_number, reward_rate, penalty_rate, min_k_3, max_k_3, LearningAutomataType.AVDHLA, False)\nnik_defense_3.gamma = 0.5\n\n\nalpha_values = [x / 100 for x in range(25, 51) if x % 5 == 0]\n\nnik_defense_1_revenue = []\nnik_defense_1_stale_block = []\n\nnik_defense_2_revenue = []\nnik_defense_2_stale_block = []\n\nnik_defense_3_revenue = []\nnik_defense_3_stale_block = []\n\nideal_defense_revenue_value = []\nupper_bound_value = []\n\n\nfor alpha in alpha_values:\n nik_defense_1.reset()\n\n nik_defense_1.alpha = alpha\n nik_defense_1.start_simulate(iteration_number)\n nik_defense_1.print_final_result()\n nik_defense_1_revenue.append(nik_defense_1.revenue)\n nik_defense_1_stale_block.append(nik_defense_1.stale_block)\n\nfor alpha in alpha_values:\n nik_defense_2.reset()\n\n nik_defense_2.alpha = alpha\n nik_defense_2.start_simulate(iteration_number)\n nik_defense_2.print_final_result()\n nik_defense_2_revenue.append(nik_defense_2.revenue)\n nik_defense_2_stale_block.append(nik_defense_2.stale_block)\n\nfor alpha in alpha_values:\n nik_defense_3.reset()\n\n nik_defense_3.alpha = alpha\n nik_defense_3.start_simulate(iteration_number)\n nik_defense_3.print_final_result()\n nik_defense_3_revenue.append(nik_defense_3.revenue)\n nik_defense_3_stale_block.append(nik_defense_3.stale_block)\n\nfor alpha in alpha_values:\n ideal_defense_revenue_value.append(alpha * 100)\n\nfor alpha in alpha_values:\n upper_bound_value.append(alpha / (1 - alpha) * 100)\n\n\nlinestyles_dict = OrderedDict(\n [('solid', (0, ())),\n ('loosely dotted', (0, (1, 10))),\n ('dotted', (0, (1, 5))),\n ('densely dotted', (0, (1, 1))),\n\n ('loosely dashed', (0, (5, 10))),\n ('dashed', (0, (5, 5))),\n ('densely dashed', (0, (5, 1))),\n\n ('loosely dashdotted', (0, (3, 10, 1, 10))),\n ('dashdotted', (0, (3, 5, 1, 5))),\n ('densely dashdotted', (0, (3, 1, 1, 1))),\n\n ('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))),\n ('dashdotdotted', (0, (3, 5, 1, 5, 1, 5))),\n ('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))])\n\n\nplt.plot(\n alpha_values, nik_defense_1_revenue, color='r', label='K=[1,3]', linestyle=linestyles_dict['densely dotted'], linewidth=1.5)\nplt.plot(\n alpha_values, nik_defense_2_revenue, color='b', label='K=[2,4]', linestyle=linestyles_dict['densely dashdotdotted'], linewidth=1.5)\nplt.plot(\n alpha_values, nik_defense_3_revenue, color='y', label='K=[1,5]', linestyle=linestyles_dict['densely dashed'], linewidth=1.5)\n\nplt.plot(alpha_values, ideal_defense_revenue_value,\n color='k', label='Ideal Defense', linestyle=linestyles_dict['densely dashed'], linewidth=1.5)\nplt.plot(\n alpha_values, upper_bound_value, color='g', label='Upper Bound', linestyle=linestyles_dict['dashdotdotted'], linewidth=1.5)\n\nplt.title('ُNik Defense(AVDHLA) K Based Revenue Comparison-Ex2.3')\nplt.xlabel('Pool size')\nplt.ylabel('Relative Revenue')\n\nplt.legend(loc=\"upper left\")\n\nplt.show()\n\n\nplt.plot(\n alpha_values, nik_defense_1_stale_block, color='r', label='K=[1,3]', linestyle=linestyles_dict['densely dotted'], linewidth=1.5)\nplt.plot(\n alpha_values, nik_defense_2_stale_block, color='b', label='K=[2,4]', linestyle=linestyles_dict['densely dashdotdotted'], linewidth=1.5)\nplt.plot(\n alpha_values, nik_defense_3_stale_block, color='y', label='K=[1,5]', linestyle=linestyles_dict['densely dashed'], linewidth=1.5)\n\n\nplt.title('ُNik Defense(AVDHLA) K Based Stale Block Comparison-Ex2.3')\nplt.xlabel('Pool size')\nplt.ylabel('ُStale Block Number')\n\nplt.legend(loc=\"upper left\")\n\nplt.show()\n","sub_path":"tests/nik_selfish_mining_k_comparison_test.py","file_name":"nik_selfish_mining_k_comparison_test.py","file_ext":"py","file_size_in_byte":4710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"397628635","text":"#!/usr/bin/env python\nimport argparse\nfrom igf_data.task_tracking.igf_slack import IGF_slack\nfrom igf_data.utils.seqrunutils import load_new_seqrun_data\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-p','--seqrun_data', required=True, help='Seqrun data json file')\nparser.add_argument('-d','--dbconfig_path', required=True, help='Database configuration json file')\nparser.add_argument('-s','--slack_config', required=True, help='Slack configuration json file')\nargs = parser.parse_args()\n\ndbconfig_path = args.dbconfig_path\nslack_config = args.slack_config\nseqrun_data = args.seqrun_data\n\nslack_obj = IGF_slack(slack_config=slack_config)\n\nif __name__=='__main__':\n try:\n load_new_seqrun_data(data_file=seqrun_data, dbconfig=dbconfig_path)\n except Exception as e:\n message = 'Failed to load data to seqrun table, error: {0}'.format(e)\n slack_obj.post_message_to_channel(message,reaction='fail')\n raise ValueError(message)\n else:\n slack_obj.post_message_to_channel(message='Loaded new seqrun info to db',reaction='pass')","sub_path":"scripts/db_scripts/load_seqrun_data.py","file_name":"load_seqrun_data.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"574412655","text":"#!/usr/bin/env python\n#!-*-coding:utf-8 -*-\n#!@Create :2019/3/20 14:20\n#!@Author : zyy\n#!@File : DataTransforBigDatalog.py\n\nfilename='D:\\Datasets\\\\testcircle.txt'\nfileNew = 'D:\\Datasets\\\\testcircle.csv'\n\n#filename='D:\\Datasets\\com-friendster.ungraph\\com-friendster.ungraph.txt'\n#fileNew = 'D:\\Datasets\\\\friBDL.csv'\nfobj = open(fileNew, 'wb+')\nwith open(filename,'r') as f:\n next(f)\n next(f)\n next(f)\n next(f)\n #skip first four lines\n for line in f:\n line = line.replace('\\n', '') # 去掉换行符,需要注意\n print(line)\n res = line.split()\n srcid = res[0]\n dstid = res[1]\n input = srcid+','+dstid+'\\n'\n input1 = bytes(input,encoding=\"utf8\")\n fobj.write(input1)\n\n\n\n\nf.close()\nfobj.close()\n","sub_path":"DataTransforBigDatalog.py","file_name":"DataTransforBigDatalog.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"342741013","text":"# -*- coding:utf-8 -*-\n#--\n# Copyright (c) 2012-2014 Net-ng.\n# All rights reserved.\n#\n# This software is licensed under the BSD License, as described in\n# the file LICENSE.txt, which you should have received as part of\n# this distribution.\n#--\n\nfrom nagare import presentation, var, security\nfrom nagare.i18n import _\n\nfrom .comp import Title\n\n\n@presentation.render_for(Title, 'tabname')\ndef render(self, h, comp, *args):\n h.head << h.head.title(self.text)\n return h.root\n\n\n@presentation.render_for(Title)\ndef render(self, h, comp, *args):\n \"\"\"Render the title of the associated object\n\n Used by column title and card title on popin\n \"\"\"\n with h.div(class_='title'):\n kw = {}\n if not security.has_permissions('edit', self):\n kw['style'] = 'cursor: default'\n a = h.a(self.text, **kw)\n if security.has_permissions('edit', self):\n a.action(comp.answer)\n h << a\n return h.root\n\n\n@presentation.render_for(Title, model='edit')\ndef render(self, h, comp, *args):\n \"\"\"Render the title of the associated object\"\"\"\n text = var.Var(self.text)\n with h.form(class_='title-form'):\n id_ = h.generate_id()\n if self.field_type == 'textarea':\n h << h.textarea(self.text, id_=id_).action(text)\n elif self.field_type == 'input':\n h << h.input(type='text', value=self.text,\n id_=id_).action(text)\n else:\n raise ValueError(_('Unsupported field_type %r') % self.field_type)\n h << h.button(_('Save'), class_='btn btn-primary btn-small').action(\n lambda: comp.answer(self.change_text(text())))\n h << ' '\n h << h.button(_('Cancel'), class_='btn btn-small').action(comp.answer)\n h << h.script('YAHOO.kansha.app.selectElement(%r);YAHOO.kansha.app.hideCardsLimitEdit(%s)' % (id_, self.parent.id))\n return h.root\n","sub_path":"kansha/title/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"228672955","text":"#!/usr/bin/env python\nimport os\n\nfrom django.conf import settings\nfrom django.core.management import call_command\n\nTHIS_DIR = os.path.dirname(__file__)\n\n\ndef main():\n \"\"\"Dynamically configure the Django settings with the\n minimum necessary to get Django running tests\"\"\"\n settings.configure(\n INSTALLED_APPS=(\n 'rtl_django_tools',\n 'django.contrib.sites',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django_nose',\n 'registration',\n ),\n TEST_RUNNER = 'django_nose.NoseTestSuiteRunner',\n DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': '/tmp/registration.db',\n 'USER': '',\n 'PASSWORD': '',\n 'HOST': '',\n 'PORT': ''}},\n NOSE_ARGS=['--with-xunit', '-s'],\n ROOT_URLCONF=None,\n TEMPLATE_DIRS = (\n os.path.join(THIS_DIR, 'templates'),\n ),\n FIXTURES_DIR=(\n os.path.join(THIS_DIR, 'fixtures'),\n ),\n SITE_ID=1,\n )\n\n call_command('test', 'registration')\n\nif __name__ == '__main__':\n main()\n","sub_path":"runtests.py","file_name":"runtests.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"552925870","text":"from airflow import DAG\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom datetime import datetime, timedelta\nimport os\nimport sys\n\nPACKAGE_PARENT = '..'\nSCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))\nsys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))\n\nfrom DataUpdate.updateDataStockForAdjQuote import airflowCallable as updateDataStockForAdjQuote\nfrom DataUpdate.updateDataStockDescription import airflowCallable as updateDataStockDescription\nfrom DataUpdate.updateDataStockUnadjustedQuote import airflowCallable as updateDataStockUnadjustedQuote\nfrom DataUpdate.updateDataStockIndex import airflowCallable as updateDataStockIndex\nfrom DataUpdate.updateDataStockFundamental import airflowCallable as updateDataStockFundamental\nfrom DataUpdate.updateDataFundIndex import airflowCallable as updateDataFundIndex\nfrom DataUpdate.updateDataStockFlag import airflowCallable as updateDataStockFlag\nfrom DataUpdate.updateDataTushareDailyQuotes import airflowCallable as updateDataStockTushareQuotes\n\nfrom Basic.calForwardAdjAreaIndex import airflowCallable as calForwardAdjAreaIndex\nfrom Basic.calForwardAdjIndustryIndex import airflowCallable as calForwardAdjIndustryIndex\n\nfrom Derivatives.calStockFeatures import airflowCallableStockTechnicalInicators as calStockTechnicalInicators, \\\n airflowCallableStockExcessiveReturnArea as calStockExcessiveReturnArea, \\\n airflowCallableStockExcessiveReturnIndustry as calStockExcessiveReturnIndustry, \\\n airflowCallableStockExcessiveReturnHS300 as calStockExcessiveReturnHS300, \\\n airflowCallableStockExcessiveReturnMarket as calStockExcessiveReturnMarket, \\\n airflowCallableStockStationaryTechnicalIndicators as calStockStationaryTechnicalIndicators, \\\n airflowCallableStockStationaryFundamentalIndicators as calStockStationaryFundamentalIndicators\nfrom Derivatives.calStockMarketFeatures import airflowCallableArea as calAreaRiseRatio, \\\n airflowCallableIndustry as calIndustryRiseRatio, \\\n airflowCallableMarket as calMarketRiseRatio, \\\n airflowCallableAllStock as calAllStockRiseRatio\nfrom Derivatives.calStockBeta import airflowCallable as calStockBeta\nfrom Derivatives.calStockValue import airflowCallable as calStockValue\nfrom Derivatives.calStockDayNum import airflowCallable as calStockDayNum\nfrom Derivatives.calIndexFeatures import airflowCallableHS300Technical as calHS300TechnicalIndicator, \\\n airflowCallableStockIndexTechnical as calStockIndexTechnicalIndicators, \\\n airflowCallableStockIndexStationaryTechnical as calStockIndexStationaryTechnical, \\\n airflowCallableHS300StationaryTechnical as calHS300StationaryTechnical\nfrom Derivatives.calNonStockFeatures import airflowCallableFundIndex as calFundIndexFeatures\n\ndefault_args = {\n 'owner': 'airflow',\n 'depends_on_past': False,\n 'start_date': datetime(2015, 1, 1),\n 'email': ['13602819622@163.com'],\n 'email_on_failure': True,\n 'email_on_retry': False,\n 'retries': 1,\n 'retry_delay': timedelta(minutes=5),\n # 'queue': 'bash_queue',\n # 'pool': 'backfill',\n # 'priority_weight': 10,\n # 'end_date': datetime(2016, 1, 1),\n}\n# ========= dag =========\n# UTC time\ndag = DAG('afternoon_dag', catchup=False, schedule_interval='35 18 * * *', default_args=default_args)\n\n# ========= task ==========\n# update data\nt_stock_for_adj_quote = PythonOperator(\n task_id='data_stock_for_adj_quote',\n python_callable=updateDataStockForAdjQuote,\n dag=dag)\n\nt_stock_unadj_quote = PythonOperator(\n task_id='data_stock_unadj_quote',\n python_callable=updateDataStockUnadjustedQuote,\n dag=dag)\n\nt_stock_description = PythonOperator(\n task_id='data_stock_description',\n python_callable=updateDataStockDescription,\n dag=dag)\n\nt_stock_ts_quotes = PythonOperator(\n task_id='data_stock_ts_quotes',\n python_callable=updateDataStockTushareQuotes,\n dag=dag)\n\nt_stock_index = PythonOperator(\n task_id='data_stock_index',\n python_callable=updateDataStockIndex,\n dag=dag)\n\n# =============== boundary ============= (update source data first, and later update final data from different sources)\ndata_boundary_data_source = DummyOperator(task_id='data_boundary_afternoon_data_source', dag=dag)\ndata_boundary_data_source.set_upstream([t_stock_ts_quotes])\n\nt_fund_index = PythonOperator(\n task_id='data_fund_index',\n python_callable=updateDataFundIndex,\n dag=dag)\n\nt_stock_fundamental = PythonOperator(\n task_id='data_stock_fundamental',\n python_callable=updateDataStockFundamental,\n dag=dag)\n\ndata_boundary_data_source.set_downstream([t_fund_index, t_stock_fundamental])\n\n# =============== boundary ============= (dervative on stock quote and public index, composite customized index)\ndata_boundary = DummyOperator(task_id='data_boundary_afternoon', dag=dag)\ndata_boundary.set_upstream([t_stock_for_adj_quote, t_stock_unadj_quote, t_stock_description, t_stock_index, t_stock_fundamental, t_fund_index])\n\n# calculate features\nt_stock_technical = PythonOperator(\n task_id='feature_stock_technical',\n python_callable=calStockTechnicalInicators,\n dag=dag)\n\nt_stock_stat_technical = PythonOperator(\n task_id='feature_stock_stat_technical',\n python_callable=calStockStationaryTechnicalIndicators,\n dag=dag)\n\nt_stock_stat_fundamental = PythonOperator(\n task_id='feature_stock_stat_fundamental',\n python_callable=calStockStationaryFundamentalIndicators,\n dag=dag)\n\nt_stock_beta = PythonOperator(\n task_id='feature_stock_beta',\n python_callable=calStockBeta,\n dag=dag)\n\nt_stock_value = PythonOperator(\n task_id='feature_stock_value',\n python_callable=calStockValue,\n dag=dag)\n\nt_stock_daynum = PythonOperator(\n task_id='feature_stock_daynum',\n python_callable=calStockDayNum,\n dag=dag)\n\nt_HS300_technical = PythonOperator(\n task_id='feature_HS300_technical',\n python_callable=calHS300TechnicalIndicator,\n dag=dag)\n\nt_HS300_stat_technical = PythonOperator(\n task_id='feature_HS300_stat_technical',\n python_callable=calHS300StationaryTechnical,\n dag=dag)\n\nt_area_index_for_adj_quote = PythonOperator(\n task_id='data_area_index_for_adj_quote',\n python_callable=calForwardAdjAreaIndex,\n dag=dag)\n\nt_industry_index_for_adj_quote = PythonOperator(\n task_id='data_industry_index_for_adj_quote',\n python_callable=calForwardAdjIndustryIndex,\n dag=dag)\n\nt_fund_index_technical = PythonOperator(\n task_id='feature_fund_index',\n python_callable=calFundIndexFeatures,\n dag=dag)\n\nt_stock_flag = PythonOperator(\n task_id='data_stock_flag',\n python_callable=updateDataStockFlag,\n dag=dag)\n\ndata_boundary.set_downstream([t_stock_technical, t_stock_stat_technical, t_stock_stat_fundamental,\n t_stock_beta, t_stock_value, t_stock_daynum, t_HS300_technical, t_HS300_stat_technical,\n t_area_index_for_adj_quote, t_industry_index_for_adj_quote, t_fund_index_technical, t_stock_flag])\n\n# ================= boundry 2 =============== (derivative on customized index quote)\ndata_boundary2 = DummyOperator(task_id='data_boundary_afternoon_2', dag=dag)\ndata_boundary2.set_upstream([t_area_index_for_adj_quote, t_industry_index_for_adj_quote])\n\nt_stock_index_technical = PythonOperator(\n task_id='feature_stock_index_technical',\n python_callable=calStockIndexTechnicalIndicators,\n dag=dag)\n\nt_stock_index_stat_technical = PythonOperator(\n task_id='feature_stock_index_stat_technical',\n python_callable=calStockIndexStationaryTechnical,\n dag=dag)\n\ndata_boundary2.set_downstream([t_stock_index_technical, t_stock_index_stat_technical])\n\n# ============== boundry 3 ================== excessive return (stock derivatives over index derivatives)\ndata_boundary3 = DummyOperator(task_id='data_boundary_afternoon_3', dag=dag)\ndata_boundary3.set_upstream([t_stock_technical, t_stock_index_technical, t_HS300_technical])\n\nt_exc_ret_area = PythonOperator(\n task_id='feature_stock_excessive_return_area',\n python_callable=calStockExcessiveReturnArea,\n dag=dag)\n\nt_exc_ret_industry = PythonOperator(\n task_id='feature_stock_excessive_return_industry',\n python_callable=calStockExcessiveReturnIndustry,\n dag=dag)\n\nt_exc_ret_hs300 = PythonOperator(\n task_id='feature_stock_excessive_return_HS300',\n python_callable=calStockExcessiveReturnHS300,\n dag=dag)\n\nt_exc_ret_market = PythonOperator(\n task_id='feature_stock_excessive_return_market',\n python_callable=calStockExcessiveReturnMarket,\n dag=dag)\n\nt_rise_ratio_area = PythonOperator(\n task_id='feature_stock_rise_ratio_area',\n python_callable=calAreaRiseRatio,\n dag=dag)\n\nt_rise_ratio_industry = PythonOperator(\n task_id='feature_stock_rise_ratio_industry',\n python_callable=calIndustryRiseRatio,\n dag=dag)\n\nt_rise_ratio_market = PythonOperator(\n task_id='feature_stock_rise_ratio_market',\n python_callable=calMarketRiseRatio,\n dag=dag)\n\nt_rise_ratio_all_stock = PythonOperator(\n task_id='feature_stock_rise_ratio_all',\n python_callable=calAllStockRiseRatio,\n dag=dag)\n\ndata_boundary3.set_downstream([t_exc_ret_area, t_exc_ret_industry, t_exc_ret_market, t_exc_ret_hs300,\n t_rise_ratio_area, t_rise_ratio_industry, t_rise_ratio_market, t_rise_ratio_all_stock])","sub_path":"AirFlow/afternoonDAG.py","file_name":"afternoonDAG.py","file_ext":"py","file_size_in_byte":9402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"443780512","text":"#!/usr/bin/env python3\n\n\"\"\"\n Compare to scoring matrix, extract highest affinity binding site\n\n usage: highest_affinity_binding_site.py -m\n\"\"\"\nimport argparse\nimport os\nimport sys\n\ndef main(argv):\n \"\"\"\n main method\n \"\"\"\n args = parseArgs(argv)\n\n # create scoring matrix from file\n scoring_matrix = create_scoring_matrix_from_file(args.matrix)\n\n # retrieve highest scoring sequence and score\n sequence, score = get_highest_score_sequence(scoring_matrix)\n\n print(\"The highest scoring sequence is {} with a score of {}\".format(sequence, score))\n\n\n\ndef parseArgs(argv):\n \"\"\"\n cmd line input\n \"\"\"\n parser = argparse.ArgumentParser(description=\"This script generates sbatch script and submits sbatch job.\")\n parser.add_argument(\"-m\", \"--matrix\", required=True,\n help=\"[Required] Path to scoring matrix. matricies must be in nucleotide x (sequence length) format.\")\n\n # remove script call from list (this is passed as list of cmd line input with script at position 0)\n args = parser.parse_args(argv[1:])\n return args\n\ndef create_scoring_matrix_from_file(matrix_file):\n \"\"\"\n Reads columnar data from file, returns a dictionary representation of a matrix with {nucleotide: score}\n representing the columns in the data\n Args: matrix_file\n Returns: a dictionary representation of a 4 x p matrix where the rows are the 4 nucleotide bases\n and p is the length of the sequence\n \"\"\"\n file_data = [ x.split() for x in open(matrix_file).readlines() ]\n scoring_matrix = [ dict(A=float(a_score), C=float(c_score), G=float(g_score),\n T=float(t_score)) for a_score, c_score, g_score, t_score in\n zip(file_data[0], file_data[1], file_data[2], file_data[3])\n ]\n\n return scoring_matrix\n\ndef get_highest_score_sequence(matrix):\n \"\"\"\n modified create_scoring_matrix_from_file() from scan_sequence.py\n based on https://stackoverflow.com/a/268285/9708266\n Args: a matrix with columns represented as dictionaries where the key is the rowname\n Returns: a string length p representing the sequence with the highest score across the n x p matrix\n \"\"\"\n sequence_score_tuple = [[max(col, key=lambda key: col[key]), col[max(col, key=lambda key: col[key])]] for col in\n matrix]\n sequence = ''.join([x[0] for x in sequence_score_tuple])\n score = sum([x[1] for x in sequence_score_tuple])\n\n return sequence, score #''.join([max(col, key=lambda key: col[key]) for col in matrix])\n\n\n# call main method\nif __name__ == \"__main__\":\n main(sys.argv)","sub_path":"assignment6/highest_affinity_binding_site.py","file_name":"highest_affinity_binding_site.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"350659161","text":"import sympy as sy \nimport numpy as np \nimport matplotlib.pyplot as plt\nimport autograd.numpy as anp \nimport timeit \nfrom autograd import grad \nfrom autograd import elementwise_grad\nimport numpy.linalg as la \nimport scipy.sparse as sparse\n\n#############\n# Iterative solvers - QUESTION 1&2:\n#############\nplt.clf()\nsection = \"Iterative solvers\"\nprint(\"########\\n{} - QUESTION 1&2\\n########\\n\".format(section))\n\ndef jacobi(A, b, tol, maxiters, plot=False):\n\n\n\titer_count = 0\n\terror = np.inf \n\n\tD = np.diag(A)\t\n\tL = np.tril(A, k=-1)\n\tU = np.triu(A, k=1)\n\n\terror_tracker = np.empty(maxiters)\n\n\tassert np.allclose(A, np.diag(D) + L + U)\n\n\tD_inv = 1/D \n\tD_inv = D_inv.reshape((D_inv.size, 1))\n\n\tcur_x = np.zeros((A.shape[1],1))\n\n\twhile (iter_count < maxiters) and (error > tol):\n\n\t\tnew_x = cur_x + D_inv*(b-A@cur_x)\n\n\t\terror = np.max(np.abs(new_x - cur_x))\n\t\terror_tracker[iter_count] = error \n\t\titer_count += 1\n\n\n\t\tcur_x = new_x \n\n\terror_tracker = error_tracker[0:iter_count]\n\tif plot:\n\t\tplt.semilogy(range(iter_count), error_tracker)\n\t\tplt.xlabel(\"Iteration\")\n\t\tplt.ylabel(\"Absolute error of approx\")\n\t\tplt.title(\"Covergence of Jacobi Method\")\n\t\tplt.savefig('jacobi_covergence.png')\n\n\n\treturn cur_x \n\n\ndef diag_dom(n, num_entries=None):\n\t\"\"\"Generate a strictly diagonally dominant (n, n) matrix.\n\tParameters:\n\tn (int): The dimension of the system.\n\tnum_entries (int): The number of nonzero values.\n\tDefaults to n^(3/2)-n.\n\tReturns:\n\tA ((n,n) ndarray): A (n, n) strictly diagonally dominant matrix.\n\t\"\"\"\n\tif num_entries is None:\n\t\tnum_entries = int(n**1.5) - n\n\tA = np.zeros((n,n))\n\trows = np.random.choice(np.arange(0,n), size=num_entries)\n\tcols = np.random.choice(np.arange(0,n), size=num_entries)\n\tdata = np.random.randint(-4, 4, size=num_entries)\n\tfor i in range(num_entries):\n\t\tA[rows[i], cols[i]] = data[i]\n\tfor i in range(n):\n\t\tA[i,i] = np.sum(np.abs(A[i])) + 1\n\treturn A\n\ndef test_part1(n):\n\n\tA = diag_dom(n)\n\tb = np.random.random(n).reshape((n,1))\n\tx = jacobi(A, b, 10e-10, 200, plot=True)\n\n\treturn np.allclose(A@x, b)\n\nfor n in range(2, 10):\n\t#assert test_part1(n)\n\tassert True\nprint(\"Passed test #1\")\n\n#############\n# Iterative solvers - QUESTION 3:\n#############\nplt.clf()\nsection = \"Iterative solvers\"\nprint(\"########\\n{} - QUESTION 3\\n########\\n\".format(section))\n\ndef Gauss_Seidel(A, b, tol, maxiters, plot=False):\n\n\tn = A.shape[1]\n\titer_count = 0\n\terror = np.inf \n\n\terror_tracker = np.empty(maxiters)\n\n\tcur_x = np.zeros((n,1))\n\n\twhile (iter_count < maxiters) and (error > tol):\n\n\t\tpreserve_x = np.copy(cur_x)\n\t\tfor i in range(n):\n\t\t\tcur_x[i,0] += (1/A[i,i]) * (b[i,0] - A[i,:].T @ cur_x)\n\n\t\terror = np.max(np.abs(preserve_x - cur_x))\n\t\terror_tracker[iter_count] = error \n\t\titer_count += 1\n\n\n\terror_tracker = error_tracker[0:iter_count]\n\tif plot:\n\t\tplt.semilogy(range(iter_count), error_tracker)\n\t\tplt.xlabel(\"Iteration\")\n\t\tplt.ylabel(\"Absolute error of approx\")\n\t\tplt.title(\"Covergence of Gauss_Seidel Method\")\n\t\tplt.savefig('Gauss_Seidel_covergence.png')\n\n\n\treturn cur_x \n\ndef test_part3(n):\n\n\tA = diag_dom(n)\n\tb = np.random.random(n).reshape((n,1))\n\tx = Gauss_Seidel(A, b, 10e-10, 200, plot=True)\n\n\treturn np.allclose(A@x, b)\n\nfor n in range(2, 10):\n\tassert test_part3(n)\n\tassert True\nprint(\"Passed test #3\")\n\n#############\n# Iterative solvers - QUESTION 4:\n#############\nplt.clf()\nsection = \"Iterative solvers\"\nprint(\"########\\n{} - QUESTION 4\\n########\\n\".format(section))\n\ndef Gauss_Seidel_sparse(A, b, tol, maxiters):\n\t'''\n\tNOTE: matrix A is a sparse matrix\n\t'''\n\n\tn = A.shape[1]\n\titer_count = 0\n\terror = np.inf \n\n\tcur_x = np.zeros((n,1))\n\n\twhile (iter_count < maxiters) and (error > tol):\n\n\t\tpreserve_x = np.copy(cur_x)\n\t\tfor i in range(n):\n\t\t\trowstart = A.indptr[i]\n\t\t\trowend = A.indptr[i+1]\n\n\t\t\tAix = A.data[rowstart:rowend] @ cur_x[A.indices[rowstart:rowend]]\n\t\t\tcur_x[i,0] += (1/A[i,i]) * (b[i,0] - Aix)\n\n\t\terror = np.max(np.abs(preserve_x - cur_x))\n\t\titer_count += 1\n\n\treturn cur_x \n\ndef test_part4(n):\n\n\tA = diag_dom(n)\n\tb = np.random.random(n).reshape((n,1))\n\tx = Gauss_Seidel_sparse(sparse.csr_matrix(A), b, 10e-10, 200)\n\n\treturn np.allclose(A@x, b)\n\nfor n in range(2, 10):\n\tassert test_part4(n)\n\tassert True\nprint(\"Passed test #4\")\n\n\n#############\n# Iterative solvers - QUESTION 5:\n#############\nplt.clf()\nsection = \"Iterative solvers\"\nprint(\"########\\n{} - QUESTION 5\\n########\\n\".format(section))\n\ndef Gauss_Seidel_SOR(A, b, tol, maxiters, omega):\n\t'''\n\tNOTE: matrix A is a sparse matrix\n\t'''\n\n\tn = A.shape[1]\n\titer_count = 0\n\terror = np.inf \n\n\tcur_x = np.zeros((n,1))\n\n\twhile (iter_count < maxiters) and (error > tol):\n\n\t\tpreserve_x = np.copy(cur_x)\n\t\tfor i in range(n):\n\t\t\trowstart = A.indptr[i]\n\t\t\trowend = A.indptr[i+1]\n\n\t\t\tAix = A.data[rowstart:rowend] @ cur_x[A.indices[rowstart:rowend]]\n\t\t\tcur_x[i,0] += (omega/A[i,i]) * (b[i,0] - Aix)\n\n\t\terror = np.max(np.abs(preserve_x - cur_x))\n\t\titer_count += 1\n\n\treturn cur_x, iter_count\n\ndef test_part5(n):\n\n\tA = diag_dom(n)\n\tb = np.random.random(n).reshape((n,1))\n\tx = Gauss_Seidel_SOR(sparse.csr_matrix(A), b, 10e-10, 200, .5)[0]\n\n\treturn np.allclose(A@x, b)\n\nfor n in range(2, 10):\n\tassert test_part5(n)\n\tassert True\nprint(\"Passed test #5\")\n\n#############\n# Iterative solvers - QUESTION 6:\n#############\nplt.clf()\nsection = \"Iterative solvers\"\nprint(\"########\\n{} - QUESTION 6\\n########\\n\".format(section))\n\ndef laplace(n, omega, tol=10e-8, maxiters=100, plot=False):\n\n\tb_n = np.zeros(n)\n\tb_n[0] = -100\n\tb_n[n-1] = -100\n\tb = np.tile(b_n, n)\n\tb = b.reshape((n**2,1))\n\n\tA = np.tile(np.identity(n), (n,n) )\n\tnp.fill_diagonal(A, -4)\n\n\tones = np.ones( (n**2, n**2) )\n\tones_diag_upper = np.triu(np.tril(ones, 1), 1)\n\tones_diag_lower = np.triu(np.tril(ones, -1), -1)\n\n\tA = A + ones_diag_lower + ones_diag_upper\n\n\tx, iters = Gauss_Seidel_SOR(sparse.csr_matrix(A), b, tol, maxiters, omega)\n\n\tx = x.reshape((n,n))\n\n\tif plot:\n\t\tplt.pcolormesh(x, cmap=\"coolwarm\")\n\t\tplt.savefig('Laplace.png')\n\nlaplace(10, 1, plot=True)\n\n","sub_path":"ProbSets/Comp/Week6/solvers.py","file_name":"solvers.py","file_ext":"py","file_size_in_byte":5888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"310986910","text":"# Phi Vision, Inc.\n# __________________\n\n# [2020] Phi Vision, Inc. All Rights Reserved.\n\n# NOTICE: All information contained herein is, and remains\n# the property of Phi Vision Incorporated and its suppliers,\n# if any. The intellectual and technical concepts contained\n# herein are proprietary to Phi Vision, Inc\n# and its suppliers and may be covered by U.S. and Foreign Patents,\n# patents in process, and are protected by trade secret or copyright law.\n# Dissemination of this information or reproduction of this material\n# is strictly forbidden unless prior written permission is obtained\n# from Phi Vision, Inc.\n\n\"\"\"\nload K2HPD serialized TFRecords format.\nBy Fanghao Yang, 12/21/2020\n\"\"\"\n\nimport click\nfrom datasets.dataset_loader import load_dataset, parse_tfr_tensor\nfrom utilities.image_utils import generate_blended_heatmap\nfrom pathlib import Path\nimport pylab\n\n\n@click.command()\n@click.option('--input_file', help='input TFRecords file')\n@click.option('--image_type', help='Type of image loading from the dataset')\ndef load_k2hpd_test(input_file: str, image_type: str):\n dataset = load_dataset(Path(input_file), image_type=image_type)\n for element in dataset.take(5):\n example = parse_tfr_tensor(element, image_type=image_type)\n print(f\"Loading data for image: {example['name'].numpy().decode('ascii')}\")\n pylab.figure()\n depth_map = example['depth'].numpy()\n pylab.imshow(depth_map)\n # list heat maps\n blended_map = generate_blended_heatmap(example['heat_map'])\n pylab.figure()\n pylab.imshow(blended_map)\n pylab.show()\n\n\nif __name__ == '__main__':\n load_k2hpd_test()\n","sub_path":"test/load_k2hpd_test.py","file_name":"load_k2hpd_test.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"386152170","text":"# SPDX-FileCopyrightText: 2020 Phillip Burgess for Adafruit Industries\n#\n# SPDX-License-Identifier: MIT\n\n\"\"\"\nRASTER EYES for Adafruit Matrix Portal: animated spooky eyes.\n\"\"\"\n\n# pylint: disable=import-error\nimport math\nimport random\nimport time\nimport displayio\nimport adafruit_imageload\nfrom adafruit_matrixportal.matrix import Matrix\n\n# TO LOAD DIFFERENT EYE DESIGNS: change the middle word here (between\n# 'eyes.' and '.data') to one of the folder names inside the 'eyes' folder:\nfrom eyes.werewolf.data import EYE_DATA\n#from eyes.cyclops.data import EYE_DATA\n#from eyes.kobold.data import EYE_DATA\n#from eyes.adabot.data import EYE_DATA\n#from eyes.skull.data import EYE_DATA\n\n# UTILITY FUNCTIONS AND CLASSES --------------------------------------------\n\n# pylint: disable=too-few-public-methods\nclass Sprite(displayio.TileGrid):\n \"\"\"Single-tile-with-bitmap TileGrid subclass, adds a height element\n because TileGrid doesn't appear to have a way to poll that later,\n object still functions in a displayio.Group.\n \"\"\"\n def __init__(self, filename, transparent=None):\n \"\"\"Create Sprite object from color-paletted BMP file, optionally\n set one color to transparent (pass as RGB tuple or list to locate\n nearest color, or integer to use a known specific color index).\n \"\"\"\n bitmap, palette = adafruit_imageload.load(\n filename, bitmap=displayio.Bitmap, palette=displayio.Palette)\n if isinstance(transparent, (tuple, list)): # Find closest RGB match\n closest_distance = 0x1000000 # Force first match\n for color_index, color in enumerate(palette): # Compare each...\n delta = (transparent[0] - ((color >> 16) & 0xFF),\n transparent[1] - ((color >> 8) & 0xFF),\n transparent[2] - (color & 0xFF))\n rgb_distance = (delta[0] * delta[0] +\n delta[1] * delta[1] +\n delta[2] * delta[2]) # Actually dist^2\n if rgb_distance < closest_distance: # but adequate for\n closest_distance = rgb_distance # compare purposes,\n closest_index = color_index # no sqrt needed\n palette.make_transparent(closest_index)\n elif isinstance(transparent, int):\n palette.make_transparent(transparent)\n super(Sprite, self).__init__(bitmap, pixel_shader=palette)\n\n\n# ONE-TIME INITIALIZATION --------------------------------------------------\n\nMATRIX = Matrix(bit_depth=6)\nDISPLAY = MATRIX.display\n\n# Order in which sprites are added determines the 'stacking order' and\n# visual priority. Lower lid is added before the upper lid so that if they\n# overlap, the upper lid is 'on top' (e.g. if it has eyelashes or such).\nSPRITES = displayio.Group()\nSPRITES.append(Sprite(EYE_DATA['eye_image'])) # Base image is opaque\nSPRITES.append(Sprite(EYE_DATA['lower_lid_image'], EYE_DATA['transparent']))\nSPRITES.append(Sprite(EYE_DATA['upper_lid_image'], EYE_DATA['transparent']))\nSPRITES.append(Sprite(EYE_DATA['stencil_image'], EYE_DATA['transparent']))\nDISPLAY.show(SPRITES)\n\nEYE_CENTER = ((EYE_DATA['eye_move_min'][0] + # Pixel coords of eye\n EYE_DATA['eye_move_max'][0]) / 2, # image when centered\n (EYE_DATA['eye_move_min'][1] + # ('neutral' position)\n EYE_DATA['eye_move_max'][1]) / 2)\nEYE_RANGE = (abs(EYE_DATA['eye_move_max'][0] - # Max eye image motion\n EYE_DATA['eye_move_min'][0]) / 2, # delta from center\n abs(EYE_DATA['eye_move_max'][1] -\n EYE_DATA['eye_move_min'][1]) / 2)\nUPPER_LID_MIN = (min(EYE_DATA['upper_lid_open'][0], # Motion bounds of\n EYE_DATA['upper_lid_closed'][0]), # upper and lower\n min(EYE_DATA['upper_lid_open'][1], # eyelids\n EYE_DATA['upper_lid_closed'][1]))\nUPPER_LID_MAX = (max(EYE_DATA['upper_lid_open'][0],\n EYE_DATA['upper_lid_closed'][0]),\n max(EYE_DATA['upper_lid_open'][1],\n EYE_DATA['upper_lid_closed'][1]))\nLOWER_LID_MIN = (min(EYE_DATA['lower_lid_open'][0],\n EYE_DATA['lower_lid_closed'][0]),\n min(EYE_DATA['lower_lid_open'][1],\n EYE_DATA['lower_lid_closed'][1]))\nLOWER_LID_MAX = (max(EYE_DATA['lower_lid_open'][0],\n EYE_DATA['lower_lid_closed'][0]),\n max(EYE_DATA['lower_lid_open'][1],\n EYE_DATA['lower_lid_closed'][1]))\nEYE_PREV = (0, 0)\nEYE_NEXT = (0, 0)\nMOVE_STATE = False # Initially stationary\nMOVE_EVENT_DURATION = random.uniform(0.1, 3) # Time to first move\nBLINK_STATE = 2 # Start eyes closed\nBLINK_EVENT_DURATION = random.uniform(0.25, 0.5) # Time for eyes to open\nTIME_OF_LAST_MOVE_EVENT = TIME_OF_LAST_BLINK_EVENT = time.monotonic()\n\n\n# MAIN LOOP ----------------------------------------------------------------\n\nwhile True:\n NOW = time.monotonic()\n\n # Eye movement ---------------------------------------------------------\n\n if NOW - TIME_OF_LAST_MOVE_EVENT > MOVE_EVENT_DURATION:\n TIME_OF_LAST_MOVE_EVENT = NOW # Start new move or pause\n MOVE_STATE = not MOVE_STATE # Toggle between moving & stationary\n if MOVE_STATE: # Starting a new move?\n MOVE_EVENT_DURATION = random.uniform(0.08, 0.17) # Move time\n ANGLE = random.uniform(0, math.pi * 2)\n EYE_NEXT = (math.cos(ANGLE) * EYE_RANGE[0], # (0,0) in center,\n math.sin(ANGLE) * EYE_RANGE[1]) # NOT pixel coords\n else: # Starting a new pause\n MOVE_EVENT_DURATION = random.uniform(0.04, 3) # Hold time\n EYE_PREV = EYE_NEXT\n\n # Fraction of move elapsed (0.0 to 1.0), then ease in/out 3*e^2-2*e^3\n RATIO = (NOW - TIME_OF_LAST_MOVE_EVENT) / MOVE_EVENT_DURATION\n RATIO = 3 * RATIO * RATIO - 2 * RATIO * RATIO * RATIO\n EYE_POS = (EYE_PREV[0] + RATIO * (EYE_NEXT[0] - EYE_PREV[0]),\n EYE_PREV[1] + RATIO * (EYE_NEXT[1] - EYE_PREV[1]))\n\n # Blinking -------------------------------------------------------------\n\n if NOW - TIME_OF_LAST_BLINK_EVENT > BLINK_EVENT_DURATION:\n TIME_OF_LAST_BLINK_EVENT = NOW # Start change in blink\n BLINK_STATE += 1 # Cycle paused/closing/opening\n if BLINK_STATE == 1: # Starting a new blink (closing)\n BLINK_EVENT_DURATION = random.uniform(0.03, 0.07)\n elif BLINK_STATE == 2: # Starting de-blink (opening)\n BLINK_EVENT_DURATION *= 2\n else: # Blink ended,\n BLINK_STATE = 0 # paused\n BLINK_EVENT_DURATION = random.uniform(BLINK_EVENT_DURATION * 3, 4)\n\n if BLINK_STATE: # Currently in a blink?\n # Fraction of closing or opening elapsed (0.0 to 1.0)\n RATIO = (NOW - TIME_OF_LAST_BLINK_EVENT) / BLINK_EVENT_DURATION\n if BLINK_STATE == 2: # Opening\n RATIO = 1.0 - RATIO # Flip ratio so eye opens instead of closes\n else: # Not blinking\n RATIO = 0\n\n # Eyelid tracking ------------------------------------------------------\n\n # Initial estimate of 'tracked' eyelid positions\n UPPER_LID_POS = (EYE_DATA['upper_lid_center'][0] + EYE_POS[0],\n EYE_DATA['upper_lid_center'][1] + EYE_POS[1])\n LOWER_LID_POS = (EYE_DATA['lower_lid_center'][0] + EYE_POS[0],\n EYE_DATA['lower_lid_center'][1] + EYE_POS[1])\n # Then constrain these to the upper/lower lid motion bounds\n UPPER_LID_POS = (min(max(UPPER_LID_POS[0],\n UPPER_LID_MIN[0]), UPPER_LID_MAX[0]),\n min(max(UPPER_LID_POS[1],\n UPPER_LID_MIN[1]), UPPER_LID_MAX[1]))\n LOWER_LID_POS = (min(max(LOWER_LID_POS[0],\n LOWER_LID_MIN[0]), LOWER_LID_MAX[0]),\n min(max(LOWER_LID_POS[1],\n LOWER_LID_MIN[1]), LOWER_LID_MAX[1]))\n # Then interpolate between bounded tracked position to closed position\n UPPER_LID_POS = (UPPER_LID_POS[0] + RATIO *\n (EYE_DATA['upper_lid_closed'][0] - UPPER_LID_POS[0]),\n UPPER_LID_POS[1] + RATIO *\n (EYE_DATA['upper_lid_closed'][1] - UPPER_LID_POS[1]))\n LOWER_LID_POS = (LOWER_LID_POS[0] + RATIO *\n (EYE_DATA['lower_lid_closed'][0] - LOWER_LID_POS[0]),\n LOWER_LID_POS[1] + RATIO *\n (EYE_DATA['lower_lid_closed'][1] - LOWER_LID_POS[1]))\n\n # Move eye sprites -----------------------------------------------------\n\n SPRITES[0].x, SPRITES[0].y = (int(EYE_CENTER[0] + EYE_POS[0] + 0.5),\n int(EYE_CENTER[1] + EYE_POS[1] + 0.5))\n SPRITES[2].x, SPRITES[2].y = (int(UPPER_LID_POS[0] + 0.5),\n int(UPPER_LID_POS[1] + 0.5))\n SPRITES[1].x, SPRITES[1].y = (int(LOWER_LID_POS[0] + 0.5),\n int(LOWER_LID_POS[1] + 0.5))\n","sub_path":"Matrix_Portal_Eyes/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":9267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"299617010","text":"from flask_jwt import jwt_required\nfrom flask import request\nfrom . import rest\nfrom app import utils\nfrom app.model import User as UserModel\nfrom app.model import AbstractUser as AUserModel\nimport logging, datetime\n#from logging.config import fileConfig\n#fileConfig('conf/log-app.conf')\n#logger = logging.getLogger(__name__)\n\n\n#query all users\n@rest.route('users/privilege/', methods=['GET'])\n@jwt_required()\ndef get_privilege(loginUser):\n # default is lowest privilege\n privilege = 3\n errcode = 1\n ## here, need verify if loginUser has privilege to get user list\n user = AUserModel.IsExist(loginUser)\n logging.debug(\"user is %s\"%user)\n if user:\n privilege =user.privilege\n errcode = 0\n return utils.jsonresp(jsonobj={'errcode':errcode,'privilege':privilege})\n\n@rest.route('users/blgadmin/', methods=['GET'])\n@jwt_required()\ndef get_blgAdmins(loginUser):\n errcode = 1\n blgAdmins = []\n user = UserModel.IsExist(loginUser)\n if user:\n if user.privilege == '0': # only super admin can return all admin users\n blgAdmins = UserModel.GetBlgAdmins()\n errcode = 0\n return utils.jsonresp(jsonobj={'errcode':errcode,'blgAdmins':blgAdmins})\n\n@rest.route('users/blgqmuser/', methods=['GET'])\n@jwt_required()\ndef get_blgQMUsers(loginUser):\n errcode = 1\n blgQMUsers = []\n user = UserModel.IsExist(loginUser)\n if user:\n blgQMUsers = UserModel.GetBlgQMUsers(user.privilege, loginUser)\n errcode = 0\n\n return utils.jsonresp(jsonobj={'errcode':errcode,'blgQMUsers':blgQMUsers})\n\n\n@rest.route('users/blgquser/', methods=['GET'])\n@jwt_required()\ndef get_blgQUsers(loginUser):\n errcode = 1\n blgQUsers = []\n user = UserModel.IsExist(loginUser)\n if user:\n blgQUsers = UserModel.GetBlgQUsers(user.privilege, loginUser)\n errcode = 0\n\n return utils.jsonresp(jsonobj={'errcode':errcode,'blgQUsers':blgQUsers})\n\n\n\n#query all users\n@rest.route('users/', methods=['GET'])\n@jwt_required()\ndef get_users():\n limit = int(request.args.get('limit'))\n page = int(request.args.get('page'))\n # this name allow none, if no value, it mean query all user list under this amdin\n name = request.args.get('name')\n # \n total, users = 0, \"null\"\n loginUser = request.args.get('loginUser')\n ## here, need verify if loginUser has privilege to get user list\n if loginUser:\n user = UserModel.IsExist(loginUser)\n if user:\n if user.privilege == '0': # super admin\n if name:\n total, users = UserModel.SearchUserByName(page, limit, name)\n else:\n total, users = UserModel.GetUsers(page, limit)\n \n if user.privilege == '1': # admin \n if name:\n total, users = UserModel.SearchUserByName(page, limit, name, loginUser)\n else:\n total, users = UserModel.GetUsers(page, limit, loginUser) \n \n\n\n return utils.jsonresp(jsonobj={'total':total, 'limit':limit, 'users':users})\n\n\n\n# create one user\n@rest.route('users/', methods=['POST'])\n#@jwt_required()\ndef create_user():\n data = request.get_json('content')\n print(type(data))\n print(data)\n # need check if username already exist\n username = data.get('username')\n if username:\n user = UserModel.IsExist(username)\n if user:\n errcode = 2 # 2 mean username already exist\n else:\n errcode = UserModel.CreateUser(**data)\n else:\n errcode = 1\n\n return utils.jsonresp(jsonobj={'errcode':errcode})\n\n# update one user\n@rest.route('users/', methods=['PUT'])\n#@jwt_required()\ndef update_user(userid):\n data = request.get_json(force=True) \n print(data)\n print(type(data))\n errcode = UserModel.UpdateUser(userid, **data)\n return utils.jsonresp(jsonobj={'errcode':errcode})\n\n# delete one user\n@rest.route('users/', methods=['DELETE'])\n#@jwt_required()\ndef delete_user(username):\n errcode = UserModel.DeleteUser(username)\n return utils.jsonresp(jsonobj={'errcode':errcode})\n\n# patch del users\n@rest.route('users/batch/', methods=['DELETE'])\n#@jwt_required()\ndef delete_users(usernames):\n errcode = 0\n #nameList = names.split(',')\n for username in usernames.split(','):\n ret = UserModel.DeleteUser(username)\n if ret != 0:\n errcode = 1\n\n return utils.jsonresp(jsonobj={'errcode':errcode})\n\n\n# change password\n@rest.route('users/password/', methods=['PUT'])\n#@jwt_required()\ndef change_password(username):\n data = request.get_json(force=True) \n oldpwd = data.get('oldpwd')\n newpwd = data.get('newpwd')\n errcode = 1\n # check if username is exist\n #\n # check privi\n errcode = AUserModel.ChangePwd(username, oldpwd, newpwd )\n #errcode = UserModel.UpdateUser(userid, **data)\n return utils.jsonresp(jsonobj={'errcode':errcode})\n","sub_path":"server/app/rest/userapi.py","file_name":"userapi.py","file_ext":"py","file_size_in_byte":5017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"443145744","text":"import random\r\nimport time\r\nimport sys\r\n\r\ndef d_p(s):\r\n for c in s:\r\n sys.stdout.write(c)\r\n sys.stdout.flush()\r\n time.sleep(0.03)\r\n print(\"\")\r\n\r\ndef bad_input():\r\n print(\"Bad input.\")\r\n time.sleep(1)\r\n print(\"Please try again when prompted.\")\r\n time.sleep(1)\r\n\r\nclass Character:\r\n def __init__(self, name, race, cls, attack, defense, magic, range, hp, stealth, speed, luck, inv):\r\n self.name = name\r\n self.race = race\r\n self.cls = cls\r\n self.attack = attack\r\n self.defense = defense\r\n self.magic = magic\r\n self.range = range\r\n self.hp = hp\r\n self.stealth = stealth\r\n self.speed = speed\r\n self.luck = luck\r\n self.inv = inv\r\n\r\n def get_char_info(Character):\r\n print(Character.name.capitalize(), Character.race.capitalize(), Character.cls.capitalize(),f\"Inventory:{Character.inv}\")\r\n time.sleep(2)\r\n\r\n def get_char_stats(Character):\r\n d_p(f\"Attack = {Character.attack}, Defense = {Character.defense}, Magic = {Character.magic}, Range = {Character.range}\")\r\n d_p(f\"HP = {Character.hp}, Stealth = {Character.stealth}, Speed = {Character.speed}, Luck = {Character.luck}\")\r\n time.sleep(2)\r\n\r\n def dragon_base(Character):\r\n Character.race = \"dragon\"\r\n Character.attack = 150\r\n Character.defense = 150\r\n Character.magic = 1\r\n Character.range = 1\r\n Character.hp = 100\r\n Character.stealth = 2\r\n Character.speed = 3\r\n Character.inv = ['']\r\n\r\n def orc_base(Character):\r\n Character.race = \"orc\"\r\n Character.attack = 75\r\n Character.defense = 75\r\n Character.magic = 50\r\n Character.range = 00\r\n Character.hp = 75\r\n Character.stealth = 1\r\n Character.speed = 3\r\n Character.inv = ['']\r\n\r\n def human_base(Character):\r\n Character.race = \"human\"\r\n Character.attack = 50\r\n Character.defense = 50\r\n Character.magic = 50\r\n Character.range = 50\r\n Character.hp = 60\r\n Character.stealth = 5\r\n Character.speed = 3\r\n Character.inv = ['']\r\n\r\n def elf_base(Character):\r\n Character.race = \"elf\"\r\n Character.attack = 40\r\n Character.defense = 50\r\n Character.magic = 75\r\n Character.range = 75\r\n Character.hp = 50\r\n Character.stealth = 6\r\n Character.speed = 6\r\n Character.inv = ['']\r\n\r\n def dwarf_base(Character):\r\n Character.race = \"dwarf\"\r\n Character.attack = 100\r\n Character.defense = 100\r\n Character.magic = 1\r\n Character.range = 1\r\n Character.hp = 100\r\n Character.stealth = 2\r\n Character.speed = 3\r\n Character.inv = ['']\r\n\r\n def shaman(Character):\r\n d_p(\"A shaman uses magic to cripple an opponent's speed, while sapping life from them.\")\r\n d_p(\"Shaman's use wards to prevent enemies from harming them, and spirit energy to attack them.\")\r\n d_p(\"You have gained stats towards magic and defense, and your hp will randomly recover during fights.\")\r\n d_p(\"You have lost all stats in attack and range.\")\r\n\r\n Character.cls = \"shaman\"\r\n Character.magic += 60\r\n Character.defense += 30\r\n Character.attack = 1\r\n Character.range = 1\r\n\r\n def berserker(Character):\r\n d_p(\"A berserker cares nothing for defense and relies on reflexes to avoid damage during a relentless attack.\")\r\n d_p(\"Berserkers gain speed and attack bonuses during fights at the cost of defense.\")\r\n d_p(\"You have gained a massive attack bonus, and a slight speed bonus, but your defense has dropped.\")\r\n d_p(\"You have lost all stats in range and magic.\")\r\n\r\n Character.cls = \"berserker\"\r\n Character.attack += 75\r\n Character.defense -= 25\r\n Character.speed += 2\r\n Character.range = 1\r\n Character.magic = 1\r\n\r\n def rogue(Character):\r\n d_p(\"A rogue uses range to attack from afar and speed to attack quickly in near quarters.\")\r\n d_p(\"Due to a rogue's stealth, they often are successful in one attack assassinations.\")\r\n d_p(\"You have gained bonuses in stealth, speed, and range, and a slight bonus in attack.\")\r\n\r\n Character.cls = \"rogue\"\r\n Character.attack += 10\r\n Character.range += 30\r\n Character.speed += 4\r\n Character.stealth += 5\r\n\r\n def warrior(Character):\r\n d_p(\"A warrior uses speed with attack and defense skills to handle opponents head on.\")\r\n d_p(\"You have gained bonuses in attack, defense, and hp, but have lost all stats in range and mage\")\r\n\r\n Character.cls = \"warrior\"\r\n Character.attack += 40\r\n Character.defense += 40\r\n Character.hp += 10\r\n Character.magic = 1\r\n Character.range = 1\r\n Character.speed += 1\r\n\r\n def ranger(Character):\r\n d_p(\"A ranger uses ranged weapons to handle enemies from afar.\")\r\n d_p(\"Often, rangers are able to get off two attacks before an enemy can attack.\")\r\n d_p(\"You have gained bonuses in range at the cost of attack and magic.\")\r\n\r\n Character.cls = \"ranger\"\r\n Character.range += 75\r\n Character.speed += 1\r\n Character.attack = 1\r\n Character.magic = 1\r\n\r\n def mage(Character):\r\n d_p(\"A mage uses energy to bend reality, especially the elements, to fight.\")\r\n d_p(\"You have gained a massive magic bonus, at the cost of attack and range.\")\r\n\r\n Character.cls = \"mage\"\r\n Character.magic += 75\r\n Character.speed +=1\r\n Character.attack = 1\r\n Character.range = 1\r\n def hunter(Character):\r\n d_p(\"So you have chosen to be a dragon.\")\r\n d_p(\"You are the last of your people, and have thus raised yourself by hunting in the wild.\")\r\n d_p(\"You start with massive stats, but your story will unfold with many mysteries.\")\r\n d_p(\"Be on the lookout for those like you as the story unfolds.\")\r\n\r\n Character.cls = \"hunter\"\r\n\r\n\r\n def player_creation(Character):\r\n ### build race attributes and class attributes\r\n ### Add fancy stuff around mechanics\r\n print(\"Let's build your character.\")\r\n time.sleep(1)\r\n print(\"Please do NOT type until the text has finished displaying.\")\r\n time.sleep(1)\r\n print(\"Typing beforehand will cause return errors, and your character will not be properly built.\")\r\n time.sleep(1)\r\n Character.name = input(\"What is your name? \").lower()\r\n\r\n races = [\"dragon\", \"orc\", \"elf\", \"dwarf\", \"human\"]\r\n print(\"let's select your race. You can be {} or {}.\".format(\", \".join(races[0:-1]), races[-1]))\r\n Character.race = \"\"\r\n while Character.race == \"\":\r\n Character.race = input(\"What race would you like to be: \").lower()\r\n if not Character.race in races:\r\n bad_input()\r\n Character.race = \"\"\r\n getattr(Character, Character.race + \"_base\")()\r\n\r\n classes = (\"mage\", \"ranger\", \"warrior\", \"rogue\", \"berserker\", \"shaman\")\r\n Character.cls = \"\"\r\n while Character.cls == \"\":\r\n if Character.race == \"dragon\":\r\n Character.hunter()\r\n else:\r\n print(\"let's select your race. You can be {} or {}.\".format(\", \".join(classes[0:-1]), classes[-1]))\r\n Character.cls = input(\"What class would you like to be: \").lower()\r\n if not Character.cls in classes:\r\n bad_input()\r\n Character.cls = \"\"\r\n getattr(Character, Character.cls)()\r\n\r\n\r\n luck = random.randint(1, 10)\r\n Character.luck = luck\r\n\r\n def fightIntro(Character):\r\n time.sleep(.5)\r\n print(\"\\n\" * 10)\r\n d_p(\"We are going to quickly simulate a fight between you and a robber before going on.\")\r\n d_p(\"You will be able to do an accurate attack, strong attack, or very aggressive attack.\")\r\n d_p(\"Type the respective number when prompted, and you will attack respective of your class.\")\r\n d_p(\"As the fight goes on, you will see the left over health of your character and the opponent character.\")\r\n d_p(\"If you lose: GAME OVER\")\r\n d_p(\"Let's begin!\")\r\n time.sleep(1.5)\r\n print(\"\\n\" * 10)\r\n\r\n def fight(Character, NPC):\r\n ### To do tasks\r\n ### continue loop so that NPC.speed > character plays...\r\n ### finish the loop without -hp showing\r\n ### create a class based fighting style, so that robbers don't use magic... lol\r\n # create functions that can be called in fights based on character class\r\n\r\n def char_fight_attack():\r\n d_p(\"You can make an accurate attack, a strong attack, or a very aggressive attack.\")\r\n d_p(\"At the prompt, type the number corresponding to your desired attack.\")\r\n a = \"\"\r\n while a == \"\":\r\n a = input(\"[1] accurate, [2] strong, [3] very aggressive: \")\r\n if a == \"1\":\r\n attack = (Character.attack * random.randint(1, 2))\r\n b = 0\r\n elif a == \"2\":\r\n attack = (Character.attack * random.randint(1, 3))\r\n b = 1\r\n elif a == \"3\":\r\n attack = (Character.attack * random.randint(0, 6))\r\n b = 2\r\n else:\r\n bad_input()\r\n defense = (NPC.defense * random.randint(1, 4))\r\n total = (attack / defense) + 1\r\n health = (NPC.hp - total)\r\n NPC.hp = health // 1\r\n attack_tuple = (\"Accurate\", \"Strong\", \"Very Aggressive\")\r\n d_p(\"{} used {} attack.\".format(Character.name.capitalize(), attack_tuple[b]))\r\n if total < NPC.hp:\r\n print(f\"{Character.name.capitalize()} did {int(total)} damage!\")\r\n if NPC.hp > 0:\r\n print(int(NPC.hp))\r\n elif NPC.hp < 0:\r\n print(f\"{NPC.name} died!\")\r\n def char_fight_mage():\r\n d_p(\"You can use an elemental spell of water, fire, or lightening.\")\r\n d_p(\"At the prompt, type the number corresponding to your desired attack.\")\r\n a = \"\"\r\n while a == \"\":\r\n a = input(\"[1] (water) accurate, [2] (fire) strong, [3] (lightening) very aggressive: \")\r\n if a == \"1\":\r\n attack = (Character.magic * random.randint(1, 2))\r\n b = 0\r\n elif a == \"2\":\r\n attack = (Character.magic * random.randint(1, 3))\r\n b = 1\r\n elif a == \"3\":\r\n attack = (Character.magic * random.randint(0, 6))\r\n b = 2\r\n else:\r\n bad_input()\r\n magic_tuple = (\"water\", \"fire\", \"lightening\")\r\n print(\"{} used {}\".format(Character.name.capitalize(), magic_tuple[b]))\r\n attack = (Character.magic * 2 * random.randint(1, 2))\r\n defense = (NPC.defense * random.randint(1, 4))\r\n total = (attack / defense) + 1\r\n health = (NPC.hp - total)\r\n NPC.hp = health // 1\r\n if NPC.hp > 0:\r\n print(int(NPC.hp))\r\n\r\n def char_fight_range():\r\n print(\"You used a ranged attack.\")\r\n attack = (Character.range * random.randint(1, 4))\r\n defense = (NPC.defense * random.randint(1, 4))\r\n total = (attack / defense)\r\n health = (NPC.hp - total)\r\n NPC.hp = health // 1\r\n if NPC.hp > 0:\r\n (int(NPC.hp))\r\n elif NPC.hp <= 0:\r\n print(f\"{NPC.name} died!\")\r\n if ((Character.speed - NPC.speed) > NPC.speed) and NPC.hp > 0:\r\n d_p(f\"{Character.name.capitalize()} was twice as fast as {NPC.name}, and was able to get off an extra shot\")\r\n attack = (Character.attack * random.randint(1, 4))\r\n defense = (NPC.defense * random.randint(1, 4))\r\n total = (attack / defense) + 1\r\n health = (NPC.hp - total)\r\n NPC.hp = health // 1\r\n if NPC.hp > 0:\r\n print(int(NPC.hp))\r\n\r\n def char_fight_rogue():\r\n if Character.speed > NPC.speed:\r\n first_move = True\r\n while first_move == True:\r\n d_p(\"You make the first move. You can use a stealth attack, a regular attack, or a ranged attack.\")\r\n first_move = input(\"Choose your move [1] stealth [2] regular [3] ranged: \")\r\n if first_move == \"1\":\r\n if Character.stealth < NPC.speed:\r\n attack = 0\r\n elif Character.stealth > NPC.speed:\r\n attack = (Character.attack * random.randint(2, 10))\r\n b = 0\r\n defense = (NPC.defense * random.randint(1, 4))\r\n total = (attack / defense)\r\n health = (NPC.hp - total)\r\n NPC.hp = health // 1\r\n first_move = False\r\n elif first_move == \"2\":\r\n attack = (Character.attack * random.randint(1, 2))\r\n b = 1\r\n defense = (NPC.defense * random.randint(1, 4))\r\n total = (attack / defense)\r\n health = (NPC.hp - total)\r\n NPC.hp = health // 1\r\n first_move = False\r\n elif first_move == \"3\":\r\n attack = (Character.attack * random.randint(0, 6))\r\n b = 2\r\n attack = (Character.range * random.randint(1, 4))\r\n defense = (NPC.defense * random.randint(1, 4))\r\n total = (attack / defense)\r\n health = (NPC.hp - total)\r\n NPC.hp = health // 1\r\n first_move = False\r\n else:\r\n bad_input()\r\n first_move = True\r\n if NPC.hp > 0:\r\n print(int(NPC.hp))\r\n npc_fight()\r\n while first_move == False:\r\n while Character.hp > 0 and NPC.hp > 0:\r\n d_p(\"You can use a ranged attack or a physical attack.\")\r\n a = \"\"\r\n while a == \"\":\r\n a = input(\"[1] ranged attack [2] physical attack: \")\r\n if a == \"1\":\r\n char_fight_range()\r\n elif a == \"2\":\r\n char_fight_attack()\r\n else:\r\n bad_input()\r\n if NPC.hp > 0:\r\n npc_fight()\r\n if NPC.hp < 0:\r\n first_move = \"\"\r\n def char_fight_shaman():\r\n d_p(\"You can use a spirit attack, a defensive ward, or an hp boost.\")\r\n d_p(\"At the prompt, type the number corresponding to your desired attack.\")\r\n a = \"\"\r\n while a == \"\":\r\n a = input(\"[1] spirit attack, [2] defensive ward, [3] hp boost: \")\r\n if a == \"1\":\r\n attack = (Character.magic * random.randint(1, 3) + (Character.hp/NPC.hp))\r\n print(\"You stole your opponent's spirit energy to attack them.\")\r\n attack = (Character.magic * 2 * random.randint(1, 2))\r\n defense = (NPC.defense * random.randint(1, 4))\r\n total = (attack / defense) + 1\r\n health = (NPC.hp - total)\r\n NPC.hp = health // 1\r\n if NPC.hp > 0:\r\n print(NPC.hp)\r\n elif a == \"2\":\r\n defense = ((Character.defense * (1 + random.random())) // 1)\r\n Character.defense = defense\r\n print(\"You create a defensive ward.\")\r\n print(int(Character.defense))\r\n\r\n elif a == \"3\":\r\n sha_health = (Character.hp + random.randint(10, 100))\r\n Character.hp = sha_health\r\n print(f\"Your hp is now {Character.hp}.\")\r\n else:\r\n bad_input()\r\n\r\n\r\n def npc_fight():\r\n if NPC.cls == \"fighter\":\r\n print(f\"{NPC.name} attacked!\")\r\n attack = (NPC.attack * random.randint(1, 4))\r\n defense = (Character.defense * random.randint(1, 4))\r\n total = (attack / defense) + 1\r\n health = (Character.hp - total)\r\n Character.hp = health // 1\r\n print(int(Character.hp))\r\n elif NPC.cls == \"mage\":\r\n d_p(f\"{NPC.name} used magic to attack!\")\r\n attack = (NPC.magic * random.randint(1, 4))\r\n defense = (Character.defense * random.randint(1, 4))\r\n total = (attack / defense) + 1\r\n health = (Character.hp - total)\r\n Character.hp = health // 1\r\n print(int(Character.hp))\r\n elif NPC.cls == \"ranger\":\r\n d_p(f\"{NPC.name} used a ranged attack!\")\r\n attack = (NPC.attack * random.randint(1, 4))\r\n defense = (Character.defense * random.randint(1, 4))\r\n total = (attack / defense)\r\n health = (Character.hp - total)\r\n Character.hp = health // 1\r\n print(int(Character.hp))\r\n if (NPC.speed - Character.speed) > Character.speed:\r\n d_p(f\"{NPC.name} was twice as fast as {Character.name}, and was able to get off an extra shot\")\r\n attack = (NPC.attack * random.randint(1, 4))\r\n defense = (Character.defense * random.randint(1, 4))\r\n total = (attack / defense) - 1\r\n health = (Character.hp - total)\r\n Character.hp = health // 1\r\n print(int(Character.hp))\r\n\r\n a_health = Character.hp\r\n a_defense = Character.defense\r\n while Character.hp > 0 and NPC.hp > 0:\r\n if Character.speed >= NPC.speed:\r\n print(f\"{Character.name.capitalize()}'s turn.\")\r\n time.sleep(1)\r\n if Character.cls in (\"berserker\", \"warrior\", \"hunter\"):\r\n fight_sequence = True\r\n while fight_sequence == True:\r\n char_fight_attack()\r\n if NPC.hp > 0:\r\n npc_fight()\r\n if NPC.hp <= 0:\r\n print(f\"{NPC.name} lost.\")\r\n fight_sequence = False\r\n if Character.cls == \"mage\":\r\n fight_sequence = True\r\n while fight_sequence == True:\r\n char_fight_mage()\r\n if NPC.hp > 0:\r\n npc_fight()\r\n if NPC.hp <= 0:\r\n print(f\"{NPC.name} lost.\")\r\n fight_sequence = False\r\n if Character.cls == \"rogue\":\r\n char_fight_rogue()\r\n if Character.cls == \"shaman\":\r\n fight_sequence = True\r\n while fight_sequence == True:\r\n char_fight_shaman()\r\n if NPC.hp > 0:\r\n npc_fight()\r\n if NPC.hp <= 0:\r\n print(f\"{NPC.name} lost.\")\r\n fight_sequence = False\r\n\r\n\r\n elif NPC.speed > Character.speed:\r\n pass\r\n if Character.hp > 0:\r\n Character.hp = a_health\r\n Character.defense = a_defense\r\n if Character.hp < 0:\r\n print(\"GAME OVER\")\r\n exit()\r\n\r\n\r\n\r\n\r\nclass NPC:\r\n def __init__(self, name, race, cls, attack, defense, magic, range, hp, stealth, speed, luck):\r\n self.name = name\r\n self.race = race\r\n self.cls = cls\r\n self.attack = attack\r\n self.defense = defense\r\n self.magic = magic\r\n self.range = range\r\n self.hp = hp\r\n self.stealth = stealth\r\n self.speed = speed\r\n self.luck = luck\r\n\r\n ### define robber, mage, boss, and other NPC stats\r\n#ignore below this line... testing\r\n# \r\n# player = Character(\"A\", \"human\", \"shaman\", 100, 100, 100, 100, 100, 100, 100, 100, \"\")\r\n# robber = NPC(\"Robber\", \"human\", \"fighter\", 50, 10, 1, 1, 50, 1, 1, random.random())\r\n# rogue_mage = NPC(\"Rogue Mage\", \"human\", \"mage\", 0, 10, 15, 0, 25, 0, 110, 10)\r\n# NPC1 = robber\r\n# NPC2 = rogue_mage\r\n# \r\n# print(\"random dooooog\")\r\n# Character.player_creation(player)\r\n# Character.get_char_stats(player)\r\n# Character.get_char_info(player)\r\n# Character.fightIntro(player)\r\n# Character.fight(player, robber)\r\n# print(player.hp)","sub_path":"character.py","file_name":"character.py","file_ext":"py","file_size_in_byte":21392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"7808370","text":"\n#=================================================\n#\n#File Name \t\t: 1.py\n#\n#Purpose \t\t: A func() that return a decimal \n# string from a fraction\n#\n#Creation Date : 22=2=008\n#\n#Last Modified : Mon 22 Dec 2008 10:36:49 PM PST\n#\n#Created By : Prathu Baronia, 14D070046 \n#\n#=================================================\n\nclass Solution:\n # @param A : integer\n # @param B : integer\n # @return a strings\n \n def fractionToDecimal(self, A, B):\n \n def fractional_part(A,B):\n \n rem = abs_A%abs_B\n d = []\n res = \"\"\n \n while(rem!=0 & ~(rem in d)):\n d.append(rem)\n rem = rem*10\n res = res + str(rem//B)\n rem = rem%B\n \n if(rem==0):\n return res\n else:\n return (\"(\" + res + \")\")\n \n if(A==0):\n return 0\n \n sign = 1\n \n if((A<0)^(B<0)):\n sign = -1\n \n abs_A = abs(A)\n abs_B = abs(B)\n \n integer_part = abs_A//abs_B\n \n res = \"\"\n if(sign==-1):\n res = \"-\" + str(integer_part)\n else:\n res = \"\" + str(integer_part)\n \n res = res + fractional_part(abs_A,abs_B)\n \n return res\n\n","sub_path":"Hashing/fraction.py","file_name":"fraction.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"548872990","text":"from protein import Protein\n\nclass BlastMatch():\n\n\tdef __init__(self, target_protein=None, protein_name=None, evalue=None, accession_number=None, description=None, aaseq=None, tags=None):\n\t\tself.target_protein = target_protein\n\t\tself.protein = Protein.from_name_and_sequence(protein_name, aaseq)\n\t\tself.protein.accession_number = accession_number\n\t\tself.protein.description = description\n\t\tself.evalue = evalue\n\t\tself.tags = tags\n\n\tdef __str__(self):\n\t\tretstring = \"Target Protein Name: \" + self.target_protein.name + '\\n'\n\t\tretstring += \"Description: \" + self.protein.description + '\\n'\n\t\tretstring += \"eValue: \" + self.evalue + '\\n'\n\t\tretstring += \"Tags: \" + self.tags + '\\n'\n\t\treturn retstring\n\n\tdef to_csv_line(self):\n\t\tvalues = [self.protein.name, self.evalue, self.protein.accession_number, self.protein.description, self.protein.aaseq, self.tags]\n\t\treturn ','.join(values)\n\nclass BlastInfo():\n\n\tdef __init__(self, target_protein, matches=None):\n\t\tself.target_protein = target_protein\n\t\tself.matches = []\n\t\tif matches:\n\t\t\tself.top_matches = top_matches\n\n\tdef has_result(self):\n\t\treturn self.matches != []\n\n\tdef get_target_protein_name(self):\n\t\treturn self.target_protein.name\n\n\tdef add_match(self, match):\n\t\tself.matches.append(match)\n\n\tdef num_matches(self):\n\t\treturn len(self.matches)\n\n\tdef to_csv_lines(self):\n\t\tretstring = \"\"\n\t\tif self.has_result():\n\t\t\tfor match in self.matches:\n\t\t\t\tretstring += match.to_csv_line() + '\\n'\n\t\telse:\n\t\t\tretstring += self.target_protein.name + ',NO BLAST RESULT\\n'\n\t\treturn retstring\n\n\tdef __str__(self):\n\t\tretstring = \"Blast Info for Target Protein: \" + self.target_protein.name +'\\n'\n\t\tif not self.has_result():\n\t\t\tretstring += \"No matches.\\n\"\n\t\telse:\n\t\t\tfor match in self.matches:\n\t\t\t\tretstring += str(match)\n\t\treturn retstring\n\n\t@staticmethod\n\tdef construct_from_csv(filename):\n\t\tblastinfo_list = []\n\t\twith open(filename) as fp:\n\t\t\tline = fp.readline()\n\t\t\twhile line:\n\t\t\t\tline = line.replace('\\n', '')\n\t\t\t\ttokens = line.split(',')\n\t\t\t\tblastinfo = None\n\t\t\t\tfor item in blastinfo_list:\n\t\t\t\t\tif item.get_target_protein_name() == tokens[0]:\n\t\t\t\t\t\tblastinfo = item\n\t\t\t\t\t\tbreak\n\t\t\t\tif not blastinfo:\n\t\t\t\t\ttarget_protein = Protein.from_name_and_sequence(tokens[0], \"UNKNOWN\")\n\t\t\t\t\tblastinfo = BlastInfo(target_protein)\n\t\t\t\t\tblastinfo_list.append(blastinfo)\n\t\t\t\tif tokens[1].strip() != \"NO BLAST RESULT\":\n\t\t\t\t\tif len(tokens) != 6:\n\t\t\t\t\t\traise ValueError(\"Not enough arguments in data line.\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tblastmatch = BlastMatch(blastinfo.target_protein, tokens[0], tokens[1], tokens[2], tokens[3], tokens[4], tokens[5])\n\t\t\t\t\t\tblastinfo.add_match(blastmatch)\n\t\t\t\tline = fp.readline()\n\t\treturn blastinfo_list\n\n# blast_results = BlastInfo.construct_from_csv(\"Data/SampleData/SAMPLE_C_BLAST_RESULTS.csv\")\n# print(blast_results[0].to_csv_lines())\n\n\n\n\n\t\t","sub_path":"blast.py","file_name":"blast.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"588773035","text":"\nimport pytest\nimport numpy as np\nimport cntk as C\n\ndef test_outputs():\n fwd_state = C.placeholder(\"placeholder\")\n prev_state = C.sequence.past_value(fwd_state, name=\"prev_state\")\n z = C.abs(prev_state, \"abs\")\n output = z.output\n z = z.replace_placeholders({fwd_state: z.output})\n\n fwd_state = None\n prev_state = None\n z = None\n\n for arg in output.owner.arguments:\n print(\"Argument name: {}, argument owner name {}\".format(arg.name, arg.owner.name))\n\ndef test_0d_data_1d_sample_shape():\n x = C.input_variable(shape=(1,))\n op = x + x\n\n with pytest.raises(ValueError):\n op.eval({x : [np.asarray(2)]})\n\ndef test_1d_NDArrayView_copy():\n x = C.input_variable(shape=(1,))\n op = x + 1\n result = op.eval({x : [np.asarray([1])]}, as_numpy=False)\n result_slice = result.data.slice_view((0, 0), (1,))\n\n w = C.parameter(init=np.asarray([1]))\n w.set_value(result_slice)\n \n assert np.array_equal(w.value, result_slice.asarray())\n\ndef test_sequences_packed_in_single_ndarray():\n dim = 2\n input_with_sequence_axis = C.sequence.input_variable(shape=(dim,))\n\n data = np.asarray([[1, 2], [2, 3]])\n op = C.sequence.last(input_with_sequence_axis)\n result = op.eval({input_with_sequence_axis : data})\n assert np.array_equal(result, [[2., 3.]])\n\n result = op.eval({input_with_sequence_axis : (data, [True, True])})\n assert np.array_equal(result, [[1., 2.], [2., 3.]])\n\n \n","sub_path":"tests/function_test.py","file_name":"function_test.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"40446345","text":"\nfrom collections import defaultdict as dd\n\ndef list_features(input_file, output_file):\n f_cnt = dd(int)\n for line in open(input_file):\n inputs = line.strip().split()\n for t in inputs[1:]:\n f_cnt[t] += 1\n t_len = len(f_cnt.keys())\n f_set = sorted([(k, v) for k, v in f_cnt.iteritems() if v > 1], key = lambda x: x[1], reverse = True)\n\n f2ind = {}\n for i, k in enumerate(f_set):\n f2ind[k[0]] = i\n\n fout = open(output_file, 'w')\n for line in open(input_file):\n inputs = line.strip().split()\n s = inputs[0]\n for t in inputs[1:]:\n if t not in f2ind: continue\n s += \" {}\".format(f2ind[t])\n fout.write(s + '\\n')\n fout.close()\n\nlist_features('../diel/all_list_ALL.tok_feat', 'list_features.txt')","sub_path":"theano/list_features.py","file_name":"list_features.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"236250861","text":"import bottle\nimport pymongo\n\n@bottle.route('/')\ndef index():\n\tconnection = pymongo.MongoClient('localhost')\n\t\n\tdb = connection.test\n\t\n\tnames = db.names\n\t\n\titem = names.find_one()\n\t\n\treturn bottle.template('Hello {{name}}!', name=item['name'])\n\nbottle.run(host='localhost', port=8080)\n","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"406939481","text":"import torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.distributions.normal import Normal\nfrom torch.distributions.kl import kl_divergence\n\n# Hyper-parameters \ninput_size = 784\nnum_classes = 10\nnum_epochs = 5\nbatch_size = 100\nlearning_rate = 1e-4\n\n# MNIST dataset (images and labels)\ntrain_dataset = torchvision.datasets.MNIST(root='/Users/sunpeiquan/data',\n train=True,\n transform=transforms.ToTensor(),\n download=True)\n\ntest_dataset = torchvision.datasets.MNIST(root='/Users/sunpeiquan/data',\n train=False,\n transform=transforms.ToTensor())\n\n# Data loader (input pipeline)\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=batch_size,\n shuffle=True)\n\ntest_loader = torch.utils.data.DataLoader(dataset=test_dataset,\n batch_size=batch_size,\n shuffle=False)\n\n# Logistic regression model\nclass Encoder(nn.Module):\n def __init__(self):\n super().__init__()\n self.model = nn.Sequential(\n nn.Linear(input_size, 1024),\n nn.ReLU(),\n nn.Linear(1024, 1024),\n nn.ReLU()\n )\n self.mu = nn.Linear(1024, 256)\n self.sigma = nn.Linear(1024, 256)\n self.decoder = nn.Linear(256, num_classes)\n\n def forward(self, x):\n hidden = self.model(x)\n mu = self.mu(hidden)\n sigma = self.sigma(hidden)\n std = nn.functional.softplus(sigma)\n dist = Normal(mu, std)\n z = dist.rsample()\n return z, dist, mu\n\nencoder = Encoder()\n\n# model = nn.Linear(input_size, num_classes)\n\n# Loss and optimizer\n# nn.CrossEntropyLoss() computes softmax internally\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(encoder.parameters(), lr=learning_rate)\n\n# Train the model\ntotal_step = len(train_loader)\nfor epoch in range(num_epochs):\n for i, (images, labels) in enumerate(train_loader):\n # Reshape images to (batch_size, input_size)\n images = images.reshape(-1, 28*28)\n\n # Forward pass\n z, dist, mu = encoder(images)\n prior = Normal(torch.zeros_like(z), torch.ones_like(z))\n kl = 0.001 * kl_divergence(dist, prior).sum(1).mean()\n loss = criterion(z, labels) + kl\n\n # Backward and optimize\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if (i+1) % 100 == 0:\n print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'\n .format(epoch+1, num_epochs, i+1, total_step, loss.item()))\n\n# Test the model\n# In test phase, we don't need to compute gradients (for memory efficiency)\nwith torch.no_grad():\n correct = 0.\n total = 0\n for images, labels in test_loader:\n images = images.reshape(-1, 28*28)\n _, _, outputs = encoder(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum()\n\n print('Accuracy of the model on the 10000 test images: {} %'.format(100 * correct / total))\n\n# Save the model checkpoint\ntorch.save(encoder.state_dict(), 'model.ckpt')\n","sub_path":"tutorials/01-basics/logistic_regression/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"618641333","text":"# This code if a part of the HPM library for rapid hypersonic modelling.\n# Heads up! This software most likely still contains errors.\n# It is therefore distributed without warranty of merchantability.\n#\n#\n# HPM_read.py: here, all functions for reading of the input data and save data are defined. \n#\n# Developed/ made available: 19/10/2020 by M. Brchnelova\n# Questions? michaela.brchnelova@kuleuven.be\n\n\n\n\nfrom HPM_import import *\n\n\n\n\n\n\ndef ReadNullSpace(filename):\n j = 0.\n null_spaces = []\n with open(filename, \"r\") as ins:\n nullspace_array = []\n for line in ins:\n line = line.strip()\n line = line.split()\n if len(line) == 1:\n nullspace_array.append(float(line[0]))\n if len(line) > 1:\n null_spaces.append(nullspace_array)\n nullspace_array = []\n\n j += 1\n null_spaces.append(nullspace_array)\n\n null_spaces_formatted = []\n for i in range(0, len(null_spaces)):\n null_spaces_formatted.append(null_spaces[i])\n\n return null_spaces_formatted[1:]\n\n\n\n###############################################################################\n\n\n\ndef ReadInviscidData(filename):\n data = []\n nodes = []\n with open(filename, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n x = float(line[0])\n y = float(line[1])\n z = float(line[2])\n\n nodes.append([x, y, z])\n data.append(float(line[3]))\n\n return data, nodes\n\n\n\n###############################################################################\n\n\n\ndef ReadCentroids(filename):\n centroids = []\n with open(filename, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n x = float(line[0])\n y = float(line[1])\n z = float(line[2])\n\n centroids.append([x, y, z])\n\n return centroids\n\n\n\n###############################################################################\n\n\n\ndef ReadNormals(filename):\n normals = []\n with open(filename, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n x = float(line[0])\n y = float(line[1])\n z = float(line[2])\n\n normals.append([x, y, z])\n\n return normals\n\n\n\n###############################################################################\n\n\n\ndef ReadStagPointData(filename):\n stag_points = []\n stg_idxs = []\n epss = []\n with open(filename, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n stag_point = [float(line[0]), float(line[1]), float(line[2])]\n stg_idx = int(line[3])\n eps = float(line[4])\n\n stag_points.append(stag_point)\n stg_idxs.append(stg_idx)\n epss.append(eps)\n\n return stag_points, stg_idxs, epss\n\n\n\n###############################################################################\n\n\n\ndef ReadConnectivity(filename):\n connectivity = []\n with open(filename, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n x = int(line[0])\n y = int(line[1])\n z = int(line[2])\n\n connectivity.append([x, y, z])\n\n return connectivity\n\n\n\n###############################################################################\n\n\n\ndef ReadSolvedFitting(filename):\n j = 0.\n vectors = []\n with open(filename, \"r\") as ins:\n vector_array = []\n for line in ins:\n line = line.strip()\n line = line.split()\n if len(line) == 1:\n vector_array.append(float(line[0]))\n if len(line) > 1:\n vectors.append(vector_array)\n vector_array = []\n\n j += 1\n vectors.append(vector_array)\n\n solutions_formatted = []\n for i in range(0, len(vectors)):\n solutions_formatted.append(vectors[i])\n\n return solutions_formatted[1:]\n\n\n\n###############################################################################\n\n\n\ndef ReadBacktracingData(filename_intersections, filename_nodepaths, filename_nodecoords, filename_nodesresolved, filename_epsilonnodes):\n intersections = []\n node_paths_elem = []\n node_paths_coord = []\n epsilon_nodes = []\n nodes_resolved_idxs = []\n\n with open(filename_epsilonnodes, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n x = float(line[0])\n y = float(line[1])\n z = float(line[2])\n\n epsilon_nodes.append([x, y, z])\n\n with open(filename_intersections, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n x = float(line[0])\n y = float(line[1])\n z = float(line[2])\n\n intersections.append([x, y, z])\n\n with open(filename_nodesresolved, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n node_idx = int(line[0])\n\n nodes_resolved_idxs.append(node_idx)\n\n\n with open(filename_nodepaths, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n node_path = []\n for i in range(0, len(line)):\n node_path.append(int(line[i]))\n\n node_paths_elem.append(node_path)\n\n with open(filename_nodecoords, \"r\") as ins:\n for line in ins:\n line = line.strip()\n line = line.split()\n node_path_coord = []\n coord = []\n for i in range(0, len(line)):\n #print line\n if line[i][0] != ',':\n if line[i] != '' and line[i] != ' ' and line[i] != '\\n':\n coord_cur = float(line[i])\n coord.append(coord_cur)\n else:\n if line[i] != '' and line[i] != ' ' and line[i] != '\\n':\n node_path_coord.append(coord)\n if len(line[i][1:]) > 1:\n new_coord = line[i][1:]\n coord = [float(new_coord)]\n\n node_paths_coord.append(node_path_coord)\n\n\n return intersections, node_paths_elem, node_paths_coord, epsilon_nodes, nodes_resolved_idxs\n\n","sub_path":"single_SP/HPM_read.py","file_name":"HPM_read.py","file_ext":"py","file_size_in_byte":6474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"597317139","text":"from pymongo import MongoClient\r\ndef displayCursor(cursor):\r\n words = ''\r\n for doc in cursor:\r\n words += doc[\"word\"] + \",\"\r\n if len(words) > 65:\r\n words = words[:65] + \"...\"\r\n print (words)\r\ndef pageResults(collection, skip):\r\n query = {'first': 'w'} \r\n cursor = collection.find(query)\r\n cursor.limit(10)\r\n cursor.skip(skip)\r\n print (\"Page \" + str(skip+1) + \" to \" + \\\r\n str(skip + cursor.count(True)) + \":\")\r\n displayCursor(cursor);\r\n if(cursor.count(True) == 10):\r\n pageResults(collection, skip+10);\r\nif __name__==\"__main__\":\r\n mongo = MongoClient('mongodb://localhost:27017/')\r\n db = mongo['words']\r\n collection = db['word_stats']\r\n pageResults(collection, 0)","sub_path":"hour17/PythonFindPaging.py","file_name":"PythonFindPaging.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"592529135","text":"import requests\nimport json\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass OpenBD:\n def __init__(self):\n pass\n\n def get_json(self, isbn: str) -> dict:\n api_data = self.__call_api(isbn)\n if api_data == {}:\n return {}\n if api_data[0] == None:\n return {}\n json_data = {}\n json_data['isbn'] = api_data[0]['summary']['isbn']\n json_data['title'] = api_data[0]['summary']['title']\n json_data['series'] = api_data[0]['summary']['series']\n json_data['publisher'] = api_data[0]['summary']['publisher']\n json_data['pubdate'] = self.modify_datetime(api_data[0]['summary']['pubdate'])\n json_data['cover'] = api_data[0]['summary']['cover']\n json_data['author'] = self.clean_author(api_data[0]['summary']['author'])\n return json_data\n\n def __call_api(self, isbn: str) -> dict:\n url = 'https://api.openbd.jp/v1/get?isbn=' + isbn\n response = requests.get(url)\n if response.status_code != 200:\n return {}\n return json.loads(response.text)\n\n def modify_datetime(self, date: str) -> str:\n \"\"\"\n OpenBDのAPIで取得した出版日を整形する\n :param date:\n :return:\n \"\"\"\n return date.replace('c', '')\n\n def clean_author(self, author: str) -> str:\n \"\"\"\n OpenBDのAPIで取得した著者名を修正\n :param author:\n :return:\n \"\"\"\n return author.replace('/著', '')\n","sub_path":"api/book/openbd.py","file_name":"openbd.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"53857233","text":"#!/usr/bin/python\nimport Image\nimport tesseract\n\ndef extractText(pPath):\n lImage = Image.open(pPath) \n lResult = tesseract.image_to_string(lImage, lang=\"deu\")\n print (lResult)\n if (lResult != None):\n \treturn 1, pPath\n else:\n \treturn 0, pPath\n\n","sub_path":"BastelPython/src/Code-Snipels/OpenCV/src/prog/ocr.py","file_name":"ocr.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"635139629","text":"#!/usr/bin/env python\nfrom sqlalchemy import *\nfrom sqlalchemy.orm import column_property\n# cancerhermit\nfrom pg_catalog import pg_namespace, pg_type\nfrom pgvcs import ddl_object, constraint, label, range_params\n\nclass regtype(pg_type,ddl_object):\n __table__ = pg_type.__table__\n _regtype = column_property(\n func.regtypeout(pg_type.oid)\n )\n #format_type = column_property(\n # func.format_type(pg_type.oid,pg_type.typtypmod)\n #)\n parent_cls = [pg_namespace]\n filter = not_(pg_type.typname.like('%pg_toast_%'))\n child_cls = [constraint,label,range_params]\n required = True\n __synonyms__ = dict(\n name = \"typname\",\n default = \"typdefault\"\n )\n unused = [\n \"typlen\",\n \"typbyval\",\n \"typispreferred\",\n \"typisdefined\",\n \"typdelim\",\n \"typarray\",\n \"typalign\",\n \"typstorage\",\n \"typtypmod\",\n \"typndims\",\n \"typdefaultbin\"\n ]\n\n @property\n def regtype(self):\n regtype = self._regtype\n if regtype.find(\".\")>0:\n return regtype[regtype.find(\".\")+1:]\n else:\n return regtype\n\n @property \n def null(self):\n return not self.typnotnull\n\n @property\n def composite(self):\n return self.typtype=='c'\n\n @property\n def domain(self):\n return self.typtype=='d'\n\n @property\n def enum(self):\n return self.typtype=='e'\n\n @property\n def range(self):\n return self.typtype=='r'\n\n @property\n def basetype(self):\n return self.db[self.typbasetype]\n\n @classmethod\n def get_filter(cls,db):\n \"\"\"return SQLAlchemy filter for class\"\"\"\n # required for generate SQL\n required_oids = db.required_pg_type_oids\n schema_oids = map(\n lambda s:s.oid,\n filter(lambda s:s.included,db.schemas)\n )\n return and_(\n cls.filter,\n or_(\n pg_type.typnamespace.in_(schema_oids),\n pg_type.oid.in_(required_oids) if required_oids else None\n )\n )\n\n","sub_path":"pgvcs/ddl/regtype.py","file_name":"regtype.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"233417872","text":"import pandas as pd\nimport pymysql\npymysql.install_as_MySQLdb()\nimport MySQLdb\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nimport warnings\nimport pandas as pd\nimport FinanceDataReader as fdr\nimport numpy as np\nfrom datetime import datetime, timedelta\nimport time\nwarnings.filterwarnings(action='ignore')\nimport user\n\nquerys = pd.read_csv('investing_query.csv')\nsymbol_list = querys['symbol'].values\n\n\n# %%time\ntoday = datetime.today()\n\ndfs = fdr.DataReader(\"US500\",end=today) # fdr 기존 양식에 symbol_list를 추가하기 위해 base_table 생성\ndfs['Symbol'] = \"AAPL\"\nfor i in symbol_list:\n try:# apple data frame에 symbol_list 추가작업 진행\n data = fdr.DataReader(i, end=today)\n df = pd.DataFrame(data)\n df['Symbol'] = i\n dfs = pd.concat([df,dfs])\n except:\n pass\n\ndfs = dfs[['Symbol', 'Close', \"Open\", \"High\", \"Low\", \"Volume\", \"Change\"]]\ndfs = dfs.reset_index() # reset_index()를 사용해 date column에 위치하게 정렬\ndfs = dfs.drop_duplicates(['Symbol', 'Close', \"Open\", \"High\", \"Low\", \"Volume\", \"Change\"]) # 상단에 생성한 중복된 apple 정보 삭제\n# print(dfs)\n# print(\"time :\", time.time() - start) # 현재시각 - 시작시간 = 실행시간\n\nus_stock_basedata = pd.read_csv('./amount_to_be registered.csv') # frd에 없는 data csv로 import\n# us_stock_basedata\n\ndaily = pd.merge(dfs,us_stock_basedata, how='left', on='Symbol') # frd와 csv merge 작업 기준은 symbol로 잡아 왼쪽으로 정렬\n# daily\n\ndaily[\"market_capitalization\"] = daily[\"Close\"]*daily[\"amount_to_be_registered\"]\n# daily\na=daily.rename(columns={\"Change\":\"Changee\"})\nb=a.rename(columns={'index':'Date'})\nb.to_csv('daily_210730_3.csv')\n\n#1. mysqldb 접속객체 세팅(연결하기)\nconnect_datas = {\n 'host': user.host,\n 'user': user.user,\n 'passwd': user.pw,\n 'db': user.db,\n 'charset': 'utf8'\n}\ndb = MySQLdb.connect(**connect_datas)\n# db\n\n#2. 주가데이터 csv파일 불러오기\nstock = pd.DataFrame(b)\nstock_df = stock.drop(columns='Unnamed: 0')\nstock.rename(columns={'Change':'Changee'})\nstock_df.rename(columns={'index':'Date'})\n\n# MYsqldb로 테이블 생성하기\nQUERY = \"\"\"\n CREATE TABLE daily (\n Date DATE,\n Symbol Varchar(5) NOT NULL,\n Close INT(30) NOT NULL,\n Open INT(30)NOT NULL,\n High INT(30) NOT NULL,\n Low INT(30)NOT NULL,\n Volume DOUBLE,\n Changee Varchar(30),\n amount_to_be_registered INT(100),\n market_capitalization DOUBLE,\n FOREIGN KEY (Symbol) REFERENCES company(Symbol)\n )\n\"\"\"\n# cursor객체 생성후 쿼리 실행\ncurs = db.cursor()\ncurs.execute(QUERY)\n\n#3. sqlalchemy 클라이언트 설정\nclient = create_engine('mysql://{}:{}@{}/{}?charset=utf8'.format(user.user, user.pw, user.host, user.db),encoding=\"utf-8\")\nconn = client.connect()\n\n#4. csv파일 db에 담기(Daily file)\nstock.to_sql(name='daily',con=client, if_exists='append',index=False)\nconn.close()","sub_path":"US_stock/Dev/daily_starting.py","file_name":"daily_starting.py","file_ext":"py","file_size_in_byte":2989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"148825287","text":"class Tacotron2Config(object):\n \"\"\"Initialize Tacotron-2 Config.\"\"\"\n\n def __init__(\n self,\n max_len_seq=200,\n max_input_length=1000,\n embedding_hidden_size=64,\n\n # encoder层数\n n_conv_encoder=3,\n encoder_conv_filters=256,\n encoder_conv_kernel_sizes=5,\n encoder_conv_activation=\"relu\",\n encoder_conv_dropout_rate=0.1,\n encoder_lstm_units=256,\n\n # decode(限制条件:initial_hidden_size==2*encoder_lstm_units)\n attention_rnn_dim=512,\n decoder_lstm_dim=512,\n decoder_lstm_rate=0.1,\n initial_hidden_size=512,\n\n # Attention parameters\n attention_dim=128,\n # Location Layer parameters\n attention_filters=32,\n attention_kernel=31,\n\n # Mel-post processing network parameters\n n_prenet_layers=2,\n prenet_units=256,\n prenet_dropout_rate=0.1,\n gate_threshold=0.5,\n\n #postnet-conv1d层数\n n_conv_postnet=3,\n postnet_conv_filters=256,\n postnet_conv_kernel_sizes=5,\n postnet_dropout_rate=0.1,\n postnet_conv_activation=\"tanh\",\n checkpoingt_dir=r\"./checkpoints\",\n\n # ljspeech的path\n wave_train_path=r\"../data/LJSpeech-1.1/train/wavs/\",\n wave_test_path=r\"../data/LJSpeech-1.1/test/wavs/\",\n csv_dir=r\"../data/LJSpeech-1.1/metadata.csv\",\n save_path_dictionary=r\"../data/LJSpeech-1.1/dictionary.json\",\n\n # number的path\n wave_train_path_number=r\"../data/number/train/wavs/\",\n wave_test_path_number=r\"../data/number/test/wavs/\",\n csv_dir_number=r\"../data/number/metadata.csv\",\n save_path_dictionary_number=r\"../data/number/dictionary.json\",\n\n # 关于音频的参数\n sr=22050,\n n_fft=2048,\n frame_shift=0.0125,\n frame_length=0.05,\n hop_length=275,\n win_length=1102,\n n_mels=80,\n power=1.2,\n n_iter=100,\n preemphasis=.97,\n max_db=100,\n ref_db=20,\n top_db=15,\n # 其他\n batch_size=2,\n test_batch_size=1,\n #最大检查点保存数目\n max_to_keep=2,\n ):\n \"\"\"tacotron2参数.\"\"\"\n self.max_len_seq = max_len_seq\n self.max_input_length = max_input_length\n self.embedding_hidden_size = embedding_hidden_size\n self.n_conv_encoder = n_conv_encoder\n self.encoder_conv_filters = encoder_conv_filters\n self.encoder_conv_kernel_sizes = encoder_conv_kernel_sizes\n self.encoder_conv_activation = encoder_conv_activation\n self.encoder_conv_dropout_rate = encoder_conv_dropout_rate\n self.encoder_lstm_units = encoder_lstm_units\n\n # 解码器参数\n self.n_prenet_layers = n_prenet_layers\n self.prenet_units = prenet_units\n self.prenet_dropout_rate = prenet_dropout_rate\n self.attention_dim = attention_dim\n self.attention_filters = attention_filters\n self.attention_kernel = attention_kernel\n self.n_mels = n_mels\n self.attention_rnn_dim = attention_rnn_dim\n self.decoder_lstm_dim = decoder_lstm_dim\n self.decoder_lstm_rate = decoder_lstm_rate\n self.gate_threshold = gate_threshold\n self.initial_hidden_size = initial_hidden_size\n\n # postnet网络\n self.n_conv_postnet = n_conv_postnet\n self.postnet_conv_activation = postnet_conv_activation\n self.postnet_conv_filters = postnet_conv_filters\n self.postnet_conv_kernel_sizes = postnet_conv_kernel_sizes\n self.postnet_dropout_rate = postnet_dropout_rate\n\n # 检查点路径\n self.checkpoingt_dir = checkpoingt_dir\n\n # ljspeech路径\n self.wave_train_path = wave_train_path\n self.wave_test_path = wave_test_path\n self.save_path_dictionary = save_path_dictionary\n self.csv_dir = csv_dir\n\n # number路径\n self.wave_train_path_number = wave_train_path_number\n self.wave_test_path_number = wave_test_path_number\n self.save_path_dictionary_number = save_path_dictionary_number\n self.csv_dir_number = csv_dir_number\n\n # 声音参数\n self.sr = sr\n self.n_fft = n_fft\n self.frame_shift = frame_shift\n self.frame_length = frame_length\n self.hop_length = hop_length\n self.win_length = win_length\n self.n_mels = n_mels\n self.power = power\n self.n_iter = n_iter\n self.preemphasis = preemphasis\n self.max_db = max_db\n self.ref_db = ref_db\n self.top_db = top_db\n\n # 其他\n self.batch_size = batch_size\n self.test_batch_size = test_batch_size\n self.max_to_keep = max_to_keep\n","sub_path":"hlp/tts/tacotron2/config2.py","file_name":"config2.py","file_ext":"py","file_size_in_byte":4984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"172912426","text":"class Node():\n def __init__(self,data):\n self.data = data\n self.next = next\n\nclass myQueue():\n def __init__(self,head = None,tail = None):\n self.head = head\n self.tail = tail\n \n def enqueue(self,data):\n node = Node(data)\n self.head, node.next = node, self.head\n def dequeue(self):\n pos = self.head\n while pos.next!=None:\n prev_pos = pos\n pos = pos.next\n prev_pos.next = None\n return pos.data\n \n def printQueue(self):\n if self.head == None: return\n cur_pos = self.head\n l = []\n while cur_pos.next != None:\n l.append(cur_pos.data)\n cur_pos = cur_pos.next\n l.append(cur_pos.data)\n return l\nq = myQueue()\nq.enqueue(2)\nq.enqueue(4)\nq.enqueue(6)\nprint(q.printQueue())\nprint(q.dequeue())\nprint(q.printQueue())\n","sub_path":"03_queues.py","file_name":"03_queues.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"55362352","text":"import json\n\nfrom digs.raaka_bed.decoder import Decoder\nfrom tools import format as FORM\n\n\n# Nothing in the code ... best we can do is make lists here\nOBJECT_SHORT_NAMES = {\n \n 0x01 : 'BOTTLE', # Word is not in CoCo version \n 0x02 : 'POTION',\n 0x03 : 'RUG',\n 0x04 : 'DOOR_RUG',\n 0x05 : 'FOOD',\n 0x06 : 'STATUE_FACING_EAST',\n 0x07 : 'STATUE_FACING_WEST',\n 0x08 : 'RING',\n 0x09 : 'SWORD',\n 0x0A : 'GARGOYLE_STONE',\n 0x0B : 'ALTAR_STAINED',\n 0x0C : 'IDOL',\n 0x0D : 'GATE',\n 0x0E : 'LEVER_UNPULLED',\n 0x0F : 'LEVER_PULLED',\n \n 0x10 : 'PLAQUE_LEVER',\n 0x11 : 'CANDLE_UNLIT',\n 0x12 : 'CANDLE_LIT',\n 0x13 : 'PLAQUE_TUNNEL',\n 0x14 : 'LAMP_LIT',\n 0x15 : 'SERPENT_LIVE',\n 0x16 : 'SERPENT_DEAD',\n 0x17 : 'HANDS',\n 0x18 : 'COIN',\n 0x19 : 'SLOT',\n 0x1A : 'PLAQUE_SLOT',\n 0x1B : 'DOOR_CLOSED',\n 0x1C : 'DOOR_OPEN',\n 0x1D : 'PLAYER',\n 0x1E : 'GARGOYLE_LIVE',\n 0x1F : 'GARGOYLE_DEAD',\n \n 0x20 : 'WALL',\n 0x21 : 'VINE',\n 0x22 : 'CHOPSTICK',\n 0x23 : 'GUARD',\n 0x24 : 'GUARD_REPORTER',\n 0x25 : 'GEM_MOVER',\n 0x26 : 'GEM_TREASURE',\n 0x27 : 'ROOM',\n 0x28 : 'LAMP_UNLIT',\n 0x29 : 'FLOOR',\n 0x2A : 'EXIT',\n 0x2B : 'PASSAGE',\n 0x2C : 'HOLE',\n 0x2D : 'CORRIDOR',\n 0x2E : 'CORNER',\n 0x2F : 'BOW',\n \n 0x30 : 'ARROW',\n 0x31 : 'HALLWAY',\n 0x32 : 'CHAMBER',\n 0x33 : 'VAULT',\n 0x34 : 'ENTRANCE',\n 0x35 : 'TUNNEL',\n 0x36 : 'JUNGLE',\n 0x37 : 'TEMPLE',\n 0x38 : 'SERPENTS',\n 0x39 : 'PIT',\n 0x3A : 'CEILING',\n 0x3B : 'ALTAR_UNDER',\n 0x3C : 'AMBIENT_SOUNDS', \n \n 0xFF : '??255',\n}\n\nchkr = []\nfor k in OBJECT_SHORT_NAMES:\n if OBJECT_SHORT_NAMES[k] in chkr:\n raise Exception('DUPLICATE '+OBJECT_SHORT_NAMES[k])\n chkr.append(OBJECT_SHORT_NAMES[k])\n\nROOM_SHORT_NAMES = {\n 0x00 : 'NOWHERE',\n 0xFF : 'EVERYWHERE',\n 0x81 : 'Small room granite walls',\n 0x82 : 'Oriental rug',\n 0x83 : 'Dark passage',\n 0x84 : 'Top of a passage',\n 0x85 : 'T-shaped room 1',\n 0x86 : 'Gray stone walls 1',\n 0x87 : 'Round room high walls 1',\n 0x88 : 'Triangular room',\n 0x89 : 'South end central hall',\n 0x8A : 'T-shaped room 2',\n 0x8B : 'Grey stone walls 2', # Not the 'GRAY stone walls'\n 0x8C : 'Round room high walls 2',\n 0x8D : 'Petite chamber',\n 0x8E : 'Smells of decaying flesh',\n 0x8F : 'Tall room',\n 0x90 : 'North end central hall',\n 0x91 : 'Vault',\n 0x92 : 'Entrance long dark tunnel west',\n 0x93 : 'Dark tunnel',\n 0x94 : 'Entrance long dark tunnel east',\n 0x95 : 'Large room',\n 0x96 : 'Dense dark damp jungle',\n 0x97 : 'Dark dense damp jungle',\n 0x98 : 'See east wall',\n 0x99 : 'Stands south wall',\n 0x9A : 'See bronze gates',\n 0x9B : 'See north wall',\n 0x9C : 'Standing west entrance',\n 0x9D : 'At north wall',\n 0x9E : 'At east wall',\n 0x9F : 'At south wall',\n 0xA0 : 'Very small room',\n 0xA1 : 'Small room',\n 0xA2 : 'Dark damp dense jungle',\n 0xA3 : 'Dense damp dark jungle',\n 0xA4 : 'Damp dark dense jungle',\n 0xA5 : 'Secret passage',\n 0xA6 : 'End of the passage',\n}\n\nHELPER_SHORT_NAMES = {\n 0x81: 'ResetGame',\n 0x82: 'DeathByStatue',\n 0x83: 'Manipulate',\n 0x84: 'PrintPeriod',\n 0x85: 'PrintGuardsMarchRight',\n 0x86: 'PrintGuardsAroundCorner',\n 0x87: 'PrintGuardsDisappearLeft', \n 0x88: 'PrintTheNOUNIsNotBurning', \n 0x89: 'PrintCantJumpThatFar',\n 0x8A: 'DeathByRugSpike',\n 0x8B: 'DeathByHiddenRugSpike',\n 0x8C: 'PrintDiscoverPit',\n 0x8D: 'PrintStatueTooHeavy',\n 0x8E: 'PrintMoveAlter',\n 0x8F: 'EnterSecretPassage',\n 0x90: 'PrinteAlterMovesBack',\n 0x91: 'SealUpHole',\n 0x92: 'PrintScore',\n 0x93: 'InvalidClimbInOrOut',\n 0x94: 'PrintUseDirections',\n 0x95: 'ResetDungeon',\n 0x96: 'PrintGoodWayToLoseHand',\n 0x97: 'PrintMouthImGame',\n 0x98: 'PrintGiantLeapForYou' \n}\n \nINFO_TRS80 = {\n 'binfile' : '../../../content/TRS80/RaakaTu/RAAKA.bin',\n 'codefile' : '../../../content/TRS80/RaakaTu/Code.md',\n 'origin' : 0x4300,\n 'word_data' : 0x52C2,\n 'phrase_data' : 0x50B9,\n 'object_data' : 0x5651,\n 'general_commands_data' : 0x73FB,\n 'helper_commands_data' : 0x7BCD,\n 'room_descriptions_data' : 0x681F,\n 'command_table': 0x5066,\n}\n\nINFO_COCO = {\n 'binfile' : '../../../content/CoCo/RaakaTu/RaakaTu.bin',\n 'codefile' : '../../../content/CoCo/RaakaTu/Code.md',\n 'origin' : 0x0600,\n 'word_data' : 0x3C29,\n 'phrase_data' : 0x135B,\n 'command_table': 0x12E5,\n \n 'object_data' : 0x20FF, \n 'general_commands_data' : 0x323C,\n 'helper_commands_data' : 0x37FA,\n 'room_descriptions_data' : 0x1523, # same for coco/trs80 \n}\n\ncoco = Decoder(INFO_COCO,OBJECT_SHORT_NAMES,ROOM_SHORT_NAMES,HELPER_SHORT_NAMES)\ntrs80 = Decoder(INFO_TRS80,OBJECT_SHORT_NAMES,ROOM_SHORT_NAMES,HELPER_SHORT_NAMES)\n\ndef make_original_json(plat,name_tag):\n with open('rooms_raaka_'+name_tag+'.json','w') as f:\n js = plat.tojson_room_descriptions()\n js = json.dumps(js,indent=2)\n f.write(js)\n with open('objects_raaka_'+name_tag+'.json','w') as f:\n js = plat.tojson_objects()\n js = json.dumps(js,indent=2)\n f.write(js) \n with open('general_raaka_'+name_tag+'.json','w') as f:\n js = plat.tojson_general()\n js = json.dumps(js,indent=2)\n f.write(js) \n with open('helper_raakas_'+name_tag+'.json','w') as f:\n js = plat.tojson_helpers()\n js = json.dumps(js,indent=2)\n f.write(js) \n with open('words_raaka_'+name_tag+'.json','w') as f:\n js = plat.tojson_words()\n js = json.dumps(js,indent=2)\n f.write(js)\n with open('phrases_raaka_'+name_tag+'.json','w') as f:\n js = plat.tojson_phrases()\n js = json.dumps(js,indent=2)\n f.write(js)\n \nmake_original_json(trs80,'trs80')\n\n\"\"\"\nplat = coco\nout = []\nplat.print_general_commands(out)\nplat.merge_into(out)\nout = []\nplat.print_helper_commands(out)\nplat.merge_into(out)\nout = []\nplat.print_room_descriptions(out)\nplat.merge_into(out)\nout = []\nplat.print_object_data(out)\nplat.merge_into(out)\nout = []\nplat.print_words(out)\nplat.merge_into(out)\nout = []\nplat.print_phrases(out)\nplat.merge_into(out)\n\nplat.fix_command_names()\n\nplat = trs80\nout = []\nplat.print_general_commands(out)\nplat.merge_into(out)\nout = []\nplat.print_helper_commands(out)\nplat.merge_into(out)\nout = []\nplat.print_room_descriptions(out)\nplat.merge_into(out)\nout = []\nplat.print_object_data(out)\nplat.merge_into(out)\nout = []\nplat.print_words(out)\nplat.merge_into(out)\nout = []\nplat.print_phrases(out)\nplat.merge_into(out)\n\nplat.fix_command_names()\n\nwith open('rooms_raaka_trs80.json','w') as f:\n js = plat.tojson_room_descriptions()\n js = json.dumps(js,indent=2)\n f.write(js)\nwith open('objects_raaka_trs80.json','w') as f:\n js = plat.tojson_objects()\n js = json.dumps(js,indent=2)\n f.write(js) \nwith open('general_raaka_trs80.json','w') as f:\n js = plat.tojson_general()\n js = json.dumps(js,indent=2)\n f.write(js) \nwith open('helper_raakas_trs80.json','w') as f:\n js = plat.tojson_helpers()\n js = json.dumps(js,indent=2)\n f.write(js) \nwith open('words_raaka_trs80.json','w') as f:\n js = plat.tojson_words()\n js = json.dumps(js,indent=2)\n f.write(js)\nwith open('phrases_raaka_trs80.json','w') as f:\n js = plat.tojson_phrases()\n js = json.dumps(js,indent=2)\n f.write(js)\n\"\"\"\n \n\"\"\"\nin_trs80 = []\nfor t in trs80._words:\n for w in trs80._words[t]:\n in_trs80.append(FORM.shex2(w['num'])+' '+w['text'])\n \nin_coco = []\nfor t in coco._words:\n for w in coco._words[t]:\n in_coco.append(FORM.shex2(w['num'])+' '+w['text'])\n\"\"\"\n\n\"\"\"\nin_trs80 = []\nfor ph in trs80._phrases:\n in_trs80.append(trs80.phrase_to_string(ph,True))\n \nin_coco = []\nfor ph in coco._phrases:\n in_coco.append(coco.phrase_to_string(ph,True)) \n\"\"\"\n\n\"\"\"\nin_coco=[]\nobs = coco.tojson_objects(False)\nfor o in obs:\n in_coco.append(str(o))\n \nin_trs80=[]\nobs = trs80.tojson_objects(False)\nfor o in obs:\n in_trs80.append(str(o))\n \n\nprint('In CoCo but not TRS80')\nfor i in in_coco:\n if not i in in_trs80:\n print(i)\n \nprint('In TRS80 but not CoCo')\nfor i in in_trs80:\n if not i in in_coco:\n print(i)\n\"\"\"","sub_path":"computerarcheology/digs/raaka_bed/decode_raakatu_data.py","file_name":"decode_raakatu_data.py","file_ext":"py","file_size_in_byte":8345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"336192729","text":"# import paho.mqtt.client as mqtt\r\nimport json\r\nimport time\r\nimport os\r\n\r\nfrom helper import get_logger\r\n\r\n\r\nclass MqttClient:\r\n \"\"\"\r\n It deals with MQTT Broker directly.\r\n \"\"\"\r\n def __init__(self, client_mqtt):\r\n self.mqtt_client = client_mqtt\r\n self._connection_ok = False \r\n self._pub_result = False\r\n self._sub_result = False\r\n self._sub_msgs = []\r\n self._qos = 0\r\n\r\n self.logger = get_logger(name=__name__, _type=\"mqtt\")\r\n\r\n def on_connect(self, client, userdata, flags, rc):\r\n if rc != 0:\r\n raise RuntimeError(\"MQTT Broker connection failed.\")\r\n else:\r\n self._connection_ok = True\r\n \r\n def on_disconnect(self, client, userdata, flags):\r\n self.mqtt_client.loop_stop()\r\n self._connection_ok = False\r\n\r\n def on_log(self, client, userdata, level, buf): \r\n self.logger.debug(\"Client: %s -- %s\" % client, buf)\r\n\r\n def on_publish(self, client, userdata, mid):\r\n self._pub_result = True\r\n \r\n def on_subscribe(self, client, userdata, mid, granted_qos):\r\n self._sub_result = True\r\n self.logger(\"Ready to receive Signal\")\r\n\r\n def on_message(self, client, userdata, message):\r\n logger = get_logger(_type=\"cloud_rx\", name=__name__)\r\n time.sleep(0.1)\r\n logger.info(\"Signal Received.\")\r\n self._sub_msgs.append(str(message.payload))\r\n \r\n from cloud import SignalReception\r\n SignalReception().process_signal(message.payload)\r\n \r\n logger.info(\"Signal Processed Successfully\")\r\n\r\n def get_connection_details(self):\r\n try:\r\n path = \"/opt/app/arduino_app/CutiePi/\"\r\n with open(os.path.join(path, 'config/mqtt_config.json'), \"r\") as config_file:\r\n connection = json.load(config_file)\r\n self._qos = int(connection[\"qos\"])\r\n return connection\r\n except Exception as e:\r\n self.logger.exception(\"Error in getting Broker details\")\r\n raise RuntimeError(\"Could not get Broker details.\") \r\n \r\n def connect_target(self):\r\n \"\"\"\r\n Connects to MQTT broker and returns a MQTT Client object.\r\n \"\"\"\r\n\r\n connection_details = self.get_connection_details()\r\n\r\n self.mqtt_client.username_pw_set(connection_details['USERNAME'], connection_details['PASSWORD'])\r\n\r\n self.mqtt_client.on_connect = self.on_connect\r\n self.mqtt_client.on_disconnect = self.on_disconnect\r\n self.mqtt_client.on_publish = self.on_publish\r\n self.mqtt_client.on_subscribe = self.on_subscribe\r\n self.mqtt_client.on_message = self.on_message\r\n self.mqtt_client.on_log = self.on_log\r\n \r\n try:\r\n self.mqtt_client.connect(\r\n connection_details['HOST'],\r\n connection_details['PORT'],\r\n connection_details['keepalive'])\r\n except Exception as e: \r\n # del self.mqtt_client\r\n self.logger.exception(\"Error in connection...!!!\")\r\n raise RuntimeError(\"MQTT Broker connection failed.\")\r\n \r\n time.sleep(0.2)\r\n\r\n def transmit_signal(self, topic, message):\r\n self.connect_target()\r\n \r\n self.mqtt_client.loop_start()\r\n time.sleep(0.5)\r\n self.mqtt_client.publish(topic=topic, payload=str(message), qos=self._qos)\r\n time.sleep(0.1)\r\n self.logger.info(\"Signal transmitted successfully.\")\r\n \r\n if self._connection_ok or self._pub_result:\r\n self.disconnect_from_broker()\r\n\r\n def receive_signal(self, channel):\r\n self.connect_target()\r\n try:\r\n self.mqtt_client.subscribe(channel, qos=self._qos)\r\n except:\r\n self.logger.exception(\"Error in Recieving Signal\")\r\n raise RuntimeError(\"Unable to receive from channel: \", channel)\r\n\r\n self.mqtt_client.loop_forever()\r\n\r\n def disconnect_from_broker(self):\r\n self.mqtt_client.disconnect()\r\n time.sleep(0.1)\r\n","sub_path":"libraries/mqtt_engine.py","file_name":"mqtt_engine.py","file_ext":"py","file_size_in_byte":4090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"496517411","text":"def citanjeIzFajla(_file, _separator):\n final_list = []\n temp_list = []\n file = open(_file, \"r\")\n separator = _separator\n lines = file.readlines()\n for line in lines:\n temp_list = line.strip(\"\\n\").split(separator)\n final_list.append(temp_list)\n\n file.close()\n return final_list\n\nif __name__ == \"__main__\":\n print(citanjeIzFajla(\"korisnici.txt\",\"|\"))\n\n","sub_path":"vezba5/zadatak3.py","file_name":"zadatak3.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"26877307","text":"def sequentialSearch(myList, item):\n count = 0\n found = False\n\n while count < len(myList) and not found:\n if myList[count] == item:\n found = True\n else:\n count = count+1\n return found\n\ntestlist=[1,2,32,8,17,19,42,13,0]\nprint(sequentialSearch(testlist, 3))\nprint(sequentialSearch(testlist, 13))\n\ndef orderedSequentialSearch(myList,item):\n count = 0\n found = False\n stop = False\n while count < len(myList) and not found and not stop:\n if myList[count] == item:\n found = True\n else:\n if myList[count] > item:\n stop = True\n else:\n count = count+1\n return found\n\ntestlist = [0,1,2,8,13,17,19,32,42]\nint(orderedSequentialSearch(testlist, 3))","sub_path":"Python/sequentialSearch.py","file_name":"sequentialSearch.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"414948258","text":"import unittest\n\n\nclass Solution:\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n return any(i == target for row in matrix for i in row)\n\n\nclass Test(unittest.TestCase):\n def test(self):\n matrix = [\n [1, 4, 7, 11, 15],\n [2, 5, 8, 12, 19],\n [3, 6, 9, 16, 22],\n [10, 13, 14, 17, 24],\n [18, 21, 23, 26, 30]\n ]\n self._test(matrix, 5, True)\n self._test(matrix, 20, False)\n\n def _test(self, matrix, target, expected):\n actual = Solution().searchMatrix(matrix, target)\n self.assertEqual(expected, actual)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"problems/test_0240_bruteforce.py","file_name":"test_0240_bruteforce.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"278933261","text":"import asyncio\nimport sys\n\n# cette constante est utile pour déclarer qu'on a l'intention\n# de lire les sorties (stout et stderr)\n# de nos sous-process par l'intermédiaire de pipes\nfrom subprocess import PIPE\n\nclass Scheduler:\n\n def __init__(self, script, fut):\n\n #future object\n self.fut = fut\n # on trie le script par ordre chronologique\n self.script = list(script)\n self.script.sort(key = lambda time_predef : time_predef[0])\n\n # juste pour donner un numéro à chaque processus\n self.counter = 1\n # combien de processus sont actifs\n self.running = 0\n # nombre de processus à executer et nombre de processus terminés\n self.to_be_run = len(script)\n self.finished = 0\n\n\n async def run(self):\n \"\"\"\n fait tout le travail, c'est-à-dire :\n * lance tous les sous-processus à l'heure indiquée\n * et aussi en préambule, pour le mode avec clavier,\n arme une callback sur l'entrée standard\n \"\"\"\n # pour le mode avec clavier (pas fonctionnel dans le notebook)\n # on arme une callback sur stdin\n asyncio.get_running_loop().add_reader(\n # il nous faut un file descriptor, pas un objet Python\n sys.stdin.fileno(),\n # la callback\n Scheduler.read_keyboard_line,\n # les arguments de la callback\n # cette fois c'est un objet Python\n self, sys.stdin\n )\n \n # le scénario prédéfini\n epoch = 0\n for tick, predef in self.script:\n # attendre le bon moment\n await asyncio.sleep(tick - epoch)\n # pour le prochain\n epoch = tick\n asyncio.ensure_future(self.fork_players(predef))\n\n\n async def fork_players(self, predef):\n \"\"\"\n lance maintenant une instance de players.py avec cette config\n\n puis\n écoute à la fois sdtout et stderr, et les imprime\n (bon c'est vrai que players n'écrit rien sur stderr)\n attend la fin du sous-processus (avec wait())\n et retourne son code de retour (exitcode) du sous-processus\n\n par commodité on décide d'arrêter la boucle principale\n lorsqu'il n'y a plus aucun process actif\n \"\"\"\n\n # la commande à lancer pour forker une instance de players.py\n # l'option python -u sert à désactiver le buffering sur stdout\n command = f\"python3 -u players.py {predef}\".split()\n \n # pour afficher un nom un peu plus parlant\n worker = f\"ps#{self.counter} (predef {predef})\"\n\n # housekeeping\n self.counter += 1\n self.running += 1\n\n # c'est là que ça se passe : on forke\n print(8 * '>', f\"worker {worker}\")\n process = await asyncio.create_subprocess_exec(\n *command,\n stdout=PIPE, stderr=PIPE,\n )\n # et on lit et écrit les canaux du sous-process\n stdout, stderr = await asyncio.gather(\n self.read_and_display(process.stdout, worker),\n self.read_and_display(process.stderr, worker))\n # qu'il ne faut pas oublier d'attendre pour que l'OS sache\n # qu'il peut nettoyer\n retcod = await process.wait()\n \n # le process est terminé\n self.running -= 1\n self.finished += 1\n print(8 * '<', f\"worker {worker} - exit code {retcod}\"\n f\" - {self.running} still running\")\n \n # si c'était le dernier on sort de la boucle principale\n # if self.running == 0:\n # Plus de processus en cours d'execution ET tous les processus executés\n if self.running == 0 and self.finished == self.to_be_run:\n print(\"no process left - bye\")\n # On donne un résultat à l'objet pour le set à done\n self.fut.set_result(\"end\")\n # sinon on retourne le code de retour\n return retcod\n\n\n async def read_and_display(self, stream, worker):\n \"\"\"\n une coroutine pour afficher les sorties d'un canal\n stdout ou stderr d'un sous-process\n elle retourne lorsque le processus est terminé\n \"\"\"\n while True:\n bytes = await stream.readline()\n # l'OS nous signale qu'on en a terminé\n # avec ce process en renvoyant ici un objet bytes vide\n if not bytes:\n break\n \n # bien qu'ici players n'écrit que de l'ASCII\n # readline() nous renvoie un objet `bytes`\n # qu'il faut convertir en str \n line = bytes.decode().strip()\n print(8 * ' ', f\"got `{line}` from {worker}\")\n\n\n # ceci est seulement fonctionnel si vous exécutez\n # le programme localement sur votre ordinateur\n # car depuis un notebook le clavier est intercepté\n # par le serveur web\n def read_keyboard_line(self, stdin):\n \"\"\"\n ceci est une callback; eh oui :)\n c'est pourquoi d'ailleurs ce n'est pas une coroutine\n cependant on est sûr qu'elle n'est appelée\n que lorsqu'il y a réellement quelque chose à lire\n \"\"\"\n line = stdin.readline().strip()\n # ici je triche complètement\n # lorsqu'on est dans un notebook, pour bien faire\n # on ne devrait pas regarder stdin du tout\n # mais pour garder le code le plus simple possible\n # je choisis d'ignorer les lignes vides ici\n # comme ça mon code marche dans les deux cas\n if not line:\n return\n # on traduit la ligne tapée au clavier\n # en un entier entre 1 et 4\n try:\n predef = int(line)\n if not (1 <= predef <= 4):\n raise ValueError('entre 1 et 4')\n except Exception as e:\n print(f\"{line} doit être entre 1 et 4 {type(e)} - {e}\")\n return\n asyncio.ensure_future(self.fork_players(predef))\n # Un nouveau processus à executer\n self.to_be_run += 1\n\nclass Clock:\n\n def __init__(self, fut):\n self.clock_seconds = 0\n self.fut = fut\n\n async def run(self):\n while not self.fut.done():\n print(f\"clock = {self.clock_seconds:04d}s\")\n await asyncio.sleep(1)\n self.clock_seconds += 1\n\n\nclass Game:\n\n def __init__(self, script):\n self.script = script\n\n async def mainloop(self):\n loop = asyncio.get_running_loop()\n fut = loop.create_future()\n\n # on met ensemble une clock et un scheduler\n clock = Clock(fut)\n scheduler = Scheduler(self.script, fut)\n\n # et on fait tourner le tout\n asyncio.ensure_future(clock.run())\n asyncio.ensure_future(scheduler.run())\n await fut\n\n# nous allons juxtaposer 3 instances de players.py\n# et donc avoir 6 joueurs dans le jeu\n# La dernière instance se déroulera alors que les 2 premières sont terminées\ngame = Game( [(0.5, 1), (1., 2), (6., 3)])\n\n# si vous êtes dans un notebook\n# await game.mainloop()\nasyncio.run(game.mainloop())\n","sub_path":"games.py","file_name":"games.py","file_ext":"py","file_size_in_byte":7060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"444524231","text":"from tkinter import *\nimport sqlite3 as sq\nfrom tkinter import ttk\nimport books as books\nimport datetime\n\nclass Rental():\n def __init__(self, master):\n\n ####### Master #############\n self.rent_master=master\n style = ttk.Style()\n style.configure(\"Treeview.Heading\", font=(None, 10))\n\n self.mainFrame=_mainFrame(self.rent_master, row=0, column=0)\n self.message=_message(self.mainFrame.frame, row=1, column=0)\n self.rentFrame=_rentFrame(self.mainFrame.frame, row=2, column=0)\n self.searchFrame=_searchFrame(self.mainFrame.frame, self.message, self.rentFrame, row=0, column=0)\n self.menuFrame =_menuFrame(self.rent_master, self.searchFrame, row=0, column=1, sticky=NS)\n\nclass _mainFrame():\n def __init__(self, parent, *args, **kwargs):\n self.frame=Frame(parent)\n print(kwargs['row'])\n self.frame.grid(row=kwargs['row'], column=kwargs['column'], padx=3)\n\nclass _message():\n def __init__(self, parent, *args, **kwargs):\n self.frame=Frame(parent)\n self.frame.grid(row=kwargs['row'], column=kwargs['column'], pady=10, sticky=W, padx=10)\n\n self.status_message=Label(self.frame, text='', fg='red', width=15)\n self.status_message.grid(row=0, column=0)\n\n self.member_info=Frame(self.frame)\n self.member_info.grid(row=0, column=1)\n\n Label(self.member_info, text='이름:', fg='blue').grid(row=0, column=0, sticky=W, padx=10 )\n self.name=Label(self.member_info, text='', fg='blue')\n self.name.grid(row=0, column=1, sticky=W, padx=10 )\n\n Label(self.member_info, text='휴대폰:', fg='blue').grid(row=1, column=0, sticky=W, padx=10 )\n self.phone=Label(self.member_info, text='', fg='blue')\n self.phone.grid(row=1, column=1, sticky=W, padx=10 )\n\n Label(self.member_info, text='주소:', fg='blue').grid(row=2, column=0, sticky=W, padx=10 )\n self.address=Label(self.member_info, text='', fg='blue')\n self.address.grid(row=2, column=1, sticky=W, padx=10 )\n\n def update_status_info(self, message):\n self.status_message['text']=message\n\n def update_member_info(self, row):\n self.name['text']=row[1]\n self.phone['text']=row[2]\n self.address['text']=row[3]\n\nclass _rentFrame():\n def __init__(self, parent, *args, **kwargs):\n ############# Tree ###################\n self.tree = ttk.Treeview(parent, height=15, column=('rent_date', 'title', 'vol', 'genre', 'author', 'days'),\n show='headings', selectmode=\"browse\")\n self.tree.grid(row=kwargs['row'], column=kwargs['column'], pady=10)\n\n # scrollbar\n ysb = ttk.Scrollbar(parent, orient='vertical', command=self.tree.yview)\n ysb.grid(row=2, column=1, sticky='ns', pady=10)\n self.tree.configure(yscroll=ysb.set)\n\n self.tree.heading('#1', text='대여일')\n self.tree.heading('#2', text='제목')\n self.tree.heading('#3', text='권')\n self.tree.heading('#4', text='장르')\n self.tree.heading('#5', text='저자')\n self.tree.heading('#6', text='경과일')\n\n self.tree.column('rent_date', width=150, anchor=CENTER)\n self.tree.column('title', width=170, anchor=CENTER)\n self.tree.column('vol', width=40, anchor=CENTER)\n self.tree.column('genre', width=40, anchor=CENTER)\n self.tree.column('author', width=40, anchor=CENTER)\n self.tree.column('days', width=50, anchor=CENTER)\n #####################################\n\n def update_rent_info(self, member_id):\n con = sq.connect('guelbang.db')\n c = con.cursor()\n query = 'SELECT RentDate, Title, Vol, Genre, AUthor FROM RENT join BOOK on BOOK.Id=RENT.BookId where MemberId=?'\n parameters = (member_id,)\n c.execute(query, parameters)\n\n rows = c.fetchall()\n for row in rows:\n delta = datetime.datetime.now() - datetime.datetime.strptime(row[0], \"%Y-%m-%d %H:%M:%S\")\n row=row + (delta.days,)\n self.tree.insert(\"\", END, values=row)\n\n c.close()\n\n def clear_rent_info(self):\n self.tree.delete(*self.tree.get_children())\n\nclass _searchFrame():\n def __init__(self, parent, message, tree, *args, **kwargs):\n\n # setting Frame\n self.searchFrame = Frame(parent)\n self.searchFrame.grid(row=kwargs['row'], column=kwargs['column'], sticky=W)\n # search bar\n self.searchMember = Entry(self.searchFrame, width=20)\n self.searchMember.grid(row=0, column=0, padx=10, sticky=W)\n # connected Frame\n self.message=message\n self.tree=tree\n # button\n Button(self.searchFrame, text='검색', command= lambda:self.search_members(self.searchMember.get())).grid(row=0,column=1)\n\n def search_validation(self, parameters):\n return len(parameters)!=0\n\n def search_members(self, parameters):\n if self.search_validation(parameters):\n\n member_row=self.search_query_return(parameters)\n\n if len(member_row)==0:\n self.message.update_status_info('검색결과가 없습니다')\n\n elif len(member_row)==1:\n self.message.update_member_info(member_row[0])\n self.tree.clear_rent_info()\n self.selected_id=member_row[0][0]\n self.tree.update_rent_info(self.selected_id)\n\n else:\n self.popup=PopupMember(self.searchFrame, self.message, self.tree, member_row)\n\n\n else:\n self.message.update_status_info('글자를 입력하세요')\n\n def search_query_return(self, parameters):\n con = sq.connect('guelbang.db')\n c = con.cursor()\n query = 'select Id, Name,Phone,Address from MEMBER where Name like ?'\n c.execute(query, ('%{}%'.format(parameters),))\n rows=c.fetchall()\n c.close()\n return rows\n\nclass PopupMember():\n def __init__(self, parent, message, tree, fetch_rows):\n\n self.parent=parent\n ## popup new window\n self.win_master =Toplevel(parent)\n\n # connected widget\n self.message=message\n self.rentFrame=tree\n\n # determine popup position\n x_axis = parent.winfo_x()\n y_axis = parent.winfo_y()\n self.win_master.geometry('+{}+{}'.format(x_axis + 600, y_axis + 400))\n\n # generate Frame within windows\n self.mainFrame = Frame(self.win_master)\n self.mainFrame.grid(row=0, column=0)\n\n # generate treeviews\n self.tree = ttk.Treeview(self.mainFrame, height=5, column=('no','name','mobile','address'),show='headings', selectmode='browse')\n self.tree.grid(row=0, column=0)\n\n self.tree.heading('#1', text='번호')\n self.tree.heading('#2', text='이름')\n self.tree.heading('#3', text='핸드폰')\n self.tree.heading('#4', text='주소')\n\n self.tree.column('no',width=40, anchor=CENTER)\n self.tree.column('name',width=80, anchor=CENTER)\n self.tree.column('mobile', width=120, anchor=CENTER)\n self.tree.column('address', width=200, anchor=CENTER)\n\n for row in fetch_rows:\n self.tree.insert(\"\",END,values=row)\n\n # button\n Button(self.mainFrame, text='선택', command=self.proceed).grid(row=1, column=0)\n\n def proceed(self):\n self.selected_row=tuple(self.tree.item(self.tree.selection())['values'])\n self.message.update_member_info(self.selected_row)\n self.rentFrame.clear_rent_info()\n self.rentFrame.update_rent_info(self.selected_row[0])\n self.parent.selected_id=self.selected_row[0]\n self.win_master.destroy()\n return self.selected_row\n\nclass _menuFrame():\n def __init__(self, parent, searchFrame, *args, **kwargs):\n\n # create Frame\n self.menuFrame=Frame(parent)\n self.menuFrame.grid(row=kwargs['row'],column=kwargs['column'], padx=3, pady=40, sticky=N)\n\n # connected widget\n self.searchFrame=searchFrame\n\n Button(self.menuFrame, text='대여',command=self.pop_add_rent, width=10).grid(row=5, padx=3, pady=10)\n Button(self.menuFrame, text='회수',command=self.return_rent, width=10).grid(row=6, padx=3, pady=10)\n Button(self.menuFrame, text='대여기록',command=self.view_history, width=10).grid(row=7, padx=3, pady=10)\n\n def pop_add_rent(self):\n add_rent(self.menuFrame)\n\n def return_rent(self):\n return\n\n def view_history(self):\n return\n\nclass add_rent():\n def __init__(self,parent,**kwargs):\n\n ## popup new window\n self.win_master = Toplevel(parent)\n\n # generate Frame within windows\n self.mainFrame = Frame(self.win_master)\n self.mainFrame.grid(row=0, column=0,padx=10, pady=5)\n\n # generate Entry\n self.entryFrame = Frame(self.mainFrame)\n self.entryFrame.grid(row=0, column=0)\n\n Label(self.entryFrame, text='도서검색: ').grid(row=0, column=0, pady=5)\n self.entry=Entry(self.entryFrame, width=20)\n self.entry.grid(row=0,column=1)\n Button(self.entryFrame, text='검색', command=self.button_pressed).grid(row=0, column=2, padx=5)\n Button(self.entryFrame, text='대여목록추가', command=self.add_pressed).grid(row=0, column=3, padx=5)\n\n # generate treeviews\n self.tree = ttk.Treeview(self.mainFrame, height=20, column=('id','title','vol','genre','author'),show='headings')\n self.tree.grid(row=1, column=0)\n\n self.tree.heading('#1', text='Id')\n self.tree.heading('#2', text='제목')\n self.tree.heading('#3', text='권')\n self.tree.heading('#4', text='장르')\n self.tree.heading('#5', text='저자')\n\n self.tree.column('id',width=40, anchor=CENTER)\n self.tree.column('title',width=200, anchor=CENTER)\n self.tree.column('vol',width=40, anchor=CENTER)\n self.tree.column('genre', width=80, anchor=CENTER)\n self.tree.column('author', width=80, anchor=CENTER)\n\n def button_pressed(self):\n self.keyword=self.entry.get()\n self.get_query_result()\n self.update_tree()\n\n def get_query_result(self):\n con=sq.connect('guelbang.db')\n c=con.cursor()\n query='SELECT Id, Title, Vol, Genre, Author FROM BOOK WHERE Title like ?'\n c.execute(query, ('%{}%'.format(self.keyword),))\n self.rows=c.fetchall()\n c.close()\n\n def update_tree(self):\n for row in self.rows:\n self.tree.insert(\"\",END,values=row)\n\n def clear_rent_info(self):\n self.tree.delete(*self.tree.get_children())\n\n def add_pressed(self):\n\n params=[]\n for i in self.tree.selection():\n id=self.tree.item(i)['values']\n print(id)\n params.append((id,))\n\n query='INSERT INTO BOOK VALUES ()'\n\n\n\n return\n\n\n\n\ndef main():\n root=Tk()\n myGUIWelcome=Rental(root)\n root.mainloop()\n\nif __name__ == '__main__':\n main()\n","sub_path":"rental.py","file_name":"rental.py","file_ext":"py","file_size_in_byte":10981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"493932258","text":"from PyQt5.QtWidgets import QGridLayout, QWidget, QPushButton, QFileDialog\nfrom PyQt5 import QtCore\n\nfrom gcode_viewer.gcode.layer_parser import Layer_Parser\nfrom gcode_viewer.gui.left_side.left_side import Left_Side\nfrom gcode_viewer.gui.menu_bar.menu_bar import Menu_Bar\nfrom gcode_viewer.gui.right_side.right_side import Right_Side\nfrom gcode_viewer.gui.startup_window.startup_window import Startup_Window\nfrom gcode_viewer.util.file_handler import File_Handler\n\n\nclass Central_Widget(QWidget):\n\n def __init__(self):\n super().__init__()\n\n self.file_handler = File_Handler()\n self.settings = self.file_handler.read_settings()\n\n self.initUI()\n\n def initUI(self):\n\n self.grid = QGridLayout()\n\n self.menu_bar = Menu_Bar(self.settings)\n self.grid.addWidget(self.menu_bar, 0, 0, 1, 2)\n self.menu_bar.observer = self\n\n self.left_side = Left_Side()\n self.grid.addWidget(self.left_side, 1, 0)\n\n self.right_side = Right_Side(self.settings)\n self.grid.addWidget(self.right_side, 1, 1)\n\n bottom_grid = QGridLayout()\n self.grid.addLayout(bottom_grid, 2, 0, 1, 2)\n\n self.load_file_button = QPushButton(\"Load Different GCode File\")\n bottom_grid.addWidget(self.load_file_button, 0, 1)\n self.load_file_button.clicked.connect(self.get_path_to_file)\n\n bottom_grid.setColumnStretch(0, 1)\n bottom_grid.setColumnStretch(2, 1)\n\n self.setLayout(self.grid)\n\n def start(self):\n test = Startup_Window()\n file_path = test.get_initial_file_path()\n\n if file_path:\n self.load_gcode_file(file_path)\n\n def get_path_to_file(self):\n file_path, _ = QFileDialog(self).getOpenFileName(caption=\"Select A GCode File That You Want To Load\",\n filter=\"GCode (*.gcode)\", initialFilter=\"GCode (*.gcode)\")\n\n if file_path:\n self.load_gcode_file(file_path)\n\n def load_gcode_file(self, file_path):\n\n line_list = self.file_handler.read_gcode_file(file_path)\n temp_layer_parser = Layer_Parser()\n layer_list = temp_layer_parser.parse_layer_list(line_list)\n\n self.load_new_file_on_screen(layer_list)\n\n def load_new_file_on_screen(self, layer_list):\n self.right_side.load_new_gcode(layer_list)\n self.right_side.gcode_loaded = True\n\n self.left_side.gcode_3d_viewer.load_gcode(layer_list)\n\n def update(self, type, par1, par2 = None):\n\n if type == \"new_settings\":\n new_settings = par1\n\n self.settings = new_settings\n #self.left_side.settings = new_settings\n self.menu_bar.settings = new_settings\n\n self.file_handler.settings_to_file(self.settings)\n","sub_path":"src/gcode_viewer/gui/central_widget.py","file_name":"central_widget.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"129243279","text":"from random import randint\r\n\r\n# set up variables to keep score and set number of non-tie matches\r\nplayer_wins = 0\r\ncomputer_wins = 0\r\nwinning_score = 5\r\n\r\n# loop to keep game going until winning_score condition is met\r\nwhile player_wins < winning_score and computer_wins < winning_score:\r\n\tprint(f\"Player Score: {player_wins} Computer Score: {computer_wins}\")\r\n\tprint(\"Rock...\")\r\n\tprint(\"Paper...\")\r\n\tprint(\"Scissors...\")\r\n\r\n# sets rock, paper, and scissors as the number equivalents and gives players option to quit early\r\n\tplayer = input(\"What is your move?: \").lower()\r\n\tif player == \"quit\" or player == \"q\":\r\n\t\tbreak\r\n\trandom_int = random.randint(0,2)\r\n\tif random_int == 0:\r\n\t\tcomputer = \"rock\"\r\n\telif random_int == 1:\r\n\t\tcomputer = \"paper\"\r\n\telse:\r\n\t\tcomputer = \"scissors\"\r\n\r\n# indicates what the computer plays so player knows\r\n\tprint(f\"The computer plays: {computer}\")\r\n\r\n\tif player == computer:\r\n\t\tprint(\"You tied!\")\r\n\telif player == \"rock\":\r\n\t\tif computer == \"scissors\":\r\n\t\t\tprint(\"player wins!\")\r\n\t\t\tplayer_wins += 1\r\n\t\telse:\r\n\t\t\tprint(\"computer wins!\")\r\n\t\t\tcomputer_wins += 1\r\n\telif player == \"paper\":\r\n\t\tif computer == \"rock\":\r\n\t\t\tprint(\"player wins!\")\r\n\t\t\tplayer_wins += 1\r\n\t\telse:\r\n\t\t\tprint(\"computer wins!\")\r\n\t\t\tcomputer_wins += 1\r\n\telif player == \"scissors\":\r\n\t\tif computer == \"paper\":\r\n\t\t\tprint(\"player wins!\")\r\n\t\t\tplayer_wins += 1\r\n\t\telse:\r\n\t\t\tprint(\"computer wins!\")\r\n\t\t\tcomputer_wins += 1\r\n\telse:\r\n\t\tprint(\"Somethin ain't right\")\r\n\r\nif player_wins > computer_wins:\r\n\tprint(\"Well done, you won!\")\r\nelif player_wins == computer_wins:\r\n\tprint(\"It's a tie!\")\r\nelse:\r\n\tprint(\"Computer won.\")","sub_path":"RPS_v2.py","file_name":"RPS_v2.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"449082846","text":"\"\"\"\n\nA basic linear classifer example that uses the pyoplot library to help us visualize the data classification.\n\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass points:\n def __init__(self, arr=None, x=None, y=None, category = None):\n self.x = []\n self.y = []\n self.category = category\n if (arr == None and x != None and y != None):\n self.x.append(x)\n self.y.append(y)\n elif (arr == None and x == None and y == None):\n return\n else:\n for pair in arr:\n self.x.append(pair[0])\n self.y.append(pair[1])\n\n def add_cordinate(self, x=None, y=None, arr=None):\n if (x != None and y != None):\n self.x.append(x)\n self.y.append(y)\n elif (arr != None):\n print(\"printing arr\" + format(arr))\n for pair in arr:\n self.x.append(pair[0])\n self.y.append(pair[1])\n\n def isEmpty(self):\n if(len(self.x) == 0):\n return True\n else:\n return False\n\n def print_pairs(self):\n for el in range(0, len(self.x)):\n print(\"x= \" + str(self.x[el]) + \" y = \" + str(self.y[el]))\n\n\ndef calculate_errors(c1, c2, threshold):\n #true positives and true negatives\n tp = 0\n tn = 0\n fp = 0\n fn = 0\n\n for ind in range (0, len(c1.x)):\n #get points from both groups\n x_1 = c1.x[ind]\n y_1 = c1.y[ind]\n \n\n x_2 = c2.x[ind]\n y_2 = c2.y[ind]\n\n print(\"x_1 = \"+str(x_1))\n print(\"threshold x = \"+str(threshold.x[0]))\n\n #test against the threshold\n\n if(x_1 > threshold.x[0] and y_1 > threshold.y[0]):\n category_1 = \"C1\"\n else:\n category_1 = \"C2\"\n \n if(x_2 > threshold.x[0] and y_2 > threshold.y[0]):\n category_2 = \"C1\"\n else:\n category_2 = \"C2\"\n\n if(category_1 == \"C1\"):\n tp += 1\n else:\n fp += 1\n \n if(category_2 == \"C2\"):\n tn += 1\n else:\n fn += 1\n \n result = 100 * ( (float (tn+ tp) ) / (float (tn+tp+fp+fn)) )\n print(\"Accuracy of threshold is... \" + str(result))\n\n#THRESHOLD setting function / General x and y input getting function\ndef get_xy(argument,msg = \"Enter the X and Y Value\"):\n if(argument == \"XY\" or argument == \"xy\"):\n print(msg)\n x = get_xy(\"X\")\n y = get_xy(\"Y\")\n return x, y\n \n if(argument == \"X\" or argument == \"x\"):\n x_in = input(\"\"\"Enter the X value :\\n\"\"\")\n try:\n x_in = float(x_in)\n except:\n print(\"error!\")\n if(isinstance(x_in, int) or isinstance(x_in,float)):\n return float(x_in)\n else:\n return get_xy(\"X\")\n \n if(argument == \"Y\" or argument == \"y\"):\n y_in = input(\"\"\"Enter the Y value : \\n\"\"\")\n try:\n y_in = float(y_in)\n except:\n print(\"error!\")\n if(isinstance(y_in, int) or isinstance(y_in,float)):\n return float(y_in)\n else:\n return get_xy(\"Y\")\n\n\ndef display_graph(group1, group2, threshold, container1, container2):\n plt.xlim([0, 5])\n plt.ylim([0, 5])\n\n plt.plot(group1.x, group1.y, \"ro\", label = group1.category)\n plt.plot(group2.x, group2.y, \"bv\", label = group2.category)\n\n if(container1.isEmpty() == False):\n plt.plot(container1.x, container1.y, \"r*\", label = container1.category)\n if(container2.isEmpty() == False):\n plt.plot(container2.x, container2.y, \"b*\", label = container2.category)\n\n plt.plot(threshold.x[0], threshold.y[0], \"g*\", label = \"threshold\")\n plt.xlabel(\"X\")\n plt.ylabel(\"Y\")\n plt.legend()\n plt.show()\n\n#This function takes a points and categorizes them according to the category passed.\ndef classify (p, threshold, category1, category2):\n categorized_group1 = points()\n categorized_group1.category = category1\n categorized_group2 = points()\n categorized_group2.category = category2\n for i in range(0,len(p.x)):\n if(p.x[i] > threshold.x[0] and p.y[i] > threshold.y[0]):\n categorized_group1.add_cordinate(x = p.x[i], y = p.y[i])\n else:\n categorized_group2.add_cordinate(x = p.x[i], y = p.y[i])\n \n return categorized_group1, categorized_group2\n\n\ndef main():\n\n #Our C1 and C2 coordinate arrays\n C1_test = points({(2, 2), (3, 2), (2, 3)}, category = \"C1\")\n C2_test = points({(1, 2), (1, 1), (2, 1)} , category = \"C2\")\n \n #set threshold\n xth = yth = 0\n threshold = points(x = xth, y = yth)\n exit = False\n user_data_points = points()\n\n while exit == False:\n\n\n main_menu = \"\"\n main_menu += \"MAIN MENU \\n\"\n main_menu += \"\"\"Press \"d\" to display graph (Part a) \\n\"\"\"\n main_menu += \"\"\"Press \"s\" to set the threshold and test it's accuracy (Part b and c) \\n\"\"\"\n main_menu += \"\"\"Press \"n\" to add data points (Part d) \\n\"\"\" \n main_menu += \"\"\"Press \"x\" to exit the program \\n \\n \\n\"\"\" \n\n main_input = input(main_menu)\n\n if(main_input == \"d\"):\n if(not(user_data_points.isEmpty())):\n print(\"Array is not empty\")\n C1_training , C2_training = classify(user_data_points, threshold, \"C1 Detected\", \"C2 Detected\")\n display_graph(C1_test, C2_test, threshold, C1_training , C2_training )\n else:\n C1_training=points()\n C2_training=points()\n display_graph(C1_test, C2_test, threshold, C1_training , C2_training )\n\n if(main_input == \"s\"):\n in_x, in_y = get_xy(\"XY\", \"SET THRESHOLD\")\n threshold.x[0] = in_x\n threshold.y[0] = in_y\n calculate_errors(C1_test, C2_test, threshold)\n\n if(main_input == \"n\"):\n while True:\n in_x, in_y = get_xy( \"XY\", \"Enter Data point\")\n user_data_points.add_cordinate(x = in_x, y = in_y)\n inn = input(\"\"\" To enter another point press \"y\" \\n Else press any other button to exit this menu \"\"\")\n\n if(inn != \"y\"):\n break;\n\n if(main_input == \"x\"):\n break;\n\n\n\nif __name__== \"__main__\":\n main()\n","sub_path":"LS.py","file_name":"LS.py","file_ext":"py","file_size_in_byte":5836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"37904636","text":"class Date:\n __slots__ = [\"year\", \"month\", \"day\"]\n\n def __init__(self, year, month, day):\n self.year = year\n self.month = month\n self.day = day\n\n def __repr__(self):\n return 'year:{d.year}month:{d.month}day:{d.day}'.format(d=self)\n\n\nd = Date(2018, 7, 9)\nprint(d)\n","sub_path":"chapter-8/8.4.py","file_name":"8.4.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"58732775","text":"from datetime import datetime\nimport os\n\ndt = datetime.today().strftime('%y%m%d')\ndirectory = \"D:/MEGA/\"\n\noutfile_name = \"merged_{}.txt\".format(datetime.today().strftime('%y%m%d'))\n\nout_file = open(outfile_name,'w')\nfiles = os.listdir(directory)\n\nfor filename in files:\n if \".txt\" not in filename:\n continue\n file = open(directory+filename)\n for line in file:\n out_file.write(line)\n print(filename)\n\n out_file.write(\"\\n\\n\")\n\n file.close()\nout_file.close()\n\n","sub_path":"python/automation/automation_text.py","file_name":"automation_text.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"398425114","text":"n = int(input())\na = []\nfor _ in range(n):a.append(int(input()))\n\nmax_ = max(a)\nmax2 = sorted(a)[-2]\nfor i in range(n):\n if a[i] != max_:\n print(max_)\n else:\n print(max2)","sub_path":"Python_codes/p02971/s928146171.py","file_name":"s928146171.py","file_ext":"py","file_size_in_byte":190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"545925715","text":"import os\nimport redis\n\n\n# configurationb\nDATABASE = 'dashboard.db'\nDEBUG = True\nSECRET_KEY = 'my_precious'\n\n# grabs the folder where the script runs\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\n# REDIS_HOST = '43.82.163.74'\n# REDIS_PORT = 6379\n# REDIS = redis.Redis(host=REDIS_HOST, port=REDIS_PORT)\n\n# defines the full path for the database\nDATABASE_PATH = os.path.join(basedir, DATABASE)\n\n# database config\nSQLALCHEMY_DATABASE_URI = 'sqlite:///' + DATABASE_PATH\nSQLALCHEMY_TRACK_MODIFICATIONS = False\n\n# celery\nCELERY_BROKER_URL = 'redis://localhost:6379/0'\nCELERY_RESULT_CACKEND = 'redis://localhost:6379/0'","sub_path":"_settings.py","file_name":"_settings.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"224238304","text":"import lightgbm as lgb\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\n\ndef add_community_ave_trademoney(df_origin):\n df_ret = df_origin.copy()\n dict_commnityname_trademoney = {}\n for i in df_ret['communityName'].unique():\n trademoney_ave = df_ret[df_ret['communityName'] == i]['tradeMoney'].mean()\n dict_commnityname_trademoney[i] = trademoney_ave\n list_trademoney_ave = []\n for index, row in df_ret.iterrows():\n communityname = row['communityName']\n trademoney = dict_commnityname_trademoney[communityname]\n list_trademoney_ave.append(trademoney)\n dict_trademoney_final = {'community_ave_trademoney': list_trademoney_ave}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_trademoney_final)], axis=1)\n return df_ret\n\n\ndef add_region_ave_trademoney(df_origin):\n df_ret = df_origin.copy()\n dict_commnityname_trademoney = {}\n for i in df_ret['region'].unique():\n trademoney_ave = df_ret[df_ret['region'] == i]['tradeMoney'].mean()\n dict_commnityname_trademoney[i] = trademoney_ave\n list_trademoney_ave = []\n for index, row in df_ret.iterrows():\n communityname = row['region']\n trademoney = dict_commnityname_trademoney[communityname]\n list_trademoney_ave.append(trademoney)\n dict_trademoney_final = {'region_ave_trademoney': list_trademoney_ave}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_trademoney_final)], axis=1)\n return df_ret\n\n\ndef add_plate_ave_trademoney(df_origin):\n df_ret = df_origin.copy()\n dict_commnityname_trademoney = {}\n for i in df_ret['plate'].unique():\n trademoney_ave = df_ret[df_ret['plate'] == i]['tradeMoney'].mean()\n dict_commnityname_trademoney[i] = trademoney_ave\n list_trademoney_ave = []\n for index, row in df_ret.iterrows():\n communityname = row['plate']\n trademoney = dict_commnityname_trademoney[communityname]\n list_trademoney_ave.append(trademoney)\n dict_trademoney_final = {'plate_ave_trademoney': list_trademoney_ave}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_trademoney_final)], axis=1)\n return df_ret\n\n\ndef add_pv_div_uv(df_origin):\n df_ret = df_origin.copy()\n list_pv_div_uv = []\n for index, row in df_ret.iterrows():\n pv = row['pv']\n uv = row['uv']\n pv_div_uv = float(pv) / float(uv)\n list_pv_div_uv.append(pv_div_uv)\n dict_pv_div_uv = {'pv_div_uv': list_pv_div_uv}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_pv_div_uv)], axis=1)\n return df_ret\n\n\ndef add_month_ave_trademoney(df_origin):\n df_ret = df_origin.copy()\n dict_month_ave_money = {}\n for i in df_ret['tradeMonth'].unique():\n trademoney_ave = df_ret[df_ret['tradeMonth'] == i]['tradeMoney'].mean()\n dict_month_ave_money[i] = trademoney_ave\n list_trademoney_month_ave = []\n for index, row in df_ret.iterrows():\n month = row['tradeMonth']\n trademoney = dict_month_ave_money[month]\n list_trademoney_month_ave.append(trademoney)\n dict_trademoney_final = {'month_ave_trademoney': list_trademoney_month_ave}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_trademoney_final)], axis=1)\n return df_ret\n\n\ndef add_totalfloor_times_housefloor(df_origin):\n df_ret = df_origin.copy()\n list_totalfloor_times_housefloor = []\n for index, row in df_ret.iterrows():\n housefloor = row['houseFloor']\n totalfloor = row['totalFloor']\n if housefloor == 0:\n ratio = 0.5\n elif housefloor == 1:\n ratio = 1.5\n else:\n ratio = 2.5\n list_totalfloor_times_housefloor.append(ratio * totalfloor)\n dict_totalfloor_times_housefloor = {'totalfloor_times_housefloor': list_totalfloor_times_housefloor}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_totalfloor_times_housefloor)], axis=1)\n return df_ret\n\n\ndef add_housetype_to_num(df_origin):\n df_ret = df_origin.copy()\n list_num = []\n for index, row in df_ret.iterrows():\n bedroom = row['bedroom']\n livingroom = row['livingroom']\n bathroom = row['bathroom']\n num = 14 * bedroom + 14 * livingroom + 3 * bathroom\n list_num.append(num)\n dict_num = {'housetype_to_num': list_num}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_num)], axis=1)\n return df_ret\n\n\ndef add_tradeyear_minus_buildyear(df_origin):\n df_ret = df_origin.copy()\n list_year = []\n tradeyear=2018\n list_buildyear = df_ret['buildYear'].tolist()\n for buildyear in list_buildyear:\n list_year.append(tradeyear - buildyear)\n dict_year = {'tradeyear_minus_buildyear': list_year}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_year)], axis=1)\n return df_ret\n\n\ndef add_plate_num_in_region(df_origin):\n df_ret = df_origin.copy()\n dict_plate_num = {}\n list_region = list(df_ret['region'].unique())\n list_plate_num_in_region = []\n for region in list_region:\n plate_num = len(df_ret[df_ret['region'] == region]['plate'].unique())\n dict_plate_num[region] = plate_num\n for index, row in df_ret.iterrows():\n region = row['region']\n plate_num = dict_plate_num[region]\n list_plate_num_in_region.append(plate_num)\n dict_plate_num_in_region = {'plate_num_in_region': list_plate_num_in_region}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_plate_num_in_region)], axis=1)\n return df_ret\n\n\ndef add_community_num_in_plate(df_origin):\n df_ret = df_origin.copy()\n dict_community_num = {}\n list_plate = list(df_ret['plate'].unique())\n list_community_num_in_plate = []\n for plate in list_plate:\n community_num = len(df_ret[df_ret['plate'] == plate]['communityName'].unique())\n dict_community_num[plate] = community_num\n for index, row in df_ret.iterrows():\n plate = row['plate']\n community_num = dict_community_num[plate]\n list_community_num_in_plate.append(community_num)\n dict_community_num_in_plate = {'community_num_in_plate': list_community_num_in_plate}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_community_num_in_plate)], axis=1)\n return df_ret\n\n\ndef add_transport_total_num(df_origin):\n df_ret = df_origin.copy()\n list_transport_total_num = []\n for index, row in df_ret.iterrows():\n subway_num = row['subwayStationNum']\n bus_num = row['busStationNum']\n total_num = subway_num + bus_num\n list_transport_total_num.append(total_num)\n dict_transport_total_num = {'transport_total_num': list_transport_total_num}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_transport_total_num)], axis=1)\n return df_ret\n\n\ndef add_education_total_num(df_origin):\n df_ret = df_origin.copy()\n list_education_total_num = []\n for index, row in df_ret.iterrows():\n interschool_num = row['interSchoolNum']\n school_num = row['schoolNum']\n privateschool_num = row['privateSchoolNum']\n total_num = interschool_num + school_num + privateschool_num\n list_education_total_num.append(total_num)\n dict_transport_total_num = {'education_total_num': list_education_total_num}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_transport_total_num)], axis=1)\n return df_ret\n\n\ndef add_service_total_num(df_origin):\n df_ret = df_origin.copy()\n list_service_total_num = []\n for index, row in df_ret.iterrows():\n hospital_num = row['hospitalNum']\n drugstore_num = row['drugStoreNum']\n gym_num = row['gymNum']\n bank_num = row['bankNum']\n shop_num = row['shopNum']\n park_num = row['parkNum']\n mall_num = row['mallNum']\n supermarket_num = row['superMarketNum']\n total_num = hospital_num + drugstore_num + gym_num + bank_num + shop_num + park_num + mall_num + supermarket_num\n list_service_total_num.append(total_num)\n dict_service_total_num = {'service_total_num': list_service_total_num}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_service_total_num)], axis=1)\n return df_ret\n\n\ndef test_feature(df_origin, feature_function):\n df_test = df_origin.copy()\n df_test = feature_function(df_test)\n X = df_test.drop(columns=['tradeMoney'])\n y = df_test['tradeMoney'].tolist()\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)\n\n model_lgb = lgb.LGBMRegressor(objective='regression', num_leaves=900,\n learning_rate=0.1, n_estimators=3141, bagging_fraction=0.7,\n feature_fraction=0.6, reg_alpha=0.3, reg_lambda=0.3,\n min_data_in_leaf=18, min_sum_hessian_in_leaf=0.001)\n model_lgb.fit(X_train, y_train)\n y_predict = model_lgb.predict(X_test)\n if len(y_test)==len(y_predict):\n return test_score(y_test, y_predict)\n else:\n print(\"len ytest != len ypredict\")\n return\n\n\ndef test_score(y_real, y_predict):\n m = len(y_real)\n y_average = np.mean(np.array(y_real))\n sum_fz = 0\n sum_fm = 0\n for i in range(m):\n sum_fz += (y_predict[i] - y_real[i]) ** 2\n sum_fm += (y_real[i] - y_average) ** 2\n score = 1 - sum_fz / sum_fm\n return score\n\n\ndef add_lookNum_div_pv(df_origin):\n df_ret=df_origin.copy()\n list_lookNum_div_pv=[]\n for index,row in df_ret.iterrows():\n lookNum=row['lookNum']\n pv=row['pv']\n lookNum_div_pv=float(lookNum)/float(pv)\n list_lookNum_div_pv.append(lookNum_div_pv)\n dict_lookNum_div_pv={'lookNum_div_pv':list_lookNum_div_pv}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_lookNum_div_pv)],axis=1)\n return df_ret\n\ndef add_lookNum_div_uv(df_origin):\n df_ret=df_origin.copy()\n list_lookNum_div_uv=[]\n for index,row in df_ret.iterrows():\n lookNum=row['lookNum']\n uv=row['uv']\n lookNum_div_uv=float(lookNum)/float(uv)\n list_lookNum_div_uv.append(lookNum_div_uv)\n dict_lookNum_div_uv={'lookNum_div_uv':list_lookNum_div_uv}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_lookNum_div_uv)],axis=1)\n return df_ret\n\ndef add_totalWorkers_div_residentPopulation(df_origin):\n df_ret=df_origin.copy()\n list_totalWorkers_div_residentPopulation=[]\n for index,row in df_ret.iterrows():\n totalWorkers=row['totalWorkers']\n residentPopulation=row['residentPopulation']\n totalWorkers_div_residentPopulation=float(totalWorkers)/float(residentPopulation)\n list_totalWorkers_div_residentPopulation.append(totalWorkers_div_residentPopulation)\n dict_totalWorkers_div_residentPopulation={'totalWorkers_div_residentPopulation':list_totalWorkers_div_residentPopulation}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_totalWorkers_div_residentPopulation)],axis=1)\n return df_ret\n\ndef add_newWorkers_div_totalWorkers(df_origin):\n df_ret=df_origin.copy()\n list_newWorkers_div_totalWorker=[]\n for index,row in df_ret.iterrows():\n newWorkers=row['newWorkers']\n totalWorker=row['totalWorkers']\n newWorkers_div_totalWorker=float(newWorkers)/float(totalWorker)\n list_newWorkers_div_totalWorker.append(newWorkers_div_totalWorker)\n dict_newWorkers_div_totalWorker={'newWorkers_div_totalWorker':list_newWorkers_div_totalWorker}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_newWorkers_div_totalWorker)],axis=1)\n return df_ret\n\ndef add_tradeLandArea_div_tradeLandNum(df_origin):\n df_ret=df_origin.copy()\n list_tradeLandArea_div_tradeLandNum=[]\n for index,row in df_ret.iterrows():\n tradeLandArea=row['tradeLandArea']\n tradeLandNum=row['tradeLandNum']\n if tradeLandNum==0:\n list_tradeLandArea_div_tradeLandNum.append(0)\n continue\n tradeLandArea_div_tradeLandNum=float(tradeLandArea)/float(tradeLandNum)\n list_tradeLandArea_div_tradeLandNum.append(tradeLandArea_div_tradeLandNum)\n dict_tradeLandArea_div_tradeLandNum={'tradeLandArea_div_tradeLandNum':list_tradeLandArea_div_tradeLandNum}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_tradeLandArea_div_tradeLandNum)],axis=1)\n return df_ret\n\ndef add_supplyLandArea_div_supplyLandNum(df_origin):\n df_ret=df_origin.copy()\n list_supplyLandArea_div_supplyLandNum=[]\n for index,row in df_ret.iterrows():\n supplyLandArea=row['supplyLandArea']\n supplyLandNum=row['supplyLandNum']\n if supplyLandNum==0:\n list_supplyLandArea_div_supplyLandNum.append(0)\n continue\n supplyLandArea_div_supplyLandNum=float(supplyLandArea)/float(supplyLandNum)\n list_supplyLandArea_div_supplyLandNum.append(supplyLandArea_div_supplyLandNum)\n dict_supplyLandArea_div_supplyLandNum={'supplyLandArea_div_supplyLandNum':list_supplyLandArea_div_supplyLandNum}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_supplyLandArea_div_supplyLandNum)],axis=1)\n return df_ret\n\n#本月成交套数+未成交套数=总套数\n#总套数*新房成交均价\n\ndef add_totalNewNum(df_origin):\n df_ret=df_origin.copy()\n list_totalNewNum=[]\n for index,row in df_ret.iterrows():\n tradeNewNum=row['tradeNewNum']\n remainNewNum=row['remainNewNum']\n totalNewNum=float(tradeNewNum)+float(remainNewNum)\n list_totalNewNum.append(totalNewNum)\n dict_totalNewNum={'totalNewNum':list_totalNewNum}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_totalNewNum)],axis=1)\n return df_ret\n\ndef add_totalNewNum_mul_tradeNewMeanPrice(df_origin):\n df_ret=df_origin.copy()\n list_totalNewNum_mul_tradeNewMeanPrice=[]\n for index,row in df_ret.iterrows():\n tradeNewNum=row['tradeNewNum']\n remainNewNum=row['remainNewNum']\n tradeNewMeanPrice=row['tradeNewMeanPrice']\n totalNewNum=float(tradeNewNum)+float(remainNewNum)\n totalNewNum_mul_tradeNewMeanPrice=totalNewNum*float(tradeNewMeanPrice)\n list_totalNewNum_mul_tradeNewMeanPrice.append(totalNewNum_mul_tradeNewMeanPrice)\n dict_totalNewNum_mul_tradeNewMeanPrice={'totalNewNum_mul_tradeNewMeanPrice':list_totalNewNum_mul_tradeNewMeanPrice}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_totalNewNum_mul_tradeNewMeanPrice)],axis=1)\n return df_ret\n\n#二手房成交总金额/二手房成交套数\n#新房成交总金额/新房成交总套数\n\ndef add_totalTradeMoney_div_tradeSecNum(df_origin):\n df_ret=df_origin.copy()\n list_totalTradeMoney_div_tradeSecNum=[]\n for index,row in df_ret.iterrows():\n totalTradeMoney=row['totalTradeMoney']\n tradeSecNum=row['tradeSecNum']\n if tradeSecNum==0:\n list_totalTradeMoney_div_tradeSecNum.append(0)\n continue\n totalTradeMoney_div_tradeSecNum=float(totalTradeMoney)/float(tradeSecNum)\n list_totalTradeMoney_div_tradeSecNum.append(totalTradeMoney_div_tradeSecNum)\n dict_totalTradeMoney_div_tradeSecNum={'totalTradeMoney_div_tradeSecNum':list_totalTradeMoney_div_tradeSecNum}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_totalTradeMoney_div_tradeSecNum)],axis=1)\n return df_ret\n\ndef add_totalNewTradeMoney_div_tradeNewNum(df_origin):\n df_ret=df_origin.copy()\n list_totalNewTradeMoney_div_tradeNewNum=[]\n for index,row in df_ret.iterrows():\n totalNewTradeMoney=row['totalNewTradeMoney']\n tradeNewNum=row['tradeNewNum']\n if tradeNewNum==0:\n list_totalNewTradeMoney_div_tradeNewNum.append(0)\n continue\n totalNewTradeMoney_div_tradeNewNum=float(totalNewTradeMoney)/float(tradeNewNum)\n list_totalNewTradeMoney_div_tradeNewNum.append(totalNewTradeMoney_div_tradeNewNum)\n dict_totalNewTradeMoney_div_tradeNewNum={'totalNewTradeMoney_div_tradeNewNum':list_totalNewTradeMoney_div_tradeNewNum}\n df_ret=pd.concat([df_ret,pd.DataFrame(dict_totalNewTradeMoney_div_tradeNewNum)],axis=1)\n return df_ret\n\ndef add_none(df_origin):\n df_ret=df_origin\n return df_ret\n\ndef test_fun(df_processed,function):\n print(function.__name__,\" score= \",test_feature(df_processed, function))\n\ndef add_trademoney_div_area(df_processed,window_length=10):\n df_ret=df_processed.copy()\n dict_trademoney_div_area={}\n list_trademoney_div_area=[]\n left=0\n right=window_length\n while left<1050:\n df_tmp=df_ret[(df_ret['area']>=left)&(df_ret['area']<=right)]\n sum_area=df_tmp['area'].sum()\n sum_trademoney=df_tmp['tradeMoney'].sum()\n dict_trademoney_div_area[int(left/window_length)]=sum_trademoney/sum_area\n left+=window_length\n right+=window_length\n list_area=df_ret['area'].tolist()\n for area in list_area:\n list_trademoney_div_area.append(dict_trademoney_div_area[int(area/window_length)])\n df_ret=pd.concat([df_ret,pd.DataFrame({'trademoney_div_area':list_trademoney_div_area})],axis=1)\n return df_ret\n\n\ndef add_community_ave_trademoney_div_area(df_origin):\n df_ret = df_origin.copy()\n dict_commnityname_trademoney = {}\n for i in df_ret['communityName'].unique():\n df_tmp=df_ret[df_ret['communityName'] == i]\n trademoney_ave = df_tmp['tradeMoney'].sum()/df_tmp['area'].sum()\n dict_commnityname_trademoney[i] = trademoney_ave\n list_trademoney_ave = []\n for index, row in df_ret.iterrows():\n communityname = row['communityName']\n trademoney = dict_commnityname_trademoney[communityname]\n list_trademoney_ave.append(trademoney)\n dict_trademoney_final = {'community_ave_trademoney_div_area': list_trademoney_ave}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_trademoney_final)], axis=1)\n return df_ret\n\n\ndef add_plate_ave_trademoney_div_area(df_origin):\n df_ret = df_origin.copy()\n dict_commnityname_trademoney = {}\n for i in df_ret['plate'].unique():\n df_tmp=df_ret[df_ret['plate'] == i]\n trademoney_ave = df_tmp['tradeMoney'].sum()/df_tmp['area'].sum()\n dict_commnityname_trademoney[i] = trademoney_ave\n list_trademoney_ave = []\n for index, row in df_ret.iterrows():\n communityname = row['plate']\n trademoney = dict_commnityname_trademoney[communityname]\n list_trademoney_ave.append(trademoney)\n dict_trademoney_final = {'plate_ave_trademoney_div_area': list_trademoney_ave}\n df_ret = pd.concat([df_ret, pd.DataFrame(dict_trademoney_final)], axis=1)\n return df_ret\n\n\n\ndf_processed = pd.read_csv(r\"C:\\Users\\master\\Desktop\\future_lab\\rental_predict\\result\\data_processed.csv\")\n\ndf_processed['houseToward'] = df_processed['houseToward'].astype('category')\ndf_processed['rentType'] = df_processed['rentType'].astype('category')\ndf_processed['houseDecoration'] = df_processed['houseDecoration'].astype('category')\ndf_processed['houseFloor'] = df_processed['houseFloor'].astype('category')\ndf_processed['communityName'] = df_processed['communityName'].astype('category')\ndf_processed['region'] = df_processed['region'].astype('category')\ndf_processed['plate'] = df_processed['plate'].astype('category')\n\ndf_processed = df_processed.drop(columns=['tradeYear'])\ndf_processed = df_processed.drop(columns=['ID'])\n\ndf_processed=add_community_ave_trademoney(df_processed)\ndf_processed=add_region_ave_trademoney(df_processed)\ndf_processed=add_plate_ave_trademoney(df_processed)\ndf_processed=add_pv_div_uv(df_processed)\ndf_processed=add_month_ave_trademoney(df_processed)\n\nlist_function=[add_tradeyear_minus_buildyear,\n add_plate_num_in_region,\n add_community_num_in_plate,\n add_transport_total_num,\n add_education_total_num,\n add_service_total_num,\n add_lookNum_div_pv,\n add_lookNum_div_uv,\n add_totalWorkers_div_residentPopulation,\n add_newWorkers_div_totalWorkers,\n add_tradeLandArea_div_tradeLandNum,\n add_supplyLandArea_div_supplyLandNum,\n add_totalNewNum,\n add_totalNewNum_mul_tradeNewMeanPrice,\n add_totalTradeMoney_div_tradeSecNum,\n add_totalNewTradeMoney_div_tradeNewNum]\nfor function_name in list_function:\n test_fun(df_processed,function_name)\n\nlist_doubt_feature=['saleSecHouseNum',\n 'interSchoolNum',\n 'schoolNum',\n 'privateSchoolNum',\n 'hospitalNum',\n 'drugStoreNum',\n 'gymNum',\n 'bankNum',\n 'shopNum',\n 'parkNum',\n 'mallNum',\n 'superMarketNum',\n 'totalTradeMoney',\n 'totalTradeArea',\n 'tradeMeanPrice',\n 'tradeSecNum',\n 'totalNewTradeMoney',\n 'totalNewTradeArea',\n 'tradeNewMeanPrice',\n 'tradeNewNum',\n 'remainNewNum',\n 'supplyNewNum',\n 'supplyLandNum',\n 'tradeLandNum',\n 'tradeLandArea',\n 'landTotalPrice',\n 'landMeanPrice',\n 'residentPopulation',\n 'tradeMonth',\n 'tradeDay',\n 'bedroom',\n 'livingroom',\n 'bathroom']\nfor feature_name in list_doubt_feature:\n print(\"drop \",feature_name)\n test_fun(df_processed.drop(columns=[feature_name]),add_none)\n\ntest_fun(df_processed,add_trademoney_div_area)\ntest_fun(df_processed,add_plate_ave_trademoney_div_area)\n\nfor i in range(5,30):\n print(\"window_length=\",i)\n test_fun(add_trademoney_div_area(df_processed,i),add_none)","sub_path":"code/feature_extraction.py","file_name":"feature_extraction.py","file_ext":"py","file_size_in_byte":21508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"208092800","text":"from scipy import constants\nimport math\n\nx = constants.Planck / (8 * constants.pi**2 * (1500/8) * constants.c)\ny = 0.016 / constants.Avogadro\nz = (y**2) / (2*y)\nw = math.sqrt(x / z)\nprint(x)\nprint(y)\nprint(z)\nprint(\"{:.6e}\".format(w))\n","sub_path":"cem992/previous-assignments/findb.py","file_name":"findb.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"437524284","text":"import main\r\nimport Book_Ticket\r\nimport sqlite3\r\nimport re\r\nair_database=sqlite3.connect('airline.db')\r\nair_cursor=air_database.cursor()\r\nclass authen:\r\n def __init__(self,choice):\r\n print(100*\"*\")\r\n print(\"WELCOME TO TESLA'S AIRLINE RESERVATION\")\r\n print(100*\"*\")\r\n #Check valid mobile and email address (2ND CALL)\r\n def pattern_Match():\r\n pattern_email=re.compile(r'[a-zA-Z0-9._+-]+@\\w+\\.\\w+')\r\n pattern_mobile=re.compile(r'^[9876]\\d{9}') \r\n \r\n if(pattern_email.match(self.email)):\r\n if(choice=='C'):\r\n if(pattern_mobile.match(self.mobile)):\r\n return True\r\n else:\r\n return True\r\n else:\r\n return False\r\n\r\n #Retry when error occured (1st EXECUTED) \r\n while(1):\r\n self.email=input(\"Enter your Email: \")\r\n print(100*\"*\")\r\n if(choice=='C'):\r\n self.name=input(\"Enter your Name: \")\r\n print(60*\"*\")\r\n self.mobile=(input(\"Enter your Mobile no: +91\"))\r\n print(100*\"*\")\r\n self.password=input(\"Enter your Password: \")\r\n print(100*\"*\")\r\n if(pattern_Match()):\r\n break\r\n else:\r\n print(\"Enter the correct credentials.....Try Again\")\r\n print(60*\"*\")\r\n continue\r\n\r\n \r\n\r\n #CHECK LOGIN CRETENTIALS\r\n def Login(self):\r\n self.names_s,self.emails,self.phones,self.choices=self.checkUser()\r\n if(self.choices==True):\r\n main.home(self.names_s,self.emails,self.phones)\r\n else:\r\n return\r\n return\r\n\r\n #USER CHECKING WITH THE SQLITE DATABASE\r\n def checkUser(self):\r\n check_query=\"SELECT Email,Name,Phone_no from User_details where Email=='{}';\".format(self.email)\r\n air_cursor.execute(check_query)\r\n get_result=air_cursor.fetchone()\r\n if(get_result==None or get_result[0]!=self.email):\r\n print(\"Invalid Account...Please Create an Account before Login\")\r\n print(100*\"*\")\r\n return False\r\n else:\r\n return get_result[1],get_result[0],get_result[2],True\r\n\r\n \r\n #INVOKE THE DATABASE(CREATION)\r\n def CreateAc(self):\r\n self.create_user()\r\n main.home(self.name,self.email,self.mobile)\r\n return\r\n\r\n\r\n #UPLOAD THE USER DATA TO DATABASE(CREATION)\r\n def create_user(self):\r\n air_cursor.execute('''INSERT INTO User_details(Name,Email,Password,Phone_no)values(?,?,?,?);''',(self.name,self.email,self.password,self.mobile))\r\n air_database.commit()\r\n \r\nget_choice=int(input(\"1.Login\\n2.Create An Account\\n\"))\r\nif(get_choice==1):\r\n s=authen('L')\r\n s.Login()\r\nelse:\r\n s=authen('C')\r\n s.CreateAc()\r\n","sub_path":"authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"532952164","text":"from lxml import html\nfrom urllib import urlopen\nresponse = urlopen('http://www.entropywebscraping.com')\nresponse_body = response.read()\n\ntree = html.fromstring(response_body)\n\nprint(response.headers)\n\nprint(tree.xpath('//meta[@name=\"description\"]/@content'))","sub_path":"networking/requests.py","file_name":"requests.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"425601261","text":"# Author: D Yoan L Mekontchou Yomba\n# Date : 1/26/2018\n# Implement fibonacci in a recursive fashion using memoisation\n\n# imports\nimport sys;\n\n# recursive function definition implementing memoization\ndef fibmemoized(argument, memory):\n # check if input argument was 1 and handle special case\n if argument <= 1:\n return 1\n # case fibonacci sequence is stored in memory already\n elif argument in memory:\n return memory[argument]\n # fill the memo with the contents of fibonacci recursive call\n else:\n memory[argument] = fibmemoized(argument-1, memory) + fibmemoized(argument-2,memory)\n return memory[argument]\n\nif __name__ == \"__main__\":\n # define memo\n memoize = {0:1,1:1}\n if(len(sys.argv)) > 1:\n arg = sys.argv[1]\n # process input\n print(fibmemoized(int(arg), memoize))\n","sub_path":"Week3/problem2.py","file_name":"problem2.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"445136991","text":"import math\nimport random\nimport sys\nfrom configparser import ConfigParser\n\nLEFT = (-1, 0)\nRIGHT = (1, 0)\nUP = (0, 1)\nDOWN = (0, -1)\nMOVE_DIRECTIONS = [LEFT, RIGHT, UP, DOWN]\n\n# values for the heuristic\nINFINITY = sys.maxsize\nLOST_GAME = -INFINITY\nWIN_GAME = INFINITY\nDRAW_GAME = LOST_GAME / 2\n\nMOVE = \"MOVE\"\nBOOM = \"BOOM\"\n\nWHITE = \"white\"\nBLACK = \"black\"\n\nSTART_BLACK_STACKS = {\n (0, 7): 1, (1, 7): 1, (3, 7): 1, (4, 7): 1, (6, 7): 1, (7, 7): 1,\n (0, 6): 1, (1, 6): 1, (3, 6): 1, (4, 6): 1, (6, 6): 1, (7, 6): 1}\nSTART_WHITE_STACKS = {\n (0, 1): 1, (1, 1): 1, (3, 1): 1, (4, 1): 1, (6, 1): 1, (7, 1): 1,\n (0, 0): 1, (1, 0): 1, (3, 0): 1, (4, 0): 1, (6, 0): 1, (7, 0): 1}\n\nWEIGHT = {1: 12 / 12, 2: 11 / 12, 3: 10 / 12, 4: 9 / 12, 5: 8 / 12, 6: 7 / 12, 7: 6 / 12, 8: 5 / 12, 9: 4 / 12,\n 10: 3 / 12, 11: 2 / 12, 12: 1 / 12}\nEMPTY_STACK_NUMBERS = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0}\n\nnum_pieces_evs = []\n\nparser = ConfigParser()\nparser.read('./tdleaf0/weights.ini')\n\nw1 = parser.getfloat('weights', 'w1')\nmanhattan_dist_evs = []\nw2 = parser.getfloat('weights', 'w2')\nnum_groups_evs = []\nw3 = parser.getfloat('weights', 'w3')\n\neval_evs = []\n\n\nclass State:\n \"\"\"State class to be associated with 1 The state is stored in the form of 2 dictionaries, one for white stacks\n and one for black stacks. Each dict has keys which are the (x, y) coordinates of a square where there is at least 1\n piece. The values associated with each x, y coordinate key is the integer number of pieces in that square.\n \"\"\"\n\n def __init__(self, white_stacks=None, black_stacks=None, turn=0):\n # e.g. white_stacks = {(3,2): 1, (3,4): 3}\n if white_stacks is None:\n self.white_stacks = dict(START_WHITE_STACKS)\n else:\n self.white_stacks = dict(white_stacks)\n if black_stacks is None:\n self.black_stacks = dict(START_BLACK_STACKS)\n else:\n self.black_stacks = dict(black_stacks)\n self.turn = turn\n\n def __eq__(self, other):\n return bool((self.white_stacks == other.white_stacks) and (self.black_stacks == other.black_stacks))\n\n def total_white(self):\n return sum(self.white_stacks.values())\n\n def total_black(self):\n return sum(self.black_stacks.values())\n\n def total_pieces(self, colour=None):\n if colour is None:\n return self.total_black() + self.total_white()\n if colour == WHITE:\n return self.total_white()\n return self.total_black()\n\n def get_colour(self, colour):\n \"\"\"returns the dictionary of stacks for colour='white' or colour='black' \"\"\"\n if colour == WHITE:\n return self.white_stacks\n if colour == BLACK:\n return self.black_stacks\n # else, invalid colour given so return None\n return None\n\n def get_squares(self, colour):\n \"\"\"returns the keys of the stack dictionary for 'colour'='white' or 'colour'='black'.\n Since the keys of the stack dictionaries are the (x, y) coordinates where there are at least 1 piece,\n the return type is a list of (x, y) tuples where there are 'colour' pieces\"\"\"\n return list(self.get_colour(colour).keys())\n\n def get_nontrivial_boom_actions(self, colour):\n # dont return square that has the same resulting state\n # dont return a boom action that only removes our pieces\n current = self.copy()\n actions = []\n while len(current.get_squares(colour)) > 0:\n stack_to_boom = current.get_squares(colour)[0]\n actions.append((BOOM, stack_to_boom))\n current = chain_boom(current, stack_to_boom)\n return actions\n\n def get_non_trivial_non_suicidal_boom_actions(self, colour):\n # dont return square that has the same resulting state\n # dont return a boom action that only removes our pieces\n\n current = self.copy()\n actions = []\n while len(current.get_squares(colour)) > 0:\n stack_to_boom = current.get_squares(colour)[0]\n if current.total_pieces(opponent(colour)) < self.total_pieces(opponent(colour)):\n actions.append((BOOM, stack_to_boom))\n current = chain_boom(current, stack_to_boom)\n return actions\n\n def get_non_trivial_move_actions(self, colour):\n actions = []\n\n for stack in self.get_colour(colour).items():\n # iterate through each possible number of pieces to move from our stack at the current occupied_square\n for n_pieces in range(1, stack[1] + 1):\n # possible moving directions\n for move_direction in MOVE_DIRECTIONS:\n # number of squares to move n_pieces from current stack, 1 <= n_steps <= n_pieces\n for n_steps in range(1, stack[1] + 1):\n # check if moving n_steps in move_direction from current stack is a legal move (i.e. not out of\n # bounds and not landing on an enemy piece)\n if is_legal_move(self.get_squares(opponent(colour)), stack[0], move_direction, n_steps):\n final_square = calculate_dest_square(stack[0], move_direction, n_steps)\n act = (MOVE, n_pieces, stack[0], final_square)\n actions.append((heuristic(colour, Node(self).apply_action(colour, act).state), act))\n random.shuffle(actions)\n actions.sort(key=lambda x: x[0], reverse=True)\n return [x[1] for x in actions][0:math.ceil(len(actions) / (3 / 2))]\n\n \"\"\"def eval(self, colour=WHITE):\n return 0\n white_stack_numbers = dict(EMPTY_STACK_NUMBERS)\n for stack_pieces in self.white_stacks.values():\n white_stack_numbers[stack_pieces] += 1\n black_stack_numbers = dict(EMPTY_STACK_NUMBERS)\n for stack_pieces in self.black_stacks.values():\n black_stack_numbers[stack_pieces] += 1\n eval = WEIGHT[1] * (white_stack_numbers[1] - black_stack_numbers[1]) \\\n + WEIGHT[2] * (white_stack_numbers[2] - black_stack_numbers[2]) \\\n + WEIGHT[1] * (white_stack_numbers[1] - black_stack_numbers[1])\n etc...\n if colour == WHITE:\n eval_sign = 1\n else:\n eval_sign = -1\n ev = 0\n for i in range(1, 13):\n ev += WEIGHT[i] * ((white_stack_numbers[i] - black_stack_numbers[i]) * eval_sign)\n # return ev + eval_sign * (self.total_white() - self.total_black())\n # return ((self.total_white() * len(self.white_stacks)) - self.total_black() * len(self.black_stacks)) * eval_sign\"\"\"\n\n def evaluation(self, colour=WHITE):\n eval = 0\n\n if (self.total_black() == 0) and (self.total_white() == 0):\n return DRAW_GAME\n\n if colour == WHITE:\n if self.total_black() == 0:\n # win game\n return WIN_GAME\n if self.total_white() == 0:\n # lost game\n return LOST_GAME\n\n if colour == BLACK:\n if self.total_white() == 0:\n # win game\n return WIN_GAME\n if self.total_black() == 0:\n # lost game\n return LOST_GAME\n\n # eval += self.piece_val(colour) - self.piece_val(opponent(colour))\n # eval += abs(math.tanh(self.num_groups(colour))) - abs(math.tanh(manhattan_dist(self, colour)))\n # eval += normalise(NUM_GROUPS, self.num_groups(colour)) - normalise(MANHATTAN, manhattan_dist(self, colour))\n # eval -= abs(math.tanh(manhattan_dist(self, colour)))\n\n eval += w1 * self.weighted_piece_val(colour)\n\n eval -= manhattan_dist(self, colour) * w2\n\n eval += self.num_groups(colour) * w3\n\n return eval\n\n def weighted_piece_val(self, colour):\n return ((0.95 ** self.total_pieces()) * (self.total_pieces(colour) - self.total_pieces(opponent(colour))))\n\n def num_groups(self, colour):\n \"\"\"A group is defined as a set of pieces over one or more squares which would all be removed in\n a boom action from a boom in any of the pieces in that group.\n That is, a BOOM of any stack in a group of stacks will BOOM all other stacks in that group\"\"\"\n # the number of distinct groups is equal to the number of possible boom actions until we have no more stacks left\n return len(self.get_nontrivial_boom_actions(colour))\n\n def copy(self):\n return State(self.white_stacks, self.black_stacks, self.turn)\n\n\nclass Node:\n \"\"\"Node class for storing states and their values\"\"\"\n\n def __init__(self, state=None, value=0, parent=None, move=None, depth=0):\n if state is None:\n self.state = State()\n self.last_colour = BLACK\n else:\n self.state = State(state.white_stacks, state.black_stacks, state.turn)\n self.value = value\n self.parent = parent\n self.move = move\n self.depth = depth\n self.last_colour = None\n\n # these functions are for comparing the scores (or 'value') associated with each node\n def __lt__(self, other):\n return self.value < other.value\n\n def __gt__(self, other):\n return self.value > other.value\n\n def __le__(self, other):\n return self.value <= other.value\n\n def __ge__(self, other):\n return self.value >= other.value\n\n # this is for checking if the node is already in the explored_nodes array (i.e. it's has the same state)\n # For example, when someone checks if node1 == node2, it will return true if they have the same state\n def __eq__(self, other):\n return self.state == other.state\n\n def copy(self):\n copy_node = Node(self.state, self.value, self.parent, self.move, self.depth)\n copy_node.last_colour = self.last_colour\n return copy_node\n\n def apply_action(self, colour, action):\n \"\"\"return a copy of the base_node after action has happened on it\"\"\"\n if action[0] == MOVE:\n return move_action(colour, self, action[1], action[2], action[3])\n if action[0] == BOOM:\n return boom_action(colour, self, action[1])\n # else invalid action\n print(\"INVALID ACTION GIVEN TO .apply_action() in aiutils.py\\n\")\n return None\n\n def get_possible_actions(self, colour):\n \"\"\"Return a list of legal actions for 'colour' from the current node's state E.g. could return something like\n [(BOOM, (0, 2)), (BOOM, (0, 1)), (MOVE, 2, (0, 1), (2, 1)), (MOVE, 1, (7, 5), (7, 6)) ... etc]\n \"\"\"\n # array of actions which we will return after we have filled it with possible (legal) moves\n actions = []\n\n # go through the list of applicable BOOM actions and add them to actions[]\n squares = self.state.get_squares(colour)\n for stack in squares:\n actions.append((BOOM, stack))\n\n if self.state.total_pieces() > 10:\n # go through the list of applicable BOOM actions and add them to actions[]\n actions += self.state.get_non_trivial_move_actions(colour)\n return actions\n else:\n # go through the list of applicable MOVE actions\n # for each item from .items() from a stack dictionary, item[0] is the (x, y) coordinates of of the stack and\n # item[1] is the number of pieces in the stack\n for stack in self.state.get_colour(colour).items():\n # iterate through each possible number of pieces to move from our stack at the current occupied_square\n for n_pieces in range(1, stack[1] + 1):\n # possible moving directions\n for move_direction in MOVE_DIRECTIONS:\n # number of squares to move n_pieces from current stack, 1 <= n_steps <= n_pieces\n for n_steps in range(1, stack[1] + 1):\n # check if moving n_steps in move_direction from current stack is a legal move (i.e. not out of\n # bounds and not landing on an enemy piece)\n if is_legal_move(self.state.get_squares(opponent(colour)), stack[0], move_direction,\n n_steps):\n final_square = calculate_dest_square(stack[0], move_direction, n_steps)\n actions.append((MOVE, n_pieces, stack[0], final_square))\n return actions\n\n \"\"\"def get_possible_actions(self, colour):\n \"\"\"\"\"\"Return a list of legal actions for 'colour' from the current node's state E.g. could return something like\n [(BOOM, (0, 2)), (BOOM, (0, 1)), (MOVE, 2, (0, 1), (2, 1)), (MOVE, 1, (7, 5), (7, 6)) ... etc]\n \"\"\"\"\"\"\n # array of actions which we will return after we have filled it with possible (legal) moves\n actions = []\n # go through the list of applicable BOOM actions and add them to actions[]\n squares = self.state.get_squares(colour)\n for stack in squares:\n actions.append((BOOM, stack))\n # go through the list of applicable MOVE actions\n # for each item from .items() from a stack dictionary, item[0] is the (x, y) coordinates of of the stack and\n # item[1] is the number of pieces in the stack\n for stack in self.state.get_colour(colour).items():\n # iterate through each possible number of pieces to move from our stack at the current occupied_square\n for n_pieces in range(1, stack[1] + 1):\n # possible moving directions\n for move_direction in MOVE_DIRECTIONS:\n # number of squares to move n_pieces from current stack, 1 <= n_steps <= n_pieces\n for n_steps in range(1, stack[1] + 1):\n # check if moving n_steps in move_direction from current stack is a legal move (i.e. not out of\n # bounds and not landing on an enemy piece)\n if is_legal_move(self.state.get_squares(opponent(colour)), stack[0], move_direction, n_steps):\n final_square = calculate_dest_square(stack[0], move_direction, n_steps)\n actions.append((MOVE, n_pieces, stack[0], final_square))\n return actions\"\"\"\n\n def get_children(self, colour):\n children = []\n actions = self.get_possible_actions(colour)\n for action in actions:\n children.append(self.apply_action(colour, action))\n return children\n\n\ndef normalise(type, value):\n if type == \"md\":\n return (value - 0.5) / (7.5 - 0.5)\n if type == \"ng\":\n return (value - 1) / (4 - 1)\n\n\ndef is_legal_move(enemy_stack_locations, moving_stack_location, move_direction, n_steps):\n \"\"\" check if moving n_steps in move_direction from current stack is a legal move (i.e. not out of bounds and not\n landing on an enemy piece) \"\"\"\n dest_square = calculate_dest_square(moving_stack_location, move_direction, n_steps)\n return bool((dest_square[0] in range(0, 8)) and (dest_square[1] in range(0, 8)) and (\n dest_square not in enemy_stack_locations))\n\n\ndef calculate_dest_square(moving_stack_location, move_direction, n_steps):\n return (\n moving_stack_location[0] + n_steps * move_direction[0], moving_stack_location[1] + n_steps * move_direction[1])\n\n\ndef opponent(colour):\n \"\"\"get the opponent colour. If given 'white' return 'black' and vice versa\"\"\"\n if colour == WHITE:\n return BLACK\n if colour == BLACK:\n return WHITE\n return None\n\n\ndef manhattan_dist(state, colour):\n total = 0\n\n if colour == WHITE:\n for white in state.white_stacks.items():\n current_total = 0\n for black in state.black_stacks.items():\n current_total += (abs(white[0][0] - black[0][0]) + abs(white[0][1] - black[0][1]))\n if len(state.black_stacks) < 3:\n total += current_total / 5\n else:\n total += current_total / len(state.black_stacks)\n # if len(state.black_stacks) == 0: return total\n if len(state.white_stacks) < 3:\n return total / 5\n return total / len(state.white_stacks)\n\n if colour == BLACK:\n for black in state.black_stacks.items():\n current_total = 0\n for white in state.white_stacks.items():\n current_total += (abs(white[0][0] - black[0][0]) + abs(white[0][1] - black[0][1]))\n if len(state.white_stacks) < 3:\n total += current_total / 5\n else:\n total += current_total / len(state.white_stacks)\n # if len(state.black_stacks) == 0: return total\n if len(state.black_stacks) < 3:\n return total / 5\n return total / len(state.black_stacks)\n\n\ndef move_action(colour, base_node, n_pieces, stack, dest_square):\n \"\"\" apply a move action to the given base node by moving n_pieces from stack n_steps in move_direction\n returns new_node resulting from the move \"\"\"\n # make a new node that is a copy of the base_node. Set last_player to current colour making the move\n new_node = base_node.copy()\n # adjust new_node fields according to how our move will change them:\n # parent node of the new_node is the base_node\n new_node.parent = base_node\n # new_node depth is parent depth + 1\n new_node.depth = base_node.depth + 1\n new_node.state.turn = base_node.state.turn + 1\n # store the move which got us to new_node\n new_node.move = (MOVE, n_pieces, stack, dest_square)\n new_node.last_colour = colour\n\n # execute move on new_node state\n # move the pieces from the stack to a new stack\n\n new_node.state.get_colour(colour)[stack] -= n_pieces\n if new_node.state.get_colour(colour)[stack] == 0:\n new_node.state.get_colour(colour).pop(stack)\n if dest_square in new_node.state.get_colour(colour):\n # there is already a stack in the square we are moving to, just add number of pieces\n new_node.state.get_colour(colour)[dest_square] += n_pieces\n else:\n # we have to make a new key value pair because we made a new stack\n new_node.state.get_colour(colour)[dest_square] = n_pieces\n\n # update node value\n # new_node.value = heuristic(colour, new_node.state)\n new_node.value = new_node.state.evaluation(colour)\n\n return new_node\n\n\ndef boom_action(colour, base_node, stack_to_boom):\n # make a new node that is a copy of the base_node\n new_node = base_node.copy()\n\n # adjust new_node fields according to how the boom change them:\n # parent node of the new_node is the base_node\n new_node.parent = base_node\n # new_node depth is parent depth + 1\n new_node.depth = base_node.depth + 1\n new_node.state.turn = base_node.state.turn + 1\n # store the move which got us to new_node\n new_node.move = (BOOM, stack_to_boom)\n new_node.last_colour = colour\n\n # recursive boom at the new_node.state starting at 'stack', this updates the state\n new_node.state = chain_boom(new_node.state, stack_to_boom)\n\n # update value and return\n # new_node.value = heuristic(colour, new_node.state)\n new_node.value = new_node.state.evaluation(colour)\n\n return new_node\n\n\ndef heuristic(colour, state):\n if (state.total_black() == 0) and (state.total_white() == 0):\n return DRAW_GAME\n\n if colour == WHITE:\n if state.total_black() == 0:\n # win game\n return WIN_GAME\n if state.total_white() == 0:\n # lost game\n return LOST_GAME\n # else, the heuristic is the number of our pieces on the board - enemy pieces on the board + manhattan\n # distance, **higer** is better\n # return state.eval(colour)\n return state.total_white() - state.total_black() # - abs(math.tanh(manhattan_dist(\n # state,colour))) # + math.tanh(state.num_groups(WHITE)) #- abs( math.tanh(manhattan_dist(state)) ) # - manhattan_dist(state)\n\n if colour == BLACK:\n if state.total_white() == 0:\n # win game\n return WIN_GAME\n if state.total_black() == 0:\n # lost game\n return LOST_GAME\n # else, the heuristic is the number of our pieces on the board - enemy pieces on the board + manhattan\n # distance, **higer** is better\n # return state.eval(colour)\n return state.total_black() - state.total_white() # - abs(math.tanh(\n # manhattan_dist(state, colour))) # + math.tanh(state.num_groups(BLACK)) #- abs( math.tanh(manhattan_dist(state)) )\n\n # else, incorrect colour given return None\n return None\n\n\ndef is_game_over(state):\n return bool(state.total_black() == 0 or state.total_white() == 0)\n\n\ndef chain_boom(state, stack_to_boom, stacks_to_remove=None):\n # add the stack_to_boom to the stacks_to_remove\n if stacks_to_remove is None:\n stacks_to_remove = set()\n stacks_to_remove.add(stack_to_boom)\n\n # go through all the adjacent stacks to stack_to_boom\n # add the stack to the stacks to be removed\n # make a boom radius from stack_to_boom\n radius_x = [stack_to_boom[0], stack_to_boom[0], stack_to_boom[0] - 1, stack_to_boom[0] - 1,\n stack_to_boom[0] - 1, stack_to_boom[0] + 1,\n stack_to_boom[0] + 1, stack_to_boom[0] + 1]\n # possible corresponding y coordinates e.g. (2,2): [1, 3, 2, 1, 3, 2, 1, 3]\n radius_y = [stack_to_boom[1] - 1, stack_to_boom[1] + 1, stack_to_boom[1], stack_to_boom[1] - 1,\n stack_to_boom[1] + 1, stack_to_boom[1],\n stack_to_boom[1] - 1, stack_to_boom[1] + 1]\n radius = list(zip(radius_x, radius_y))\n\n # get a list of all the squares where the boom hit\n all_stacks = list(state.white_stacks.keys()) + list(state.black_stacks.keys())\n stacks_hit = list(set(all_stacks).intersection(radius))\n\n # add all the stacks_stacks_hit to the stacks_to_remove set, if they havent been added before, boom them\n for st in stacks_hit:\n if st not in stacks_to_remove:\n stacks_to_remove.add(st)\n chain_boom(state, st, stacks_to_remove)\n\n # remove stacks_to_remove from state and return state\n for st in stacks_to_remove:\n if st in state.white_stacks:\n state.white_stacks.pop(st)\n if st in state.black_stacks:\n state.black_stacks.pop(st)\n return state\n\n\ndef get_greedy_action(colour, base_node, budget):\n \"\"\"returns the action associated with the best score achieved after that action is enacted on our current_node.state\n Note: because python uses a min-heap for their priority queue implementation, better scores are lower, the lower the score the better its value\"\"\"\n\n # store actions in a dict {} where the key is the score achieved by that action, break ties randomly\n # get the possible actions from our current position\n\n # make a copy of the initial node we were given\n # base_node = Node(current_node.state)\n\n # check if we can make a book move\n global in_book\n if in_book and base_node.state.turn in book_moves[colour]:\n # check if it is a legal move\n move = book_moves[colour][base_node.state.turn]\n # check if 1) the squre we are moving from is in our stack dictionay, 2) check if the move is not landing in an enemy stack square\n if move[2] in base_node.state.get_colour(colour) and move[3] not in base_node.state.get_colour(\n opponent(colour)):\n return book_moves[colour][base_node.state.turn]\n else:\n in_book = False\n\n best_actions = [] # initialise the best_actions with a dummy value so our loop doesnt kick up a fuss when we try to access the [0] index for the first time\n best_score = LOST_GAME\n actions = base_node.get_possible_actions(colour)\n for action in actions:\n current_node = base_node.apply_action(colour, action)\n current_node.value -= manhattan_dist(current_node.state, colour)\n if current_node.value > best_score:\n best_actions = [action] # reset the list to have 1 action as the new best\n best_score = current_node.value\n elif current_node.value == best_score:\n best_actions.append(action)\n\n # find the best action in those actions and return it. Break draws randomly\n return random.choice(best_actions)\n\n\ndef get_minimax_action(colour, base_node, budget):\n best_actions = [] # initialise the best_actions with a dummy value so our loop doesnt kick up a fuss when we try to access the [0] index for the first time\n best_score = LOST_GAME\n actions = base_node.get_possible_actions(colour)\n for action in actions:\n current_node = base_node.apply_action(colour, action)\n minimax_evlu = minimax(current_node, budget, False, opponent(colour))[colour]\n if minimax_evlu > best_score:\n best_actions = [action] # reset the list to have 1 action as the new best\n best_score = minimax_evlu\n elif minimax_evlu == best_score:\n best_actions.append(action)\n\n # find the best action in those actions and return it. Break draws randomly\n return random.choice(best_actions)\n\n\n# returns {WHITE: white heuristic, BLACK: black heuristic}\n# node = 'current node being worked on'\n# depth = the amount of depth we have left to explore\n# colour = the current players turn\n\"\"\"\ndef minimax(node, depth, maximising_player, colour):\n if depth == 0 or is_game_over(node.state):\n # print({WHITE: heuristic(WHITE, node.state), BLACK: heuristic(BLACK, node.state)})\n return {WHITE: heuristic(WHITE, node.state), BLACK: heuristic(BLACK, node.state)}\n if maximising_player:\n best_value = {colour: LOST_GAME, opponent(colour): WIN_GAME}\n actions = node.get_possible_actions(colour)\n for action in actions:\n current_node = node.apply_action(colour, action)\n tmp = minimax(current_node, depth - 1, False, opponent(colour))\n if tmp[colour] > best_value[colour]:\n best_value[colour] = tmp[colour]\n best_value[opponent(colour)] = tmp[opponent(colour)]\n return best_value\n else:\n best_value = {colour: WIN_GAME, opponent(colour): LOST_GAME}\n actions = node.get_possible_actions(colour)\n for action in actions:\n current_node = node.apply_action(colour, action)\n tmp = minimax(current_node, depth - 1, True, opponent(colour))\n if tmp[colour] < best_value[colour]:\n best_value[colour] = tmp[colour]\n best_value[opponent(colour)] = tmp[opponent(colour)]\n return best_value\n\"\"\"\n\"\"\"def get_alphabeta_action(colour, node, budget):\n current_node = node.copy()\n first_moves = current_node.get_children(colour)\n best_move = None\n best_value = -INFINITY\n for i in range(len(first_moves)):\n child = first_moves[i]\n value = minimax(child, budget, -INFINITY, INFINITY, False)\n if (value > best_value):\n best_move = child.move\n best_value = value\n return best_move\"\"\"\n\n\ndef get_alphabeta_action(colour, node, budget):\n current_node = node.copy()\n first_moves = current_node.get_children(colour)\n\n moves = {}\n for i in range(len(first_moves)):\n child = first_moves[i]\n value = minimax(child, budget, -INFINITY, INFINITY, False)\n if value in moves:\n moves[value].append(child.move)\n else:\n moves[value] = [child.move]\n\n best_move = random.choice(moves[max(moves)])\n return best_move\n\n\ndef minimax(node, depth, alpha, beta, maximising_player):\n if depth == 0:\n return node.value\n current_node = node.copy()\n\n if maximising_player:\n max_eval = -INFINITY\n children = current_node.get_children(opponent(current_node.last_colour))\n children.sort(key=lambda x: x.value, reverse=True)\n for i in range(len(children)):\n ev = minimax(children[i], depth - 1, alpha, beta, False)\n max_eval = max(max_eval, ev)\n alpha = max(alpha, max_eval)\n if beta <= alpha:\n return beta\n return alpha\n else:\n min_eval = INFINITY\n children = current_node.get_children(opponent(current_node.last_colour))\n children.sort(key=lambda x: x.value, reverse=False)\n for i in range(len(children)):\n ev = minimax(children[i], depth - 1, alpha, beta, True)\n min_eval = min(min_eval, ev)\n beta = min(beta, min_eval)\n if beta <= alpha:\n return alpha\n return beta\n\n\nwhite_book = {\n 0: (MOVE, 1, (4, 1), (3, 1)),\n 2: (MOVE, 2, (3, 1), (3, 3)),\n 4: (MOVE, 1, (3, 3), (3, 5)),\n # 6: (MOVE, 1, (3, 1), (3, 5))\n}\n\nblack_book = {\n 1: (MOVE, 1, (3, 6), (4, 6)),\n 3: (MOVE, 2, (4, 6), (4, 4)),\n 5: (MOVE, 1, (4, 4), (4, 2)),\n # 7: (MOVE, 1, (4, 6), (4, 2))\n}\nbook_moves = {WHITE: white_book, BLACK: black_book}\nin_book = True\n","sub_path":"testing/tdleaf0/aiutils.py","file_name":"aiutils.py","file_ext":"py","file_size_in_byte":29103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"620697760","text":"#!/usr/bin/env python\n\nimport os\nimport sys\n\nsetup = os.path.abspath(sys.argv[0])\nparent = os.path.dirname(setup)\npkg = os.path.basename(parent)\n\nif pkg.startswith(\"py-cooperhewitt\"):\n pkg = pkg.replace(\"py-\", \"\")\n pkg = pkg.replace(\"-\", \".\")\n\n egg_info = \"%s.egg-info\" % pkg\n egg_info = os.path.join(parent, egg_info)\n\n if os.path.exists(egg_info):\n shutil.rmtree(egg_info)\n\nfrom setuptools import setup, find_packages\n\npackages = find_packages()\ndesc = open(\"README.md\").read()\nversion = open(\"VERSION\").read()\n\nsetup(\n name='cooperhewitt-swatchbook',\n namespace_packages=['cooperhewitt'],\n version=version,\n description='Cooper Hewitt\\'s Python tools for wrangling colours',\n long_description=desc,\n author='Cooper Hewitt Smithsonian Design Museum',\n url='https://github.com/cooperhewitt/py-cooperhewitt-swatchbook',\n packages=packages,\n scripts=[],\n download_url='https://github.com/cooperhewitt/py-cooperhewitt-swatchbook/releases/tag/' + version,\n license='BSD'\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"251923813","text":"# Given a blacklist B containing unique integers from [0, N), write a function to return a uniform random integer\n# from [0, N) which is NOT in B.\n#\n# Optimize it such that it minimizes the call to system’s Math.random().\n#\n# Note:\n#\n# 1 <= N <= 1000000000\n# 0 <= B.length < min(100000, N)\n# [0, N) does NOT include N. See interval notation.\n# Example 1:\n#\n# Input:\n# [\"Solution\",\"pick\",\"pick\",\"pick\"]\n# [[1,[]],[],[],[]]\n# Output: [null,0,0,0]\n# Example 2:\n#\n# Input:\n# [\"Solution\",\"pick\",\"pick\",\"pick\"]\n# [[2,[]],[],[],[]]\n# Output: [null,1,1,1]\n# Example 3:\n#\n# Input:\n# [\"Solution\",\"pick\",\"pick\",\"pick\"]\n# [[3,[1]],[],[],[]]\n# Output: [null,0,0,2]\n# Example 4:\n#\n# Input:\n# [\"Solution\",\"pick\",\"pick\",\"pick\"]\n# [[4,[2]],[],[],[]]\n# Output: [null,1,3,1]\n# Explanation of Input Syntax:\n#\n# The input is two lists: the subroutines called and their arguments. Solution's constructor has two arguments,\n# N and the blacklist B. pick has no arguments. Arguments are always wrapped with a list, even if there aren't any.\n#\nimport collections\nfrom random import randint\n\n\nclass Solution(object):\n\n def __init__(self, N, blacklist):\n \"\"\"\n :type N: int\n :type blacklist: List[int]\n \"\"\"\n m = N - 1\n self._dMap = collections.defaultdict(int)\n self._M = N - len(blacklist)\n\n # bugfixed\n for b in blacklist:\n self._dMap[b] = -1\n\n # try to do re-mapping, assume we have N=10, blacklist [3, 5, 8, 9], we want to re-mapping 3 -> 7, 5->6,\n # so we would [1,2,3,4,5] as a base\n for b in blacklist:\n # we try to generate uniformly from [1, self._M]\n if b < self._M:\n\n # we keep finding element not in blacklist, for ex, 3 we found 7,\n # then we got self._dMap[3] = 7\n # same we got self._dMap[5] = 6\n while m in self._dMap:\n m -= 1\n # re-mapping\n self._dMap[b] = m\n m -= 1\n\n\n\n\n def pick(self):\n \"\"\"\n :rtype: int\n \"\"\"\n # we uniformly generate rand in [1, self._M]\n t = randint(1, self._M)\n # if it is in black list, we find its re-map, let's say we generate 3\n # then we found its remap is 6, return 6 instead of 3\n if t in self._dMap:\n return self._dMap[t]\n # if not in black list, return it directly\n return t\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(N, blacklist)\n# param_1 = obj.pick()\n","sub_path":"learnpythonthehardway/random-pick-with-blacklist-710.py","file_name":"random-pick-with-blacklist-710.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"277957899","text":"\"\"\"\n\n将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。\n\n\n\"\"\"\nfrom notebook.algorithm.链表.utils import ListNode\nfrom notebook.algorithm.链表.utils import init_ln\nfrom notebook.algorithm.链表.utils import print_ln\n\n\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n if not l1:\n return l2\n if not l2:\n return l1\n\n if l1.val > l2.val:\n head, ln = l2, l1\n else:\n head, ln = l1, l2\n result = head\n while ln and head:\n if head.val < ln.val:\n head = head.next\n else:\n # head的下一个节点置为另一个链条的节点,导致head本来的下一个节点失效\n head.next = ln\n ln = ln.next\n head = head.next\n head.next = ln\n return result\n\n\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n dump = ListNode()\n tmp = dump\n while l1 and l2:\n if l1.val < l2.val:\n dump.next = l1\n l1 = l1.next\n else:\n dump.next = l2\n l2 = l2.next\n dump = dump.next\n if l1:\n dump.next = l1\n else:\n dump.next = l2\n return tmp.next\n\n\nhead1 = init_ln([1, 3, 5, 7, 9])\nhead2 = init_ln([1, 2, 3, 4, 5, 6, 7, 8, 9])\n\nprint_ln(Solution().mergeTwoLists(head1, head2))\n\n\"\"\"\n\n作者:LeetCode-Solution\n链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/he-bing-liang-ge-you-xu-lian-biao-by-leetcode-solu/\n来源:力扣(LeetCode)\n著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。\n\"\"\"\n\n\n# 迭代\nclass Solution:\n def mergeTwoLists(self, l1, l2):\n prehead = ListNode(-1)\n\n prev = prehead\n while l1 and l2:\n if l1.val <= l2.val:\n prev.next = l1\n l1 = l1.next\n else:\n prev.next = l2\n l2 = l2.next\n prev = prev.next\n\n # 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可\n prev.next = l1 if l1 is not None else l2\n\n return prehead.next\n\n\n\"\"\"\n递归的思路: 有点意思。很直观\n\"\"\"\nclass Solution:\n def mergeTwoLists(self, l1, l2):\n if not l1:\n return l2\n if not l2:\n return l1\n if l1.val < l2.val:\n l1.next = self.mergeTwoLists(l1.next, l2)\n # 直接返回了\n return l1\n else:\n # 直接返回了\n l2.next = self.mergeTwoLists(l2.next, l1)\n return l2\n\n\n\nhead1 = init_ln([1, 3, 5, 7, 9])\nhead2 = init_ln([1, 2, 3, 4, 5, 6, 7, 8, 9])\n\nprint_ln(Solution().mergeTwoLists(head1, head2))\n","sub_path":"algorithm/链表/21. 合并两个有序链表.py","file_name":"21. 合并两个有序链表.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"341605637","text":"from channels.routing import route, include\n\nfrom trams import consumers as trams_consumers\n\n\ntrams_channels = [\n route('websocket.connect', trams_consumers.ws_add),\n route('websocket.disconnect', trams_consumers.ws_disconnect),\n]\n\n\nchannel_routing = [\n include(trams_channels, path=r'^/trams/$'),\n]\n","sub_path":"waw_data/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"356350432","text":"# coding: utf-8\n\"\"\"\nThis modules holds methods for generating predictions from a model.\n\"\"\"\nimport os\nimport sys\nimport logging\nfrom typing import List, Optional, Tuple\nimport numpy as np\n\nimport torch\nfrom torchtext.data import Dataset, Field\n\nfrom joeynmt.helpers import bpe_postprocess, load_config, \\\n get_latest_checkpoint, load_checkpoint, store_attention_plots\nfrom joeynmt.metrics import bleu, chrf, token_accuracy, sequence_accuracy, calc_ent_f1_and_ent_mcc \nfrom joeynmt.model import build_model, Model\nfrom joeynmt.batch import Batch, Batch_with_KB\nfrom joeynmt.data import load_data, make_data_iter, make_data_iter_kb, MonoDataset\nfrom joeynmt.constants import UNK_TOKEN, PAD_TOKEN, EOS_TOKEN\nfrom joeynmt.vocabulary import Vocabulary\n\n\n# pylint: disable=too-many-arguments,too-many-locals,no-member\ndef validate_on_data(model: Model, \n data: Dataset,\n batch_size: int,\n use_cuda: bool, \n max_output_length: int,\n level: str, \n eval_metric: Optional[str],\n loss_function: torch.nn.Module = None,\n beam_size: int = 0, \n beam_alpha: int = -1,\n batch_type: str = \"sentence\",\n kb_task = None,\n valid_kb: Dataset = None,\n valid_kb_lkp: list = [], \n valid_kb_lens:list=[],\n valid_kb_truvals: Dataset = None,\n valid_data_canon: Dataset = None,\n report_on_canonicals: bool = False,\n ) \\\n -> (float, float, float, List[str], List[List[str]], List[str],\n List[str], List[List[str]], List[np.array]):\n \"\"\"\n Generate translations for the given data.\n If `loss_function` is not None and references are given,\n also compute the loss.\n\n :param model: model module\n :param data: dataset for validation\n :param batch_size: validation batch size\n :param use_cuda: if True, use CUDA\n :param max_output_length: maximum length for generated hypotheses\n :param level: segmentation level, one of \"char\", \"bpe\", \"word\"\n :param eval_metric: evaluation metric, e.g. \"bleu\"\n :param loss_function: loss function that computes a scalar loss\n for given inputs and targets\n :param beam_size: beam size for validation.\n If 0 then greedy decoding (default).\n :param beam_alpha: beam search alpha for length penalty,\n disabled if set to -1 (default).\n :param batch_type: validation batch type (sentence or token)\n :param kb_task: is not None if kb_task should be executed\n :param valid_kb: MonoDataset holding the loaded valid kb data\n :param valid_kb_lkp: List with valid example index to corresponding kb indices\n :param valid_kb_len: List with amount of triples per kb \n :param valid_data_canon: TranslationDataset of valid data but with canonized target data (for loss reporting)\n\n\n :return:\n - current_valid_score: current validation score [eval_metric],\n - valid_loss: validation loss,\n - valid_ppl:, validation perplexity,\n - valid_sources: validation sources,\n - valid_sources_raw: raw validation sources (before post-processing),\n - valid_references: validation references,\n - valid_hypotheses: validation_hypotheses,\n - decoded_valid: raw validation hypotheses (before post-processing),\n - valid_attention_scores: attention scores for validation hypotheses\n - valid_ent_f1: TODO FIXME\n \"\"\"\n\n print(f\"\\n{'-'*10} ENTER VALIDATION {'-'*10}\\n\")\n\n print(f\"\\n{'-'*10} VALIDATION DEBUG {'-'*10}\\n\")\n\n print(\"---data---\")\n print(dir(data[0]))\n print([[getattr(example, attr) for attr in dir(example) if hasattr(getattr(example, attr), \"__iter__\") and \"kb\" in attr or \"src\" in attr or \"trg\" in attr] for example in data[:3] ])\n print(batch_size)\n print(use_cuda)\n print(max_output_length)\n print(level)\n print(eval_metric)\n print(loss_function)\n print(beam_size)\n print(beam_alpha)\n print(batch_type)\n print(kb_task)\n print(\"---valid_kb---\")\n print(dir(valid_kb[0]))\n print([[getattr(example, attr) for attr in dir(example) if hasattr(getattr(example, attr), \"__iter__\") and \"kb\" in attr or \"src\" in attr or \"trg\" in attr] for example in valid_kb[:3] ])\n print(len(valid_kb_lkp), valid_kb_lkp[-5:])\n print(len(valid_kb_lens), valid_kb_lens[-5:])\n print(\"---valid_kb_truvals---\")\n print(len(valid_kb_truvals), valid_kb_lens[-5:])\n print([[getattr(example, attr) for attr in dir(example) if hasattr(getattr(example, attr), \"__iter__\") and \"kb\" in attr or \"src\" in attr or \"trg\" in attr or \"trv\" in attr]for example in valid_kb_truvals[:3]])\n print(\"---valid_data_canon---\")\n print(len(valid_data_canon), valid_data_canon[-5:])\n print([[getattr(example, attr) for attr in dir(example) if hasattr(getattr(example, attr), \"__iter__\") and\"kb\" in attr or \"src\" in attr or \"trg\" in attr or \"trv\" or \"can\" in attr]for example in valid_data_canon[:3] ])\n print(report_on_canonicals)\n\n print(f\"\\n{'-'*10} END VALIDATION DEBUG {'-'*10}\\n\")\n\n if not kb_task:\n valid_iter = make_data_iter(\n dataset=data, batch_size=batch_size, batch_type=batch_type,\n shuffle=False, train=False)\n else:\n # knowledgebase version of make data iter and also provide canonized target data\n # data: for bleu/ent f1 \n # canon_data: for loss \n valid_iter = make_data_iter_kb(\n data, valid_kb, valid_kb_lkp, valid_kb_lens, valid_kb_truvals,\n batch_size=batch_size,\n batch_type=batch_type,\n shuffle=False, train=False,\n canonize=model.canonize,\n canon_data=valid_data_canon)\n\n valid_sources_raw = data.src\n pad_index = model.src_vocab.stoi[PAD_TOKEN]\n\n # disable dropout\n model.eval()\n # don't track gradients during validation\n with torch.no_grad():\n all_outputs = []\n valid_attention_scores = []\n valid_kb_att_scores = []\n total_loss = 0\n total_ntokens = 0\n total_nseqs = 0\n for valid_batch in iter(valid_iter):\n # run as during training to get validation loss (e.g. xent)\n\n batch = Batch(valid_batch, pad_index, use_cuda=use_cuda) \\\n if not kb_task else \\\n Batch_with_KB(valid_batch, pad_index, use_cuda=use_cuda)\n\n assert hasattr(batch, \"kbsrc\") == bool(kb_task)\n\n # sort batch now by src length and keep track of order\n if not kb_task:\n sort_reverse_index = batch.sort_by_src_lengths()\n else:\n sort_reverse_index = list(range(batch.src.shape[0]))\n\n # run as during training with teacher forcing\n if loss_function is not None and batch.trg is not None:\n\n ntokens = batch.ntokens\n if hasattr(batch, \"trgcanon\") and batch.trgcanon is not None:\n ntokens = batch.ntokenscanon # normalize loss with num canonical tokens for perplexity\n # do a loss calculation without grad updates just to report valid loss\n # we can only do this when batch.trg exists, so not during actual translation/deployment\n batch_loss = model.get_loss_for_batch(\n batch, loss_function=loss_function)\n # keep track of metrics for reporting\n total_loss += batch_loss\n total_ntokens += ntokens # gold target tokens\n total_nseqs += batch.nseqs\n\n # run as during inference to produce translations\n output, attention_scores, kb_att_scores = model.run_batch(\n batch=batch, beam_size=beam_size, beam_alpha=beam_alpha,\n max_output_length=max_output_length)\n\n # sort outputs back to original order\n all_outputs.extend(output[sort_reverse_index])\n valid_attention_scores.extend(\n attention_scores[sort_reverse_index]\n if attention_scores is not None else [])\n valid_kb_att_scores.extend(\n kb_att_scores[sort_reverse_index]\n if kb_att_scores is not None else [])\n\n assert len(all_outputs) == len(data)\n\n if loss_function is not None and total_ntokens > 0:\n # total validation loss\n valid_loss = total_loss\n # exponent of token-level negative log likelihood\n # can be seen as 2^(cross_entropy of model on valid set); normalized by num tokens; \n # see https://en.wikipedia.org/wiki/Perplexity#Perplexity_per_word\n valid_ppl = torch.exp(valid_loss / total_ntokens)\n else:\n valid_loss = -1\n valid_ppl = -1\n\n # decode back to symbols\n decoding_vocab = model.trg_vocab if not kb_task else model.trv_vocab\n\n decoded_valid = decoding_vocab.arrays_to_sentences(arrays=all_outputs,\n cut_at_eos=True)\n\n print(f\"decoding_vocab.itos: {decoding_vocab.itos}\")\n print(decoded_valid)\n\n\n # evaluate with metric on full dataset\n join_char = \" \" if level in [\"word\", \"bpe\"] else \"\"\n valid_sources = [join_char.join(s) for s in data.src]\n # TODO replace valid_references with uncanonicalized dev.car data ... requires writing new Dataset in data.py\n valid_references = [join_char.join(t) for t in data.trg]\n valid_hypotheses = [join_char.join(t) for t in decoded_valid]\n\n # post-process\n if level == \"bpe\":\n valid_sources = [bpe_postprocess(s) for s in valid_sources]\n valid_references = [bpe_postprocess(v) for v in valid_references]\n valid_hypotheses = [bpe_postprocess(v) for v in valid_hypotheses]\n\n # if references are given, evaluate against them\n if valid_references:\n assert len(valid_hypotheses) == len(valid_references)\n\n print(list(zip(valid_sources, valid_references, valid_hypotheses)))\n\n current_valid_score = 0\n if eval_metric.lower() == 'bleu':\n # this version does not use any tokenization\n current_valid_score = bleu(valid_hypotheses, valid_references)\n elif eval_metric.lower() == 'chrf':\n current_valid_score = chrf(valid_hypotheses, valid_references)\n elif eval_metric.lower() == 'token_accuracy':\n current_valid_score = token_accuracy(\n valid_hypotheses, valid_references, level=level)\n elif eval_metric.lower() == 'sequence_accuracy':\n current_valid_score = sequence_accuracy(\n valid_hypotheses, valid_references)\n\n if kb_task:\n valid_ent_f1, valid_ent_mcc = calc_ent_f1_and_ent_mcc(valid_hypotheses, valid_references,\n vocab=model.trv_vocab,\n c_fun=model.canonize,\n report_on_canonicals=report_on_canonicals\n )\n \n else:\n valid_ent_f1, valid_ent_mcc = -1, -1\n else:\n current_valid_score = -1\n\n print(f\"\\n{'-'*10} EXIT VALIDATION {'-'*10}\\n\")\n return current_valid_score, valid_loss, valid_ppl, valid_sources, \\\n valid_sources_raw, valid_references, valid_hypotheses, \\\n decoded_valid, valid_attention_scores, valid_kb_att_scores, \\\n valid_ent_f1, valid_ent_mcc\n\n# pylint: disable-msg=logging-too-many-args\ndef test(cfg_file,\n ckpt: str,\n output_path: str = None,\n save_attention: bool = False,\n logger: logging.Logger = None) -> None:\n \"\"\"\n Main test function. Handles loading a model from checkpoint, generating\n translations and storing them and attention plots.\n\n :param cfg_file: path to configuration file\n :param ckpt: path to checkpoint to load\n :param output_path: path to output\n :param save_attention: whether to save the computed attention weights\n :param logger: log output to this logger (creates new logger if not set)\n \"\"\"\n\n if logger is None:\n logger = logging.getLogger(__name__)\n FORMAT = '%(asctime)-15s - %(message)s'\n logging.basicConfig(format=FORMAT)\n logger.setLevel(level=logging.DEBUG)\n\n cfg = load_config(cfg_file)\n\n if \"test\" not in cfg[\"data\"].keys():\n raise ValueError(\"Test data must be specified in config.\")\n\n # when checkpoint is not specified, take latest (best) from model dir\n if ckpt is None:\n model_dir = cfg[\"training\"][\"model_dir\"]\n ckpt = get_latest_checkpoint(model_dir)\n if ckpt is None:\n raise FileNotFoundError(\"No checkpoint found in directory {}.\"\n .format(model_dir))\n try:\n step = ckpt.split(model_dir+\"/\")[1].split(\".ckpt\")[0]\n except IndexError:\n step = \"best\"\n\n batch_size = cfg[\"training\"].get(\n \"eval_batch_size\", cfg[\"training\"][\"batch_size\"])\n batch_type = cfg[\"training\"].get(\n \"eval_batch_type\", cfg[\"training\"].get(\"batch_type\", \"sentence\"))\n use_cuda = cfg[\"training\"].get(\"use_cuda\", False)\n level = cfg[\"data\"][\"level\"]\n eval_metric = cfg[\"training\"][\"eval_metric\"]\n max_output_length = cfg[\"training\"].get(\"max_output_length\", None)\n\n # load the data\n _, dev_data, test_data,\\\n src_vocab, trg_vocab,\\\n _, dev_kb, test_kb,\\\n _, dev_kb_lookup, test_kb_lookup, \\\n _, dev_kb_lengths, test_kb_lengths,\\\n _, dev_kb_truvals, test_kb_truvals, \\\n trv_vocab, canon_fun,\\\n dev_data_canon, test_data_canon \\\n = load_data(\n data_cfg=cfg[\"data\"]\n )\n\n report_entf1_on_canonicals = cfg[\"training\"].get(\"report_entf1_on_canonicals\", False)\n\n kb_task = (test_kb!=None)\n\n data_to_predict = {\"dev\": dev_data, \"test\": test_data}\n\n # load model state from disk\n model_checkpoint = load_checkpoint(ckpt, use_cuda=use_cuda)\n\n # build model and load parameters into it\n model = build_model(cfg[\"model\"], src_vocab=src_vocab, trg_vocab=trg_vocab, trv_vocab=trv_vocab, canonizer=canon_fun)\n model.load_state_dict(model_checkpoint[\"model_state\"])\n\n # FIXME for the moment, for testing, try overriding model.canonize with canon_fun from test functions loaded data\n # should hopefully not be an issue with gridsearch results...\n\n if use_cuda:\n model.cuda() # move to GPU\n\n # whether to use beam search for decoding, 0: greedy decoding\n if \"testing\" in cfg.keys():\n beam_size = cfg[\"testing\"].get(\"beam_size\", 0)\n beam_alpha = cfg[\"testing\"].get(\"alpha\", -1)\n else:\n beam_size = 0\n beam_alpha = -1\n\n for data_set_name, data_set in data_to_predict.items():\n \n if data_set_name == \"dev\":\n kb_info = [dev_kb, dev_kb_lookup, dev_kb_lengths, dev_kb_truvals, dev_data_canon]\n elif data_set_name == \"test\":\n kb_info = [test_kb, test_kb_lookup, test_kb_lengths, test_kb_truvals, test_data_canon]\n else:\n raise ValueError((data_set_name,data_set))\n \n #pylint: disable=unused-variable\n score, loss, ppl, sources, sources_raw, references, hypotheses, \\\n hypotheses_raw, attention_scores, kb_att_scores, ent_f1, ent_mcc = validate_on_data(\n model,\n data=data_set,\n batch_size=batch_size,\n batch_type=batch_type,\n level=level,\n max_output_length=max_output_length,\n eval_metric=eval_metric,\n use_cuda=use_cuda,\n loss_function=None,\n beam_size=beam_size,\n beam_alpha=beam_alpha,\n kb_task = kb_task,\n valid_kb=kb_info[0],\n valid_kb_lkp=kb_info[1], \n valid_kb_lens=kb_info[2],\n valid_kb_truvals=kb_info[3],\n valid_data_canon=kb_info[4],\n report_on_canonicals=report_entf1_on_canonicals\n )\n \"\"\"\n batch_size=self.eval_batch_size,\n data=valid_data,\n eval_metric=self.eval_metric,\n level=self.level, \n model=self.model,\n use_cuda=self.use_cuda,\n max_output_length=self.max_output_length,\n loss_function=self.loss,\n beam_size=0, \n batch_type=self.eval_batch_type,\n kb_task=kb_task,\n valid_kb=valid_kb,\n valid_kb_lkp=valid_kb_lkp,\n valid_kb_lens=valid_kb_lens,\n valid_kb_truvals=valid_kb_truvals\n \"\"\"\n #pylint: enable=unused-variable\n\n if \"trg\" in data_set.fields:\n decoding_description = \"Greedy decoding\" if beam_size == 0 else \\\n \"Beam search decoding with beam size = {} and alpha = {}\".\\\n format(beam_size, beam_alpha)\n\n logger.info(\"%4s %s: %6.2f f1: %6.2f mcc: %6.2f [%s]\",\n data_set_name, eval_metric, score, ent_f1, ent_mcc, decoding_description)\n else:\n logger.info(\"No references given for %s -> no evaluation.\",\n data_set_name)\n\n if save_attention:\n if attention_scores:\n attention_name = \"{}.{}.att\".format(data_set_name, step)\n attention_path = os.path.join(model_dir, attention_name)\n\n logger.info(\"Saving attention plots. This might take a while..\")\n store_attention_plots(attentions=attention_scores,\n targets=hypotheses_raw,\n sources=data_set.src,\n indices=range(len(hypotheses)),\n output_prefix=attention_path)\n logger.info(\"Attention plots saved to: %s\", attention_path)\n if kb_att_scores:\n kb_att_name = \"{}.{}.kbatt\".format(data_set_name, step)\n kb_att_path = os.path.join(model_dir, kb_att_name)\n store_attention_plots(\n attentions=kb_att_scores,\n targets=hypotheses_raw,\n sources=list(data_set.kbsrc),#TODO\n indices=range(len(hypotheses)),\n output_prefix=kb_att_path,\n kb_info = (dev_kb_lookup, dev_kb_lengths, list(data_set.kbtrg)))\n logger.info(\"KB Attention plots saved to: %s\", attention_path)\n \n else:\n logger.warning(\"Attention scores could not be saved. \"\n \"Note that attention scores are not available \"\n \"when using beam search. \"\n \"Set beam_size to 0 for greedy decoding.\")\n\n if output_path is not None:\n output_path_set = \"{}.{}\".format(output_path, data_set_name)\n with open(output_path_set, mode=\"w\", encoding=\"utf-8\") as out_file:\n for hyp in hypotheses:\n out_file.write(hyp + \"\\n\")\n logger.info(\"Translations saved to: %s\", output_path_set)\n\n\ndef translate(cfg_file, ckpt: str, output_path: str = None) -> None:\n # TODO FIXME XXX this function needs to be adapted to the KB case\n \"\"\"\n Interactive translation function.\n Loads model from checkpoint and translates either the stdin input or\n asks for input to translate interactively.\n The input has to be pre-processed according to the data that the model\n was trained on, i.e. tokenized or split into subwords.\n Translations are printed to stdout.\n\n :param cfg_file: path to configuration file\n :param ckpt: path to checkpoint to load\n \"\"\"\n\n def _load_line_as_data(line):\n \"\"\" Create a dataset from one line via a temporary file. \"\"\"\n # write src input to temporary file\n tmp_name = \"tmp\"\n tmp_suffix = \".src\"\n tmp_filename = tmp_name+tmp_suffix\n with open(tmp_filename, \"w\") as tmp_file:\n tmp_file.write(\"{}\\n\".format(line))\n\n test_data = MonoDataset(path=tmp_name, ext=tmp_suffix,\n field=src_field)\n\n # remove temporary file\n if os.path.exists(tmp_filename):\n os.remove(tmp_filename)\n\n return test_data\n\n def _translate_data(test_data):\n \"\"\" Translates given dataset, using parameters from outer scope. \"\"\"\n # pylint: disable=unused-variable\n score, loss, ppl, sources, sources_raw, references, hypotheses, \\\n hypotheses_raw, attention_scores = validate_on_data(\n model, data=test_data, batch_size=batch_size,\n batch_type=batch_type, level=level,\n max_output_length=max_output_length, eval_metric=\"\",\n use_cuda=use_cuda, loss_function=None, beam_size=beam_size,\n beam_alpha=beam_alpha,\n )\n return hypotheses\n\n cfg = load_config(cfg_file)\n\n # when checkpoint is not specified, take oldest from model dir\n if ckpt is None:\n model_dir = cfg[\"training\"][\"model_dir\"]\n ckpt = get_latest_checkpoint(model_dir)\n\n batch_size = cfg[\"training\"].get(\n \"eval_batch_size\", cfg[\"training\"].get(\"batch_size\", 1))\n batch_type = cfg[\"training\"].get(\n \"eval_batch_type\", cfg[\"training\"].get(\"batch_type\", \"sentence\"))\n use_cuda = cfg[\"training\"].get(\"use_cuda\", False)\n level = cfg[\"data\"][\"level\"]\n max_output_length = cfg[\"training\"].get(\"max_output_length\", None)\n\n # read vocabs\n src_vocab_file = cfg[\"data\"].get(\n \"src_vocab\", cfg[\"training\"][\"model_dir\"] + \"/src_vocab.txt\")\n trg_vocab_file = cfg[\"data\"].get(\n \"trg_vocab\", cfg[\"training\"][\"model_dir\"] + \"/trg_vocab.txt\")\n src_vocab = Vocabulary(file=src_vocab_file)\n trg_vocab = Vocabulary(file=trg_vocab_file)\n\n data_cfg = cfg[\"data\"]\n level = data_cfg[\"level\"]\n lowercase = data_cfg[\"lowercase\"]\n\n tok_fun = lambda s: list(s) if level == \"char\" else s.split()\n\n src_field = Field(init_token=None, eos_token=EOS_TOKEN,\n pad_token=PAD_TOKEN, tokenize=tok_fun,\n batch_first=True, lower=lowercase,\n unk_token=UNK_TOKEN,\n include_lengths=True)\n src_field.vocab = src_vocab\n\n # load model state from disk\n model_checkpoint = load_checkpoint(ckpt, use_cuda=use_cuda)\n\n # build model and load parameters into it\n model = build_model(cfg[\"model\"], src_vocab=src_vocab, trg_vocab=trg_vocab)\n model.load_state_dict(model_checkpoint[\"model_state\"])\n\n if use_cuda:\n model.cuda()\n\n # whether to use beam search for decoding, 0: greedy decoding\n if \"testing\" in cfg.keys():\n beam_size = cfg[\"testing\"].get(\"beam_size\", 0)\n beam_alpha = cfg[\"testing\"].get(\"alpha\", -1)\n else:\n beam_size = 0\n beam_alpha = -1\n\n if not sys.stdin.isatty():\n # file given\n test_data = MonoDataset(path=sys.stdin, ext=\"\", field=src_field)\n hypotheses = _translate_data(test_data)\n\n if output_path is not None:\n output_path_set = \"{}\".format(output_path)\n with open(output_path_set, mode=\"w\", encoding=\"utf-8\") as out_file:\n for hyp in hypotheses:\n out_file.write(hyp + \"\\n\")\n print(\"Translations saved to: {}\".format(output_path_set))\n else:\n for hyp in hypotheses:\n print(hyp)\n\n else:\n # enter interactive mode\n batch_size = 1\n while True:\n try:\n src_input = input(\"\\nPlease enter a source sentence \"\n \"(pre-processed): \\n\")\n if not src_input.strip():\n break\n\n # every line has to be made into dataset\n test_data = _load_line_as_data(line=src_input)\n\n hypotheses = _translate_data(test_data)\n print(\"JoeyNMT: {}\".format(hypotheses[0]))\n\n except (KeyboardInterrupt, EOFError):\n print(\"\\nBye.\")\n break\n","sub_path":"joeynmt/prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":24328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"496509006","text":"##################################################################\n# Date : 2016-11-15\t\t\t\t\t\t\t\t\t\t\t\n# Author : Krittaphat Pugdeethosapol (krittaphat.pug@gmail.com)\n# Version : 1.0\t\t\t\t\t\t\n##################################################################\n\nimport numpy as np\nimport math\nimport time\nimport random\nimport pickle\nimport ConfigParser\n\nclass RBM:\n\tdef __init__(self, configFile, typeRBM):\n\t\tnp.seterr(all='ignore')\n\t\t# Reading Config file\n\t\tConfig = ConfigParser.ConfigParser()\n\t\tConfig.read(configFile)\n\t\tself.numHidden = int(Config.get(typeRBM, 'numHidden'))\n\t\tself.numVisible = int(Config.get(typeRBM, 'numVisible'))\n\t\tself.startLearningRate = float(Config.get(typeRBM, 'learningRate'))\n\t\tself.maxEpochs = int(Config.get(typeRBM, 'maxEpochs'))\n\t\tself.batchSize = int(Config.get(typeRBM, 'batchSize'))\n\t\tself.weightsObject = Config.get(typeRBM, 'weightsObject')\n\t\tself.hBiasObject = Config.get(typeRBM, 'hBiasObject')\n\t\tself.vBiasObject = Config.get(typeRBM, 'vBiasObject')\n\t\tself.screenObject = Config.get(typeRBM, 'screenObject')\n\t\t\n\t\tself.numpyRng = np.random.RandomState(random.randrange(0, 100))\n\n\t\t# Initial with zero mean and 0.01 std\n\t\ttry:\n\t\t\tself.weights = pickle.load(open(self.weightsObject, 'rb' ))\n\t\texcept:\n\t\t\tself.weights = np.asarray(self.numpyRng.normal(0, 0.01, size = (self.numVisible, self.numHidden)), dtype = np.float32)\n\n\t\t# Inital hidden Bias\n\t\ttry:\n\t\t\tself.hBias = pickle.load(open(self.hBiasObject, 'rb' ))\n\t\texcept:\n\t\t\tself.hBias = np.zeros(self.numHidden, dtype = np.float32)\n\n\t\t# Inital visible Bias\n\t\ttry:\n\t\t\tself.vBias = pickle.load(open(self.vBiasObject, 'rb' ))\n\t\texcept:\n\t\t\tself.vBias = np.zeros(self.numVisible, dtype = np.float32)\n\n\t\t# Initial Screen\n\t\ttry:\n\t\t\tself.screen = pickle.load(open(self.screenObject, 'rb' ))\n\t\texcept:\n\t\t\tself.screen = [1] * self.numVisible\n\n\t# Sigmoid\n\tdef sigmoid (self, x):\n\t\treturn 1.0 / (1 + np.exp(-x))\n\n\t# Calculate and return Positive hidden states and probabilities\n\tdef positiveProb (self, visible):\n\t\tposHiddenActivations = np.dot(visible, self.weights) + self.hBias\n\t\tposHiddenProbs = self.sigmoid(posHiddenActivations)\n\t\tposHiddenStates = posHiddenProbs > np.random.rand(visible.shape[0], self.numHidden)\n\t\treturn [posHiddenStates, posHiddenProbs]\n\n\t# Calculate and return Negative hidden states and probs\n\tdef negativeProb (self, hidden, k = 1):\n\t\tfor i in range (k):\n\t\t\tvisActivations = np.dot(hidden, self.weights.T) + self.vBias\n\t\t\tvisProbs = self.sigmoid(visActivations)\n\t\t\tvisProbs = visProbs * self.screen\n\t\t\thidden, hiddenProbs = self.positiveProb(visProbs)\n\t\treturn [visProbs, hiddenProbs]\n\n\t# Get hidden state\n\tdef getHidden (self, visible):\n\t\thiddenActivations = np.dot(visible, self.weights) + self.hBias\n\t\thiddenProbs = self.sigmoid(hiddenActivations)\n\t\thiddenStates = hiddenProbs > np.random.rand(visible.shape[0], self.numHidden)\n\t\treturn hiddenStates\n\n\t# Get visivle state\n\tdef getVisible (self, hidden):\n\t\tvisibleActivations = np.dot(hidden, self.weights.T) + self.vBias\n\t\tvisibleProbs = self.sigmoid(visibleActivations)\n\t\tvisibleProbs = visibleProbs * self.screen\n\t\treturn visibleProbs\n\n\t# Train RMB model\n\tdef train (self, data):\n\t\t# Screen some visible that always 0\n\t\tself.screen = [1] * self.numVisible\n\t\tfor column in range(data.shape[1]):\n\t\t\ttmpBias = sum(row[column] for row in data)\n\t\t\tif (tmpBias < 10):\n\t\t\t\tself.screen[column] = 0\n\t\tdata = data * self.screen\n\n\t\t# Clear the weight of some visibile that never appear and Add vBias\n\t\tself.weights = np.asarray(self.numpyRng.normal(0, 0.01, size=(self.numVisible, self.numHidden)), dtype=np.float32)\n\t\tself.weights = (self.weights.T * self.screen).T\n\t\tself.hBias = np.zeros(self.numHidden, dtype = np.float32)\n\t\tself.vBias = np.zeros(self.numVisible, dtype = np.float32)\n\n\t\tstart = time.time()\n\t\t# Start at CD1\n\t\tstep = 1\n\t\tlearningRate = self.startLearningRate\n\t\t# Loop for how many iterations\n\t\tfor epoch in range (self.maxEpochs): \n\t\t\tif (epoch != 0 and epoch%20 == 0):\n\t\t\t\tstep += 2\n\n\t\t\tstartTime = time.time()\n\n\t\t\t# Divide in to batch\n\t\t\ttotalBatch = math.ceil(data.shape[0]/self.batchSize)\n\t\t\tif data.shape[0]%self.batchSize != 0:\n\t\t\t\ttotalBatch += 1\n\n\t\t\t# Loop for each batch\n\t\t\tfor batchIndex in range (int(totalBatch)):\n\t\t\t\t# Get the data for each batch\n\t\t\t\ttmpData = data[batchIndex*self.batchSize: (batchIndex+1)*self.batchSize]\n\t\t\t\tnumExamples = tmpData.shape[0]\n\n\t\t\t\t# Caculate positive probs and Expectation for Sigma(ViHj) data\n\t\t\t\tposHiddenStates, posHiddenProbs = self.positiveProb(tmpData)\n\t\t\t\tposAssociations = np.dot(tmpData.T, posHiddenProbs)\n\t\t\t\tposHiddenBias = np.dot(np.ones(tmpData.shape[0]),posHiddenProbs)\n\t\t\t\tposVisibleBias = np.dot(tmpData.T, np.ones(tmpData.shape[0]).T)\n\n\t\t\t\t# Calculate negative probs and Expecatation for Sigma(ViHj) recon with k = step of gibs\n\t\t\t\tnegVisibleProbs, negHiddenProbs = self.negativeProb(posHiddenStates, k = step)\n\t\t\t\tnegAssociations = np.dot(negVisibleProbs.T, negHiddenProbs)\n\t\t\t\tnegHiddenBias = np.dot(np.ones(tmpData.shape[0]),negHiddenProbs)\n\t\t\t\tnegVisibleBias = np.dot(negVisibleProbs.T, np.ones(tmpData.shape[0]).T)\n\n\t\t\t\t# Update weight and Bias\n\t\t\t\tself.weights += learningRate*((posAssociations-negAssociations)/numExamples)\n\t\t\t\tself.hBias += learningRate*((posHiddenBias-negHiddenBias)/numExamples)\n\t\t\t\tself.vBias += learningRate*(((posVisibleBias-negVisibleBias)*self.screen)/numExamples)\n\n\t\t\t# Check error for each epoch\n\t\t\ttmpHidden = self.getHidden(data)\n\t\t\ttmpVisible = self.getVisible(tmpHidden)\n\t\t\ttmpVisible = tmpVisible * data\n\t\t\trmseError = math.sqrt(np.sum((data-tmpVisible)**2)/np.sum(data == 1))\n\t\t\ttotalTime = time.time()-startTime\n\n\t\t\tprint ('{0:7}Epoch : {1:5} Time : {2:15} Train RMSE : {3:10}'.format('INFO', epoch, totalTime, rmseError))\n\n\t\t# Save weights\n\t\tprint ('{0:7}TotalTime : {1}'.format('INFO', time.time()-start))\n\t\tpickle.dump(self.weights, open(self.weightsObject,'wb'))\n\t\tpickle.dump(self.hBias, open(self.hBiasObject,'wb'))\n\t\tpickle.dump(self.vBias, open(self.vBiasObject,'wb'))\n\t\tpickle.dump(self.screen, open(self.screenObject,'wb'))\t\n\nif __name__ == '__main__':\n\t# userRbm = RBM ('../data/Config.ini', 'UserRBM')\n\t# filePointer = open('../data/DocumentInfo.dat')\n\t# iterLines = iter(filePointer)\n #\n\t# # Read Data\n\t# print('Loading')\n\t# dataID = []\n\t# data = []\n\t# for lineNum, line in enumerate(iterLines):\n\t# \ttmp = [0] * userRbm.numVisible\n\t# \tID = line.split('::')\n\t# \tline = line.split('::')[1:]\n\t# \tfor doc in line:\n\t# \t\ttry:\n\t# \t\t\ttmp[int(doc)] = int(1)\n\t# \t\texcept:\n\t# \t\t\ttmpFalse = None\n\t# \tdata.append(tmp)\n\t# \tdataID.append(ID[0])\n\t# data = np.array(data)\n #\n\t# # data = np.array([[1,1,1,0,0,0],[1,0,1,0,0,0],[1,1,1,0,0,0],[0,0,1,1,1,0], [0,0,1,1,0,0],[0,0,1,1,1,0]])\n\t# # dataID = np.array([0,1,2,3,4,5])\n #\n\t# # Divide testing and training data\n\t# print('Training')\n\t# trainPart = 0.8\n\t# trainSize = int(trainPart * len(data))\n\t# train = np.array(data[:trainSize])\n\t# test = np.array(data[trainSize:])\n\t# userRbm.train(train, test)\n #\n\t# # Calculate all output\n\t# print('Recalling')\n\t# tmpHidden = userRbm.getHidden(data)\n\t# tmpVisible = userRbm.getVisible(tmpHidden)\n\t# # np.set_printoptions(threshold=np.nan)\n\t# # print(tmpHidden)\n #\n\t# print('Calculating')\n\t# f = open('../data/tmpOutputTableau.txt','w')\n\t# f2 = open('../data/tmpOutput.txt','w')\n\t# outputArray = {'key':'value'}\n\t# for i in range(tmpVisible.shape[0]):\n\t# \tmaxTop = 10\n\t# \tcountTop = 0\n\t# \ttmpValue = ''\n\t# \ttmpList = sorted(range(len(tmpVisible[i])), key=lambda k: tmpVisible[i][k], reverse=True)\n\t# \tfor j in range(tmpVisible.shape[1]):\n\t# \t\tif data[i][tmpList[j]] == 0:\n\t# \t\t\tif countTop > -1:\n\t# \t\t\t\ttmpValue += str(tmpList[j])\n\t# \t\t\t\tf.write('{0},{1},2\\n'.format(dataID[i],tmpList[j]))\n\t# \t\t\t\tif (countTop < maxTop-1):\n\t# \t\t\t\t\ttmpValue += '::'\n\t# \t\t\tcountTop = countTop + 1\n\t# \t\t\tif countTop == maxTop:\n\t# \t\t\t\tbreak\n\t# \toutputArray[dataID[i]] = tmpValue\n\t# \tf2.write('{0} {1}\\n'.format(dataID[i],tmpValue))\n\tthreshold = 0\n\tuserRBM = RBM('../data/Config.ini', 'UserRBMKCiteU')\n\n\tcountEX = 0\n\t# Read Data\n\tprint('Read Data')\n\tfilePointer = open('../data/UserInfo.dat')\n\titerLines = iter(filePointer)\n\trateEx = []\n\tidEx = []\n\tdataID = []\n\tdata = []\n\tdataTest = []\n\tfor lineNum, line in enumerate(iterLines):\n\t\ttmp = [0] * userRBM.numVisible\n\t\tID = line.split('::')[0]\n\t\tline = line.split('::')[1:]\n\t\texID = np.random.randint(len(line))\n\t\tfor offset, ele in enumerate(line):\n\t\t\tidTmp = ele\n\t\t\tif int(idTmp) < 16980:\n\t\t\t\ttmp[int(idTmp)] = int(1)\n\t\t\t\tif offset == exID:\n\t\t\t\t\tif int(0) >= threshold:\n\t\t\t\t\t\tprint('Ex {0} {1}'.format(lineNum, offset))\n\t\t\t\t\t\trateEx.append(0)\n\t\t\t\t\t\tidEx.append(int(idTmp))\n\t\t\t\t\t\ttmp[int(idTmp)] = int(0)\n\t\t\t\t\t\tif lineNum >= 4000:\n\t\t\t\t\t\t\tcountEX += 1\n\t\t\t\t\telse:\n\t\t\t\t\t\texID += 1\n\t\tif lineNum < 4000:\n\t\t\tdata.append(tmp)\n\t\telse:\n\t\t\tdataTest.append(tmp)\n\t\tdataID.append(ID)\n\tdata = np.array(data)\n\tdataTest = np.array(dataTest)\n\tprint (data.shape)\n\tprint (dataTest.shape)\n\tprint (countEX)\n\n\t# Train\n\tprint('Training')\n\ta = time.time()\n\tuserRBM.train(data)\n\tprint('Time = {0}'.format(time.time() - a))\n\n\t# Calculate all output\n\tprint('Recall')\n\ttmpHidden = userRBM.getHidden(dataTest)\n\ttmpVisible = userRBM.getVisible(tmpHidden)\n\ttmpVisible = np.array(tmpVisible)\n\n\tcountCheck = 0\n\tfor eachUser in range(tmpVisible.shape[0]):\n\t\ttmpVisibleStates = tmpVisible > np.random.rand(tmpVisible.shape[0], tmpVisible.shape[1])\n\t\tif tmpVisible[eachUser][idEx[eachUser]] > 0:\n\t\t\tcountCheck += 1\n\n\tprint('Accuracy = {0}%'.format((countCheck / float(dataTest.shape[0])) * 100))\n\ttmpVisible *= dataTest\n\trmseError = math.sqrt(np.sum((dataTest - tmpVisible) ** 2) / np.sum(dataTest == 1))\n\tprint ('Testing RMSE : {0}'.format(rmseError))\n\n\t# pickle.dump(outputArray, open('../data/tmpOutput.object','wb'))\n\tprint('Done')\n\n\n\n\n\n\n","sub_path":"sourceCode/RBM.py","file_name":"RBM.py","file_ext":"py","file_size_in_byte":9706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"183058156","text":"import requests\nfrom apartment.models import Apartment\nfrom house.models import House\nfrom realestate.models import RealEstate\nfrom building.models import Building\nfrom apartmentbuilding.models import ApartmentBuilding\n\ndef getSimilarRealEstate(request):\n\n print(request.GET)\n realestate = RealEstate.objects.get(id=request.GET['real_estate_id'])\n\n building = Building.objects.get(id=request.GET['building_id'])\n\n if (realestate.lng == 0.0 or realestate.lat == 0.0):\n url = 'https://maps.googleapis.com/maps/api/geocode/json'\n url_address = '?address={} {}, {}, {}'.format(\n realestate.addressStreet,\n realestate.addressNumber,\n realestate.addressCommune,\n realestate.addressRegion)\n url_key = '&key=AIzaSyDgwKrK7tfcd9kCtS9RKSBsM5wYkTuuc7E'\n response = requests.get(url+''+url_address+''+url_key)\n response_json = response.json()\n if len(response_json['results']) > 0:\n response_results = response_json['results'][0]['geometry']['location']\n realestate.lat = response_results['lat']\n realestate.lng = response_results['lng']\n realestate.save()\n\n if 'apartment_id' in request.GET:\n if request.GET['apartment_id'] != '':\n apartment_building = ApartmentBuilding.objects.get(id=request.GET['apartment_building_id'])\n apartment = Apartment.objects.get(id=request.GET['apartment_id'])\n if (apartment.bedrooms != None and\n apartment.bathrooms != None and\n apartment.usefulSquareMeters != None and\n apartment.terraceSquareMeters != None):\n\n apartments = Apartment.objects.filter(\n bedrooms=realestate.apartment.bedrooms,\n bathrooms=realestate.apartment.bathrooms,\n usefulSquareMeters__isnull=False,\n terraceSquareMeters__isnull=False,\n marketPrice__isnull=False).exclude(marketPrice=0)\n\n ds = []\n ni = 0\n for i, apt in enumerate(apartments):\n d1 = float(pow(apartment.usefulSquareMeters - apt.usefulSquareMeters,2))\n d2 = float(pow(apartment.terraceSquareMeters - apt.terraceSquareMeters,2))\n d3 = float(pow(apt.latlng[0] - realestate.latlng[0],2)+pow(apt.latlng[1] - realestate.latlng[1],2))\n ds.append([0,0])\n ds[i][0] = apt.pk\n ds[i][1] = d1+d2+d3\n\n ds = sorted(ds, key=lambda x: x[1])\n ins = [x[0] for x in ds]\n\n references = apartments.filter(pk__in=ins[0:20])\n return references\n else:\n print('nada')\n return []\n elif 'house_id' in request.GET:\n if request.GET['house_id'] != '':\n house = House.objects.get(id=request.GET['house_id'])\n house.bathrooms=3\n house.bedrooms=4\n house.builtSquareMeters=89\n house.terrainSquareMeters=90\n house.save\n if (house.bedrooms != None and\n house.bathrooms != None and\n house.builtSquareMeters != None and\n house.terrainSquareMeters != None):\n\n houses = House.objects.filter(\n bedrooms=house.bedrooms,\n bathrooms=house.bathrooms,\n builtSquareMeters__isnull=False,\n terrainSquareMeters__isnull=False,\n marketPrice__isnull=False)\n\n ds = []\n ni = 0\n print(houses)\n for i, hs in enumerate(houses):\n #o_price_per_terrain_surface = realestate.house.marketPrice/realestate.house.terrainSquareMeters\n #o_price_per_total_surface = realestate.house.marketPrice/realestate.totalSquareMeters\n #i_price_per_terrain_surface = house.marketPrice/house.terrainSquareMeters\n #i_price_per_total_surface = house.marketPrice/house.realestate_ptr.totalSquareMeters\n #f1 = float(pow(o_price_per_terrain_surface-i_price_per_terrain_surface,2))\n #f2 = float(pow(o_price_per_total_surface-i_price_per_total_surface,2))\n\n d1 = float(pow(house.terrainSquareMeters - hs.terrainSquareMeters,2))\n d2 = float(pow(house.builtSquareMeters - hs.builtSquareMeters,2))\n d3 = 1000000000.0*float(pow(hs.building.real_estate.latlng[0] - realestate.latlng[0],2)\n +pow(hs.building.real_estate.latlng[1] - realestate.latlng[1],2))\n\n ds.append([0,0])\n ds[i][0] = hs.pk\n ds[i][1] = d1+d2+d3\n ds = sorted(ds, key=lambda x: x[1])\n ins = [x[0] for x in ds]\n\n references = houses.filter(pk__in=ins[0:20])\n return references\n else:\n print('nothing')\n return []\n else:\n return []","sub_path":"web/appraisal/related.py","file_name":"related.py","file_ext":"py","file_size_in_byte":5148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"252273976","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom TestEnvironmentPackage.FetchEnvironment import getLoggedInPage\n\n\nclass Xpath_Util:\n \"\"\"Class to generate the xpaths\"\"\"\n\n def __init__(self):\n self.elements = None\n self.guessable_elements = ['input', 'button']\n self.known_attribute_list = ['id', 'name', 'placeholder', 'value', 'title', 'type', 'class']\n\n def generate_xpath(self, soup):\n \"generate the xpath\"\n result_flag = False\n try:\n for guessable_element in self.guessable_elements:\n self.elements = soup.find_all(guessable_element)\n for element in self.elements:\n if (not element.has_attr(\"type\")) or (element.has_attr(\"type\") and element['type'] != \"hidden\"):\n for attr in self.known_attribute_list:\n if element.has_attr(attr):\n locator = self.guess_xpath(guessable_element, attr, element)\n if len(driver.find_elements_by_xpath(locator)) == 1:\n result_flag = True\n print(locator.encode('utf-8'))\n break\n elif guessable_element == 'button' and element.getText():\n button_text = element.getText()\n if element.getText() == button_text.strip():\n locator = xpath_obj.guess_xpath_button(guessable_element, \"text()\",\n element.getText())\n else:\n locator = xpath_obj.guess_xpath_using_contains(guessable_element, \"text()\",\n button_text.strip())\n if len(driver.find_elements_by_xpath(locator)) == 1:\n result_flag = True\n print(locator.encode('utf-8'))\n break\n except Exception as e:\n print(\"Exception when trying to generate xpath for:%s\" % guessable_element)\n print(\"Python says:%s\" % str(e))\n\n return result_flag\n\n def guess_xpath(self, tag, attr, element):\n \"Guess the xpath based on the tag,attr,element[attr]\"\n # Class attribute returned as a unicodeded list, so removing 'u from the list and joining back\n if type(element[attr]) is list:\n element[attr] = [i.encode('utf-8') for i in element[attr]]\n element[attr] = ' '.join(element[attr])\n self.xpath = \"//%s[@%s='%s']\" % (tag, attr, element[attr])\n\n return self.xpath\n\n def guess_xpath_button(self, tag, attr, element):\n \"Guess the xpath for button tag\"\n self.button_xpath = \"//%s[%s='%s']\" % (tag, attr, element)\n\n return self.button_xpath\n\n def guess_xpath_using_contains(self, tag, attr, element):\n \"Guess the xpath using contains function\"\n self.button_contains_xpath = \"//%s[contains(%s,'%s')]\" % (tag, attr, element)\n\n return self.button_contains_xpath\n\n#-------START OF SCRIPT--------\nif __name__ == \"__main__\":\n print(\"Start of %s\" % __file__)\n\n # Initialize the xpath object\n xpath_obj = Xpath_Util()\n\n driver = webdriver.Chrome()\n\n driver.get('http://automationpractice.com/index.php')\n getLoggedInPage(driver)\n driver.find_element_by_xpath('//*[@id=\"center_column\"]/div/div[1]/ul/li[4]/a/span').click()\n #print(driver.current_url)\n\n url = driver.current_url\n page = driver.execute_script(\"return document.body.innerHTML\").encode('utf-8')\n soup = BeautifulSoup(page, 'html.parser')\n\n if xpath_obj.generate_xpath(soup) is False:\n print(\"No XPaths generated for the URL:%s\"%url)\n\n driver.quit()","sub_path":"TestEnvironmentPackage/sandbox.py","file_name":"sandbox.py","file_ext":"py","file_size_in_byte":4040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"585780234","text":"#-*- coding: utf-8 -*-\nimport database as db\n\n###########################################\n#LOGIC FOR MATCHES\n###########################################\n\n\nTYPE_BOTH_RESULTS = 'both_results'\nTYPE_WINNER_ONE_RESULT = 'winner_one_result'\nTYPE_WINNER_NO_RESULT = 'winner_no_result'\nTYPE_DRAW = 'draw'\n\nTYPE_DESCRIPTION = {\n TYPE_BOTH_RESULTS: 'Resultado exacto',\n TYPE_WINNER_ONE_RESULT: 'Ganador, un resultado',\n TYPE_WINNER_NO_RESULT: 'Ganador, ningún resultado',\n TYPE_DRAW: 'Empate, ningún resultado',\n}\n\ndef getAllTypes():\n return (\n TYPE_BOTH_RESULTS,\n TYPE_WINNER_ONE_RESULT,\n TYPE_WINNER_NO_RESULT,\n TYPE_DRAW,\n )\n\n\ndef save_all(idChampDate,obj, cur):\n if 'matchs' in obj:\n for itemMatch in obj[\"matchs\"]:\n itemMatch[\"id_championship_date\"] = idChampDate\n save(itemMatch, cur)\n\ndef save(obj, cur):\n if obj[\"id\"] == '':\n insert(obj,cur)\n else:\n update(obj,cur)\n\ndef disable_all(idDate, cur):\n cur.execute(\"\"\"\n update championship_match set\n is_disabled = true\n where id_championship_date = %s\n \"\"\", ( idDate, ) )\n\ndef update(obj, cur):\n if obj['goals_team1'] == '': obj['goals_team1'] = None\n if obj['goals_team2'] == '': obj['goals_team2'] = None\n\n cur.execute(\"\"\"\n update championship_match set\n goals_team1 = %(goals_team1)s,\n goals_team2 = %(goals_team2)s,\n is_disabled = false\n where id = %(id)s\n \"\"\", obj)\n\ndef insert(obj, cur):\n if obj['goals_team1'] == '': obj['goals_team1'] = None\n if obj['goals_team2'] == '': obj['goals_team2'] = None\n\n cur.execute(\"\"\"\n insert into championship_match(\n id_championship_date,\n id_team1,\n id_team2,\n goals_team1,\n goals_team2,\n date_start ,\n is_disabled\n )\n values(\n %(id_championship_date)s,\n %(id_team1)s,\n %(id_team2)s,\n %(goals_team1)s,\n %(goals_team2)s,\n %(date_start)s,\n false )\n RETURNING id\n \"\"\", obj)\n\n obj['id'] = cur.fetchone()[0]\n\n###########################################\n#LOGIC FOR POINTS\n###########################################\n\n#objMatch should contains: id, goals_team1, goals_team2\ndef save_points(objMatch, objTypePoints, cur):\n cur.execute('''\n select id, score_team1, score_team2\n from gambler_score\n where\n id_championship_match = %(id)s\n ''', objMatch )\n\n for row in db._cursor_fetchall_to_dict(cur):\n if row['score_team1'] == None: continue\n if row['score_team2'] == None: continue\n save_points_by_user(objTypePoints,objMatch, row, cur)\n\ndef save_points_by_user(objTypePoints,objMatch, objGamblerScore, cur):\n s1 = objMatch['goals_team1'] #real score for team 1\n s2 = objMatch['goals_team2'] #real score for team 2\n us1 = objGamblerScore['score_team1'] #user score for team 1\n us2 = objGamblerScore['score_team2'] #user score for team 2\n\n totalPoints = 0\n idType = None \n\n t = TYPE_BOTH_RESULTS\n if (t in objTypePoints) and totalPoints==0:\n if s1 == us1 and s2 == us2:\n totalPoints += objTypePoints[t]['points']\n idType = objTypePoints[t]['id']\n #end-if\n\n t = TYPE_WINNER_ONE_RESULT\n if _exists_winner(s1,s2) and (t in objTypePoints) and totalPoints==0:\n if (s1 == us1 or s2 == us2) and _who_wins(s1,s2) == _who_wins(us1,us2):\n totalPoints += objTypePoints[t]['points']\n idType = objTypePoints[t]['id']\n #end-if\n\n t = TYPE_WINNER_NO_RESULT\n if _exists_winner(s1,s2) and (t in objTypePoints) and totalPoints==0:\n if _who_wins(s1,s2) == _who_wins(us1,us2):\n totalPoints += objTypePoints[t]['points']\n idType = objTypePoints[t]['id']\n #end-if\n\n t = TYPE_DRAW\n if not _exists_winner(s1,s2) and (t in objTypePoints) and totalPoints==0:\n if us1 == us2:\n totalPoints += objTypePoints[t]['points']\n idType = objTypePoints[t]['id']\n\n cur.execute('''\n update gambler_score set\n points = %s,\n id_championship_date_points = %s\n where id = %s\n ''', (totalPoints, idType, objGamblerScore['id']) )\n\ndef _exists_winner(score1, score2):\n return score1 != score2\n\ndef _who_wins(score1,score2):\n who = 0\n if score1>score2: who=1\n if score2>score1: who=2\n return who\n","sub_path":"src/resources/model/match.py","file_name":"match.py","file_ext":"py","file_size_in_byte":4527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"351997109","text":"\"\"\"Test note API endpoints.\"\"\"\nfrom datetime import datetime\n\nfrom aiohttp import ClientSession\nimport pytest\nimport pytz\n\nfrom aiopinboard import API\nfrom aiopinboard.note import Note\n\nfrom tests.common import TEST_API_TOKEN, load_fixture\n\n\n@pytest.mark.asyncio\nasync def test_get_notes(aresponses):\n \"\"\"Test getting notes.\"\"\"\n aresponses.add(\n \"api.pinboard.in\",\n \"/v1/notes/list\",\n \"get\",\n aresponses.Response(text=load_fixture(\"notes_get_response.xml\"), status=200),\n )\n\n async with ClientSession() as session:\n api = API(TEST_API_TOKEN, session=session)\n\n notes = await api.note.async_get_notes()\n assert len(notes) == 1\n assert notes[0] == Note(\n \"xxxxxxxxxxxxxxxxxxxx\",\n \"Test\",\n \"xxxxxxxxxxxxxxxxxxxx\",\n pytz.utc.localize(datetime(2020, 9, 6, 5, 59, 47)),\n pytz.utc.localize(datetime(2020, 9, 6, 5, 59, 47)),\n 14,\n )\n","sub_path":"tests/test_note_api.py","file_name":"test_note_api.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"410092726","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n'''\nCreated on 2018/12/6\n@author: shimakaze-git\n'''\nimport os\nfrom datetime import datetime\n\nfrom sqlalchemy import Column, DateTime, String, text\nfrom sqlalchemy.dialects.mysql import INTEGER\nfrom sqlalchemy.exc import SQLAlchemyError\nfrom sqlalchemy.sql.functions import current_timestamp\n\nfrom rdb import Base, engine, session\n\nSQLITE3_NAME = \"./db.sqlite3\"\n\n\nclass Task(Base):\n __tablename__ = 'tasks'\n\n id = Column(\n INTEGER(unsigned=True),\n primary_key=True,\n autoincrement=True\n )\n name = Column(String(256))\n text = Column(String(256))\n created_at = Column(\n DateTime,\n default=datetime.now(),\n nullable=False,\n server_default=current_timestamp()\n )\n updated_at = Column(\n DateTime,\n default=datetime.now(),\n nullable=False,\n onupdate=datetime.now()\n )\n\n def __init__(self, name=None, text=None):\n self.name = name\n self.text = text\n\n @property\n def as_dict(self):\n return {\n 'id': self.id,\n 'name': self.name,\n 'text': self.text\n }\n\n @classmethod\n def read_list(cls):\n try:\n models = []\n with session.begin():\n query = session.query(cls)\n models = query.all()\n return models\n except SQLAlchemyError as e:\n print(e)\n\n @classmethod\n def read(cls, id):\n try:\n with session.begin():\n task = session.query(\n cls\n ).filter(\n cls.id == id\n ).first()\n return task\n except SQLAlchemyError as e:\n print(e)\n\n def create(self):\n try:\n with session.begin():\n session.add(self)\n except SQLAlchemyError as e:\n print(e)\n\n def update(self, id):\n try:\n task = self.read(id)\n if task:\n with session.begin():\n task.name = self.name\n task.text = self.text\n except SQLAlchemyError as e:\n print(e)\n\n def delete(self, id):\n try:\n task = self.read(id)\n if task:\n with session.begin():\n session.delete(task)\n except SQLAlchemyError as e:\n print(e)\n\n\nif __name__ == \"__main__\":\n path = SQLITE3_NAME\n if not os.path.isfile(path):\n # テーブル作成\n Base.metadata.create_all(engine)\n","sub_path":"step1/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"51385593","text":"import sys\nfrom bs4 import BeautifulSoup\nfrom .models import Customer, Account, Statement\nfrom typing import List\n\n\n\nclass HtmlParserBs4:\n \"\"\"A class used to parse html to objects.\"\"\"\n\n def __init__(self) -> None:\n pass\n\n def parse_customers_html_to_objects(self, customers_html: str, username: str) -> List[Customer]:\n \"\"\"Iterate over the customers' html, and create and return Customer objects.\"\"\"\n customers = list()\n soup = BeautifulSoup(customers_html, 'html.parser')\n custs = soup.find_all('ul', attrs={'class':'collection with-header'})\n for cust in custs:\n attributes = cust.find_all('li')\n name = ''\n address = ''\n emails = ''\n phones = ''\n i = 0\n for attribute in attributes:\n if i == 0:\n name = attribute.text\n elif i == 1:\n phones = attribute.text\n elif i == 2:\n emails = attribute.text\n elif i == 3:\n address = attribute.text\n i += 1\n customers.append(Customer(name, username, address, emails, phones))\n return customers\n\n def parse_accounts_html_to_objects(self, accounts_html: str) -> List[Account]:\n \"\"\"Iterate over the accounts' html, and create and return Account objects.\"\"\"\n accounts = list()\n soup = BeautifulSoup(accounts_html, 'html.parser')\n acts = soup.find_all('li', attrs={'class':'collection-item avatar'})\n for act in acts:\n name = act.find('span', attrs={'class':'title'}).text\n number_and_balance = act.find('p')\n number = number_and_balance.next_element.strip()\n balance = number_and_balance.find('span').text\n account_id = act.find('a')['href']\n account_id = account_id[account_id.index('/')+1:]\n accounts.append(Account(name, number, balance, account_id))\n return accounts\n\n def parse_statements_html_to_objects(self, statements_html: str) -> List[Statement]:\n \"\"\"Iterate over the statements' html, and create and return Statement objects.\"\"\"\n statements = list()\n soup = BeautifulSoup(statements_html, 'html.parser')\n thead = soup.find('thead')\n headers = thead.find_all('th')\n i = 0\n headerPositions = {}\n for header in headers:\n headerPositions[i] = header.text.lower()\n i += 1\n tbody = soup.find('tbody')\n stmts = tbody.find_all('tr')\n for stmt in stmts:\n attributes = stmt.find_all('td')\n date = ''\n amount = ''\n balance = ''\n concept = ''\n i = 0\n for attribute in attributes:\n # if the attribute is in the header,\n # user the header for reference\n if i in headerPositions:\n if headerPositions[i] == 'statement':\n concept = attribute.text\n elif headerPositions[i] == 'date':\n date = attribute.text\n elif headerPositions[i] == 'amount':\n amount = attribute.text\n elif headerPositions[i] == 'balance':\n balance = attribute.text\n # otherwise fall back to a set position\n else:\n if i == 0:\n concept = attribute.text\n elif i == 1:\n date = attribute.text\n elif i == 2:\n amount = attribute.text\n elif i == 3:\n balance = attribute.text\n i += 1\n statements.append(Statement(date, amount, balance, concept))\n return statements\n","sub_path":"server/u_test/html_parser_bs4.py","file_name":"html_parser_bs4.py","file_ext":"py","file_size_in_byte":3898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"357084329","text":"# -*- coding: utf-8 -*-\n# @Start_Time : 2018/6/25 10:42\n# @End_time: 2018/6/25 11:52\n# @Author : Andy\n# @Site : \n# @File : 67_add_binary_180625.py\n\n\"\"\"\nGiven two binary strings, return their sum (also a binary string).\n\nThe input strings are both non-empty and contains only characters 1 or 0.\n\nExample 1:\n\nInput: a = \"11\", b = \"1\"\nOutput: \"100\"\nExample 2:\n\nInput: a = \"1010\", b = \"1011\"\nOutput: \"10101\"\n\nInput:\n\"100\"\n\"110010\"\nOutput:\n\"1010000\"\nExpected:\n\"110110\"\n\"\"\"\n\n\nclass Solution(object):\n def addBinary(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: str\n \"\"\"\n if not len(a):\n return b\n if not len(b):\n return a\n\n def add_core(a, b):\n # for char in b:\n # if char != '1' or char != '0':\n # valid_input = False\n # return 0\n valid_input = True\n c = [0 for _ in range(len(a) + 1)]\n index_c = len(a)\n for i in range(len(b) - 1, -1, -1):\n ii = i + len(a) - len(b)\n if a[ii] != '1' and a[ii] != '0' or b[i] != '1' and b[i] != '0':\n valid_input = False\n return 0\n temp = int(a[ii]) + int(b[i]) + c[index_c]\n if temp > 1:\n c[index_c] = temp - 2\n c[index_c - 1] = 1\n else:\n c[index_c] = temp\n index_c -= 1\n for j in range(len(a) - len(b) - 1, -1, -1):\n # jj = j + len(b)\n if a[j] != '1' and a[j] != '0':\n valid_input = False\n return 0\n temp = int(a[j]) + c[index_c]\n if temp > 1:\n c[index_c] = temp - 2\n c[index_c - 1] = 1\n else:\n c[index_c] = temp\n index_c -= 1\n\n return valid_input, c\n\n # make sure that a is the longer string\n if len(a) < len(b):\n valid_input, c = add_core(b, a)\n else:\n valid_input, c = add_core(a, b)\n\n if not valid_input:\n return\n # return c\n return str(int(\"\".join(map(str, c))))\n\nprint(Solution().addBinary(\"1010\", \"1011\"))\nprint(Solution().addBinary(\"100\", \"110010\"))\n\n\n","sub_path":"LeetCode/1806/67_add_binary_180625.py","file_name":"67_add_binary_180625.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"141005726","text":"import contextlib\nimport os\nimport subprocess\n\nimport pytest\n\nfrom git.get_changed_subprojects import get_changed_files, \\\n get_changed_subprojects\n\nHERE = os.path.realpath(os.path.dirname(__file__))\nTEST_REPO = os.path.join(HERE, 'resources', 'test-repo')\nGIT_DIR_UNINITIALIZED = os.path.join(TEST_REPO, 'git')\nGIT_DIR = os.path.join(TEST_REPO, '.git')\n\n\n@contextlib.contextmanager\ndef in_test_repo():\n curr = os.getcwd()\n # print('DEBUG: changing to {}'.format(TEST_REPO))\n os.chdir(TEST_REPO)\n try:\n yield\n finally:\n # print('DEBUG: changing back to {}'.format(curr))\n os.chdir(curr)\n\n\ndef reset_repo():\n with in_test_repo():\n # print('DEBUG: resetting repo')\n subprocess.call('git reset --hard HEAD', shell=True)\n\n\ndef checkout_master():\n reset_repo()\n with in_test_repo():\n # print('DEBUG: checking out master')\n subprocess.call('git checkout master'.format(TEST_REPO), shell=True)\n\n\ndef checkout_new_branch():\n reset_repo()\n with in_test_repo():\n # print('DEBUG: checking out new-branch')\n subprocess.call('git checkout new-branch'.format(TEST_REPO), shell=True)\n\n\n@contextlib.contextmanager\ndef activated_test_repo():\n print('DEBUG: activating test repo')\n os.rename(GIT_DIR_UNINITIALIZED, GIT_DIR)\n try:\n checkout_master()\n yield\n finally:\n reset_repo()\n # print('DEBUG: deactivating test repo')\n os.rename(GIT_DIR, GIT_DIR_UNINITIALIZED)\n\n\n@pytest.mark.parametrize('cwd,base_commit,commit,project_dir,expected', [\n (TEST_REPO, 'master', 'HEAD', '.', {'a-change', 'aaaa-new'}),\n (TEST_REPO, 'master', 'HEAD', 'a-change', {'b-change', 'bbbb-new'}),\n (os.path.join(TEST_REPO, 'a-change'), 'master', 'HEAD', '..', {'a-change', 'aaaa-new'}),\n (os.path.join(TEST_REPO, 'a-change'), 'master', 'HEAD', '.', {'b-change', 'bbbb-new'}),\n (os.path.join(TEST_REPO, 'aa-no-change'), 'master', 'HEAD', '../a-change', {'b-change', 'bbbb-new'}),\n])\ndef test_main(cwd, base_commit, commit, project_dir, expected):\n with activated_test_repo():\n checkout_new_branch()\n os.chdir(cwd)\n\n # print('DEBUG: calling main')\n changed_files = get_changed_files(base_commit, commit)\n changed_subprojects = get_changed_subprojects(changed_files, project_dir)\n assert changed_subprojects == expected\n\n\n","sub_path":"packages/get-changed-subprojects/tests/functional/test_get_changed_subprojects.py","file_name":"test_get_changed_subprojects.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"190805691","text":"import os\n\nfrom kluctl.tests.test_base import DeploymentTestBase\nfrom kluctl.utils.yaml_utils import yaml_load_file\n\ncur_dir = os.path.dirname(__file__)\n\nclass TestTemplating(DeploymentTestBase):\n def get_jinja2_vars(self):\n return {\n 'a': 'a1',\n 'b': 'b1',\n 'include_var': 'd1',\n }\n\n def test_deployment_yml(self):\n with self.build_deployment('templating/test_deployment', self.get_jinja2_vars(), {'a': 'a2'}) as (d, c):\n self.assertEqual(len(d.includes), 2)\n self.assertListEqual(d.conf['tags'], ['a1', 'a2'])\n\n def test_include_var(self):\n with self.build_deployment('templating/test_deployment', self.get_jinja2_vars(), {'a': 'a2'}) as (d, c):\n self.assertEqual(d.includes[0].dir, os.path.join(cur_dir, 'test_deployment', 'd1'))\n\n def test_not_rendered_kustomize_resource(self):\n with self.render_deployment('templating/test_deployment', self.get_jinja2_vars(), {'a': 'a2'}) as c:\n y = yaml_load_file(os.path.join(c.tmpdir, 'd1/k1/not-rendered.yml'))\n self.assertEqual(y['a'], '{{ a }}')\n\n def test_rendered_kustomize_resource(self):\n with self.render_deployment('templating/test_deployment', self.get_jinja2_vars(), {'a': 'a2'}) as c:\n y = yaml_load_file(os.path.join(c.tmpdir, 'd1/k1/rendered.yml'))\n self.assertEqual(y['a'], 'a1')\n\n def test_load_template(self):\n with self.render_deployment('templating/test_deployment', self.get_jinja2_vars(), {'a': 'a2'}) as c:\n y = yaml_load_file(os.path.join(c.tmpdir, 'd1/k1/rendered.yml'))\n self.assertEqual(y['b'], 'test a1')\n self.assertEqual(y['c'], 'test a1')\n\n def test_rendered_kustomization_yml(self):\n with self.render_deployment('templating/test_deployment', self.get_jinja2_vars(), {'a': 'a2'}) as c:\n y = yaml_load_file(os.path.join(c.tmpdir, 'd1/k1/kustomization.yml'))\n self.assertListEqual(y['resources'], ['b1'])\n\n def test_import_no_context(self):\n with self.render_deployment('templating/test_import', self.get_jinja2_vars(), {}) as c:\n y = yaml_load_file(os.path.join(c.tmpdir, 'k1/rendered.yml'))\n self.assertEqual(y['a'], 'a1')\n\n def test_get_var(self):\n with self.render_deployment('templating/test_utils', self.get_jinja2_vars(), {}) as c:\n y = yaml_load_file(os.path.join(c.tmpdir, 'k1/get_var.yml'))\n self.assertEqual(y['test1'], 'default')\n self.assertEqual(y['test2'], 'default')\n self.assertEqual(y['test3'], 'a')\n\n def test_vars(self):\n with self.render_deployment('templating/test_vars', self.get_jinja2_vars(), {}) as c:\n y = yaml_load_file(os.path.join(c.tmpdir, 'k1/test.yml'))\n self.assertEqual(y['test1'], 'v1')\n self.assertEqual(y['test2'], 'f1')\n self.assertEqual(y['test3'], 'v1')\n self.assertEqual(y['test4'], 'b')\n","sub_path":"kluctl/tests/templating/test_templating.py","file_name":"test_templating.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"323541580","text":"from PySide2.QtCore import Signal, QTimer\nfrom PySide2.QtWidgets import (\n QWidget,\n QHBoxLayout,\n QToolButton,\n QLabel,\n QLineEdit,\n QSpacerItem,\n QSizePolicy,\n QFrame,\n)\n\nfrom chartify.settings import Settings\nfrom chartify.utils.utils import FilterTuple\n\n\nclass ViewTools(QFrame):\n \"\"\"\n A class to represent an application toolbar.\n\n \"\"\"\n\n structureChanged = Signal()\n textFiltered = Signal(tuple)\n expandRequested = Signal()\n collapseRequested = Signal()\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.setObjectName(\"viewTools\")\n view_tools_layout = QHBoxLayout(self)\n view_tools_layout.setSpacing(6)\n view_tools_layout.setContentsMargins(0, 0, 0, 0)\n\n btn_widget = QWidget(self)\n btn_layout = QHBoxLayout(btn_widget)\n btn_layout.setSpacing(0)\n btn_layout.setContentsMargins(0, 0, 0, 0)\n\n # ~~~~ Set up view buttons ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n self.tree_view_btn = QToolButton(self)\n self.tree_view_btn.setObjectName(\"treeButton\")\n self.tree_view_btn.setCheckable(True)\n self.tree_view_btn.setChecked(Settings.TREE_VIEW)\n\n self.collapse_all_btn = QToolButton(self)\n self.collapse_all_btn.setObjectName(\"collapseButton\")\n self.collapse_all_btn.setEnabled(Settings.TREE_VIEW)\n\n self.expand_all_btn = QToolButton(self)\n self.expand_all_btn.setObjectName(\"expandButton\")\n self.expand_all_btn.setEnabled(Settings.TREE_VIEW)\n\n self.filter_icon = QLabel(self)\n self.filter_icon.setObjectName(\"filterIcon\")\n\n btn_layout.addWidget(self.expand_all_btn)\n btn_layout.addWidget(self.collapse_all_btn)\n btn_layout.addWidget(self.tree_view_btn)\n\n # ~~~~ Line edit ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n self.variable_line_edit = QLineEdit(self)\n self.variable_line_edit.setPlaceholderText(\"variable...\")\n self.variable_line_edit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)\n self.variable_line_edit.setFixedWidth(100)\n\n self.key_line_edit = QLineEdit(self)\n self.key_line_edit.setPlaceholderText(\"key...\")\n self.key_line_edit.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)\n self.key_line_edit.setFixedWidth(100)\n\n self.units_line_edit = QLineEdit(self)\n self.units_line_edit.setPlaceholderText(\"units...\")\n self.units_line_edit.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)\n self.units_line_edit.setFixedWidth(50)\n\n spacer = QSpacerItem(1, 1, QSizePolicy.Expanding, QSizePolicy.Minimum)\n\n view_tools_layout.addWidget(self.filter_icon)\n view_tools_layout.addWidget(self.variable_line_edit)\n view_tools_layout.addWidget(self.key_line_edit)\n view_tools_layout.addWidget(self.units_line_edit)\n view_tools_layout.addItem(spacer)\n view_tools_layout.addWidget(btn_widget)\n\n # ~~~~ Timer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n # Timer to delay firing of the 'text_edited' event\n self.timer = QTimer()\n self.timer.setSingleShot(True)\n self.timer.timeout.connect(self.request_filter)\n\n # ~~~~ Filter actions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n self.variable_line_edit.textEdited.connect(self.on_text_edited)\n self.key_line_edit.textEdited.connect(self.on_text_edited)\n self.units_line_edit.textEdited.connect(self.on_text_edited)\n self.expand_all_btn.clicked.connect(self.expandRequested.emit)\n self.collapse_all_btn.clicked.connect(self.collapseRequested.emit)\n self.tree_view_btn.toggled.connect(self.tree_btn_toggled)\n\n def tree_requested(self):\n \"\"\" Check if tree structure is requested. \"\"\"\n return self.tree_view_btn.isChecked()\n\n def get_filter_tuple(self):\n \"\"\" Get current filter string. \"\"\"\n return FilterTuple(\n key=self.key_line_edit.text(),\n variable=self.variable_line_edit.text(),\n units=self.units_line_edit.text(),\n )\n\n def tree_btn_toggled(self, checked):\n \"\"\" Update view when view type is changed. \"\"\"\n self.tree_view_btn.setProperty(\"checked\", checked)\n\n # collapse and expand all buttons are not relevant for plain view\n self.collapse_all_btn.setEnabled(checked)\n self.expand_all_btn.setEnabled(checked)\n # store current state in settings\n Settings.TREE_VIEW = checked\n self.structureChanged.emit()\n\n def on_text_edited(self):\n \"\"\" Delay firing a text edited event. \"\"\"\n self.timer.start(200)\n\n def request_filter(self):\n \"\"\" Apply a filter when the filter text is edited. \"\"\"\n self.textFiltered.emit(self.get_filter_tuple())\n","sub_path":"chartify/ui/treeview_tools.py","file_name":"treeview_tools.py","file_ext":"py","file_size_in_byte":4839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"23126709","text":"\n\ndef main():\n module = AnsibleModule(argument_spec=dict(name=dict(type='str', required=True), state=dict(type='str', choices=['killed', 'once', 'reloaded', 'restarted', 'started', 'stopped']), enabled=dict(type='bool'), downed=dict(type='bool'), dist=dict(type='str', default='daemontools'), service_dir=dict(type='str', default='/service'), service_src=dict(type='str', default='/etc/service')), supports_check_mode=True)\n module.run_command_environ_update = dict(LANG='C', LC_ALL='C', LC_MESSAGES='C', LC_CTYPE='C')\n state = module.params['state']\n enabled = module.params['enabled']\n downed = module.params['downed']\n svc = Svc(module)\n changed = False\n orig_state = svc.report()\n if ((enabled is not None) and (enabled != svc.enabled)):\n changed = True\n if (not module.check_mode):\n try:\n if enabled:\n svc.enable()\n else:\n svc.disable()\n except (OSError, IOError) as e:\n module.fail_json(msg=('Could change service link: %s' % to_native(e)))\n if ((state is not None) and (state != svc.state)):\n changed = True\n if (not module.check_mode):\n getattr(svc, state[:(- 2)])()\n if ((downed is not None) and (downed != svc.downed)):\n changed = True\n if (not module.check_mode):\n d_file = ('%s/down' % svc.svc_full)\n try:\n if downed:\n open(d_file, 'a').close()\n else:\n os.unlink(d_file)\n except (OSError, IOError) as e:\n module.fail_json(msg=('Could change downed file: %s ' % to_native(e)))\n module.exit_json(changed=changed, svc=svc.report())\n","sub_path":"Data Set/bug-fixing-1/ff37e5364c7921a9db3415e328924f51ce5fa9ba--bug.py","file_name":"ff37e5364c7921a9db3415e328924f51ce5fa9ba--bug.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"56107865","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author : huxiansheng (you@example.org)\n\nimport pickle\nimport re\nimport time\nfrom Public.Logger import Logger\n\n\nclass WhidowsInfo():\n '''\n 电脑环境信息\n '''\n logger = Logger('WhidowsInfo').getlog()\n def root_coordinate(self,root):\n '''\n 窗口坐标\n 获取电脑的分辨率,并判断中间位置\n :param root: 主窗口控件\n :return:返回屏幕中间坐标\n '''\n ws = root.winfo_screenmmwidth()\n hs = root.winfo_screenheight()\n x = (ws/2)+400\n y = (hs/2)-250\n self.logger.info('当前屏幕分辨率为%sx%s,中间坐标为%s,%s'%(ws,hs,x,y))\n return x,y\n\n\n def get_window_time(self):\n '''\n 获取本地时间\n :return:\n '''\n now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) # 格式化当前时间\n return now\n\n\nclass Pickle():\n '''\n 二进制文件读取\n '''\n logger = Logger('Pickle').getlog()\n def load(self,file_path):\n '''\n 读取二进制文件\n :return:\n '''\n try:\n f = open(file_path, 'rb')\n file_datas = pickle.load(f) # 读出文件的数据个数\n f.close()\n except Exception as e:\n self.logger.error('读取二进制文件【%s】失败,无法自动填写账号密码,错误信息:%s'%(file_path,e))\n file_datas =False\n return file_datas\n\n\n def dump(self,obj,path):\n '''\n 写入文件\n :param obj: 写入文件的对象\n :param path: 路劲\n :return:\n '''\n try:\n f = open(path, 'wb') # 以写模式打开二进制文件\n pickle.dump(obj,f)\n f.close()\n return True\n except Exception as e:\n self.logger.error('写入二进制文件【%s】失败,错误异常:%s' % (path, e))\n return False\n\n\nclass Str_manager():\n logger = Logger('Str_manager').getlog()\n # 检验字符串是否包含汉字\n def check_contain_chinese(self,check_str):\n '''\n 判断传入字符串是否包含中文\n :param word: 待判断字符串\n :return: None:不包含中文 False:输入的不是字符串\n '''\n zh_pattern = re.compile(u'[\\u4e00-\\u9fa5]+')\n try:\n match = zh_pattern.search(check_str)\n return match\n except:\n return False\n","sub_path":"Public/Common.py","file_name":"Common.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"210143601","text":"import json\nimport random\nimport sys\nfrom datetime import datetime\nfrom django.core import serializers\nfrom django.core.management import setup_environ\nfrom os.path import dirname, abspath, basename\n\nsys.path.insert(0, dirname(dirname(abspath(__file__))))\nimport settings\n\nsetup_environ(settings)\n\nimport free103.artists.models as am\nimport free103.works.models as wm\nimport free103.events.models as em\nimport wgxc.schedule.models as sm\n\n\n# set up the serializer\njsonify = serializers.get_serializer('json')().serialize\n\n# get the ID map\ntry:\n imj = open('id_map.json')\n id_map = json.load(imj)\n imj.close()\nexcept IOError:\n id_map = {}\n\n# open the bulk file for appending\nbulk = open('bulk.json', 'a')\n\ndef get_main(obj_id, model):\n obj = model.objects.get(id=obj_id)\n if model == wm.Work:\n return obj.title\n if model == am.Artist:\n return obj.display_name\n if model == em.Event:\n return obj.name\n if model == sm.Show:\n return obj.title\n if model == em.Location:\n return obj.name\n\n# base32 according to http://www.crockford.com/wrmg/base32.html\nalphabet = '0123456789abcdefghjkmnpqrstvwxyz';\n\ndef generate_id():\n id = []\n for x in range(6):\n id.append(random.choice(alphabet))\n return ''.join(id);\n\ndef get_existing_id(datatype, old_id):\n if datatype not in id_map:\n sys.stdout.write('[%s datatype not in map] ' % datatype)\n return\n new_id = id_map[datatype].get(unicode(old_id))\n if new_id:\n return new_id\n sys.stdout.write('[%s %s not in map] ' % (datatype, old_id))\n\nclass FancyDict(dict):\n 'dict with extra spice'\n def __init__(self, *args, **kwargs):\n dict.__init__(self, *args, **kwargs)\n # copy keys so we can add and delete\n keys = self.keys()[:]\n for key in keys:\n if self.get(key):\n if key.startswith('related_'):\n new_key = key.split('_')[1]\n self.rename(key, new_key)\n else: # convert to camelCase\n new_key = ''.join(x.capitalize() for x in key.split('_'))\n new_key = new_key[0].lower() + new_key[1:]\n self.rename(key, new_key)\n else:\n del self[key]\n\n def rename(self, key, new_key):\n val = self.get(key)\n if val:\n del self[key]\n self[new_key] = val\n\n def link(self, key, datatype, model):\n if key in self:\n rels = []\n for old_id in self[key]:\n new_id = get_existing_id(datatype, old_id)\n if new_id:\n rels.append({'id': new_id, 'main': get_main(old_id, model)})\n self[key] = rels\n\nMIMETYPE_MAP = {}\nFILETYPE_MAP = {}\nfor mimetype in wm.MimeType.objects.all():\n MIMETYPE_MAP[mimetype.id] = mimetype.name\n for media_type in ('image', 'audio', 'video'):\n if mimetype.name.startswith(media_type):\n FILETYPE_MAP[mimetype.name] = media_type\n if mimetype.name == 'application/pdf':\n FILETYPE_MAP[mimetype.name] = 'text'\n\ndef artistLink(doc, field):\n if field in doc:\n #print doc[field]\n artists = am.Artist.objects.filter(id__in=doc[field])\n del doc[field]\n for a in artists:\n if a.types.filter(id=1):\n dt = 'artist'\n elif a.types.filter(id=2):\n dt = 'collaborator'\n else: # TODO: handle wgxc artist types\n continue\n new_id = get_existing_id(dt, a.id)\n brief = {'id': new_id, 'main': a.display_name}\n rel = dt + 's'\n if rel in doc:\n doc[rel].append(brief)\n else:\n doc[rel] = [brief]\n\nSITES = [None, 'transmissionarts', 'wgxc']\n\ndef bulk_load(query_set, datatype, munge):\n if datatype not in id_map:\n id_map[datatype] = {}\n\n # TODO jsonify each record manually to avoid these shenanigans\n records = json.loads(jsonify(query_set))\n\n count = 0\n for record in records:\n sys.stdout.write('%s ' % record['pk'])\n doc = FancyDict(record['fields'])\n\n # get ID for new system\n if doc.get('newId'):\n new_id = doc['newId']\n del doc['newId']\n elif id_map[datatype].get(unicode(record['pk'])):\n new_id = id_map[datatype].get(unicode(record['pk']))\n else:\n sys.stdout.write('generating new ID ')\n new_id = generate_id()\n # stick the new_id in the map in case it isn't there already\n id_map[datatype][record['pk']] = new_id\n doc['oldId'] = record['pk']\n doc['id'] = new_id\n doc['type'] = datatype\n doc['timestamp'] = datetime.now().isoformat()\n artistLink(doc, 'artists')\n if datatype in ['artist', 'collaborator']:\n artistLink(doc, 'seeAlso')\n doc.link('works', 'work', wm.Work)\n doc.link('locations', 'location', em.Location)\n doc.link('shows', 'show', sm.Show)\n\n if 'sites' in doc:\n doc['sites'] = [SITES[x] for x in doc['sites']]\n\n # munge doc\n munge(doc)\n\n # after munge since location deletes them\n doc.link('events', 'event', em.Event)\n\n # archive files\n if 'files' in doc:\n for file_id in doc['files']:\n af = wm.ArchiveFile.objects.get(id=file_id)\n dt = FILETYPE_MAP.get(af.mimetype.name)\n if not dt:\n continue\n new_id = get_existing_id(dt, file_id)\n if new_id:\n main = af.title or basename(unicode(af.url)) or basename(unicode(af.upload))\n brief = {'id': new_id, 'main': main}\n if dt in doc:\n doc[dt].append(brief)\n else:\n doc[dt] = [brief]\n del doc['files']\n\n # stick it in the file\n bulk.write('{\"index\": {\"_index\": \"free103\", \"_type\": \"%s\", \"_id\": \"%s\"}}\\n' % \n (doc['type'], doc['id']))\n json.dump(doc, bulk)\n bulk.write('\\n')\n\n count += 1\n sys.stdout.write('\\nTotal: %s\\n' % count)\n\n # write out updated id_map\n id_map_fh = open('id_map.json', 'w')\n json.dump(id_map, id_map_fh)\n id_map_fh.close()\n","sub_path":"free103/utils/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":6332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"514808625","text":"from datetime import datetime\n\nfrom flask import jsonify, render_template\n\nfrom main import app\nfrom mongo_test_history import update_data_db\nfrom storage import Storage\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/api/v1.0/test', methods=['GET'])\ndef test():\n storage = Storage()\n client = storage.get_client()\n collection = client.lanscan.topology\n\n update_data_db(collection, '10.1.1.1', '00:00:00:00:00', 'test', datetime.now)\n\n client.close()\n\n return \"OK\"\n\n\n@app.route('/api/v1.0/all', methods=['GET'])\ndef get_all():\n storage = Storage()\n client = storage.get_client()\n collection = client.lanscan.topology\n\n try:\n data = list(collection.aggregate([{\n '$project': {\n '_id': 0,\n 'ip': 1,\n 'dns': {\n '$arrayElemAt': ['$dns.dns', -1]\n },\n 'mac': {\n '$arrayElemAt': ['$mac.mac', -1]\n }\n }\n }]))\n except:\n data = \"Error\"\n\n client.close()\n\n return jsonify(data)\n","sub_path":"app/v1_0.py","file_name":"v1_0.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"561698215","text":"import requests\nimport json\nimport pymysql\nimport datetime\nimport csv\n\nclass dongqiudi_vidio():\n\n#初始化数据库\n def __init__(self):\n dbparams = {\n 'host': '39.100.245.203',\n 'port': 3306,\n 'user': \"root\",\n 'password': \"asus123836.\",\n 'database': \"scrapy\",\n 'charset': 'utf8mb4'\n }\n self.conn = pymysql.connect(**dbparams)\n self.cursur = self.conn.cursor()\n\n def vidio(self,url):\n self.url = url\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'\n }\n\n response = requests.get(headers=headers, url=self.url)\n response.encoding = 'utf-8'\n return response.text\n\n def get_data(self,url):\n html = dongqiudi_vidio.vidio(self,url=url)\n next_url = json.loads(html).get('next')\n print(next_url)\n datas = json.loads(html).get('articles')\n for data in datas:\n item = {}\n item['id'] = data.get('id')\n item['title'] = data.get('title')\n item['thumb'] = data.get('thumb')\n item['mp4'] = data.get('video_info')['video_src']\n item['pub_time'] = data.get('published_at')\n item['avatar'] = 'https://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83eqXEgVS72kWucKk8XibicQlspRySDMWicCBfibgEbYQHpHbicVOjp7vlXIib0AxPicJ65gstwThJkEibgRTTQ/132'\n item['nickname'] = 'توپ بىلگە'\n id = str(item['id'])\n if dongqiudi_vidio.virdect(self,id=id):\n print(item)\n # dongqiudi_vidio.save_vidio(self,item=item)\n # dongqiudi_vidio.save_url(self, id=id)\n\n dongqiudi_vidio.get_data(self,url=next_url)\n\n# 保存id\n def save_url(self,id):\n list = []\n with open('dongqiudi.csv', 'a', encoding='utf-8', newline='') as fp:\n list.append(id)\n writer = csv.writer(fp)\n writer.writerow(list)\n\n# 判断id\n def virdect(self,id):\n with open('dongqiudi.csv', mode='r', encoding='cp936') as fp:\n data = fp.read()\n if id in data:\n return False\n else:\n return True\n\n\n def save_vidio(self,item):\n SQL = \"\"\"\n INSERT INTO dongqiudi_vidio (id, title, thumb, mp4, pub_time, avatar, nickname)\n values (%s,%s,%s,%s,%s,%s,%s)\n \"\"\"\n\n self.cursur.execute(SQL, (item['id'], item['title'], item['thumb'], item['mp4'],item['pub_time'], item['avatar'],item['nickname']))\n self.conn.commit()\n print('Insert success for nur_index')\n\n\nif __name__ == '__main__':\n url = 'https://api.dongqiudi.com/v3/archive/app/tabs/getlists?id=100043&platform=android&version=220'\n dic = dongqiudi_vidio().get_data(url=url)\n\n\n\n","sub_path":"spider/nur_news/dongqiudi_vidio.py","file_name":"dongqiudi_vidio.py","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"322679723","text":"\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\nbooks = []\n# for i in range(3):\n\nurl = 'http://books.toscrape.com/index.html'\nhost = \"http://books.toscrape.com\"\nr = requests.get(url)\nsoup = BeautifulSoup(r.content, \"html.parser\")\ncontent = soup.find_all(\"article\", class_=\"product_pod\")\n\nfor product_pod in content:\n books.append({\n\n \"titres\": product_pod.find(\"h3\").text,\n \"prix\": product_pod.find(\"p\", class_=\"price_color\").text,\n \"links\": host + product_pod.find(\"a\").get(\"href\"),\n \"images\": host + product_pod.find(\"img\", class_=\"thumbnail\").get(\"src\"),\n\n })\n\nprint(books)\n\ndf = pd.DataFrame(books)\ndf.to_csv(\"books_1.csv\")\ndf.to_excel(\"books.xlsx\")\nprint(\"saved to file\")\n","sub_path":"P2_02_codesource/books_2.py","file_name":"books_2.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"245364460","text":"\"\"\"\n@arthor:金龙\n@school:hrbust\n@depart:computer\n@file: b_私有方法.py\n@time: 2017/10/4 10:43\n@describe:\n\"\"\"\n\n\nclass Cat:\n # __两个下划线表示私有方法\n def __send_msg(self):\n print('正在发送短信')\n\n def send_msg(self, new_money):\n if new_money > 10:\n self.__send_msg()\n else:\n print('余额不足')\n\n\ncat = Cat()\ncat.send_msg(100)\n","sub_path":"day02/b_私有方法.py","file_name":"b_私有方法.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"603167527","text":"import matplotlib\nmatplotlib.use('Agg')\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import trapz\nfrom matplotlib.colors import LogNorm\nfrom tristan_funcs import load_particle_edotv_withtcs\nimport os\n\n\n\nplt.rcParams['mathtext.fontset'] = 'stix'\nplt.rcParams['font.family'] = 'STIXGeneral'\nplt.rcParams.update({'font.size': 14})\n\n#inputs\n\n#mypath = \"edotv_prtls/bguide.3_untriggered_hightimeres_latetime/tcs_cut/\"\nmypath = \"edotv_prtls/bguide.3_triggered_hightimeres_nothresh/tcs_cut/\"\n\n\n\n#open all .txt files in directory pointed to by filepath\nfilelist = os.listdir(mypath)\n#print(filelist)\n\n\n#for testing purposes\n#filelist = [\"edotv_prtls/bguide.3_untriggered_hightimeres_latetime/1.txt\"]\n\nwpar_list = []\nfinalgam_list = []\n\nfor filename in filelist:\n fullname = mypath + filename\n #testing\n #print(fullname)\n \n filesize = os.stat(fullname).st_size\n if filesize == 0:\n pass\n else:\n \n\n d = load_particle_edotv_withtcs(fullname)\n tcs = d['tcs']\n \n tlow=0 #change this if you want to narrow window that calculation is done in\n tup = -1\n\n #finalgam = d['gamma'][-1]\n #indexing will only work as long as we save prt info from the first timestep on, which we do, but just something to be careful about not to change\n t_arr = np.array(d['time'])[tlow:tup]\n u_arr = np.array(d['u'])[tlow:tup]\n v_arr = np.array(d['v'])[tlow:tup]\n w_arr = np.array(d['w'])[tlow:tup]\n bx_arr = np.array(d['bx'])[tlow:tup]\n by_arr = np.array(d['by'])[tlow:tup]\n bz_arr = np.array(d['bz'])[tlow:tup]\n ex_arr = -np.array(d['ex'])[tlow:tup]\n ey_arr = -np.array(d['ey'])[tlow:tup]\n ez_arr = -np.array(d['ez'])[tlow:tup]\n gamma_arr = np.array(d['gamma'])[tlow:tup]\n finalgam = d['finalgam']\n #print('tcs in output units is : ',tcs)\n\n\n bmag = np.sqrt(bx_arr**2 + by_arr**2 + bz_arr**2)\n\n unitbx = bx_arr / bmag\n unitby = by_arr / bmag\n unitbz = bz_arr / bmag\n \n #unit vector in b direction is (unitbx, unitby, unitbz) \n\n #dividing momenta by gamma to turn them into velocities\n u_arr /= gamma_arr\n v_arr /= gamma_arr\n w_arr /= gamma_arr\n\n\n edotv_tot = u_arr*ex_arr + v_arr*ey_arr + w_arr*ez_arr\n \n \n\n upar = u_arr*unitbx + v_arr*unitby + w_arr*unitbz \n epar = ex_arr*unitbx + ey_arr*unitby + ez_arr*unitbz \n epar_upar = upar*epar \n eperp_uperp = edotv_tot - epar_upar\n edotv_par_cumulative = [] \n edotv_perp_cumulative = [] \n edotv_tot_cumulative = [] \n for i in range(np.size(eperp_uperp)): \n tmp_par = trapz(epar_upar[0:i]) \n tmp_perp = trapz(eperp_uperp[0:i]) \n tmp_tot = trapz(edotv_tot[0:i]) \n edotv_par_cumulative.append(tmp_par) \n edotv_tot_cumulative.append(tmp_tot) \n edotv_perp_cumulative.append(tmp_perp)\n\n \n #testing\n #plt.plot(t_arr, edotv_par_cumulative,color=\"Blue\")\n #plt.plot(t_arr, edotv_perp_cumulative,color=\"Red\")\n #plt.plot(t_arr, edotv_tot_cumulative,color=\"Black\")\n #plt.savefig('testing_reading.png')\n \n \n wpar_frac = edotv_par_cumulative[-1]/edotv_tot_cumulative[-1]\n #print('wpar_frac : ', wpar_frac)\n #print('finalgam : ', finalgam)\n wpar_list.append(wpar_frac)\n finalgam_list.append(finalgam)\n\n\n\nmaxgam = max(finalgam_list)\nmingam = min(finalgam_list)\n\nbinnum = 40\nwpar_bins = np.linspace(-2,1,binnum)\ngambins = np.linspace(min(finalgam_list),max(finalgam_list)+1,binnum)\n\n\n \n#plt.scatter(wpar_list,finalgam_list)\n#plt.xlim(0,1.1)\n#plt.savefig('testing_scatter.png')\n\n#problem is that there are some artificially low values of wpar (down to -60 ish), so when we cut up the bins this skews the entire distribution\n\n\n\n\n#not putting bins in by hand\n#H,xedges,yedges=np.histogram2d(wpar_list,finalgam_list,bins=40)\n \n#H,xedges,yedges = np.histogram2d(wpar_list,finalgam_list,bins=[wpar_bins,gambins])\n#H,xedges,yedges = np.histogram2d(wpar_list,finalgam_list,bins=40,range=[[0,1],[mingam,maxgam]]) \n#plt.yscale('log')\n\n#print(H)\n#extent_list = [int(wpar_bins[0]),int(wpar_bins[-1]),int(gambins[0]),int(gambins[-1])]\n#extent_list = [xedges[0],xedges[-1],yedges[0],yedges[-1]]\n#print('bins : ', extent_list)\n\nplt.hist2d(wpar_list,finalgam_list,bins=40,range=[[0,1],[mingam,maxgam]],norm=LogNorm(),cmin=2,cmax=2001,alpha=1)\n\n#log scale on gamma\n#plt.hist2d(wpar_list, np.log10(finalgam_list),bins=40,range=[[0,1],[np.log10(mingam),np.log10(maxgam)]],norm=LogNorm())\n\nplt.colorbar(label='$N_{e}$')\n#plt.imshow(H,origin='lower',extent=extent_list,aspect=\"auto\")#,extent=extent_list,aspect=\"auto\")\n#plt.yscale('log')\nplt.xlim(0,1)\nplt.xlabel('$W_{||}/W_{tot}$')\nplt.ylabel('$\\gamma_{final}$')\n#plt.ylabel('$\\log{\\gamma_{final}}$')\n\nplt.savefig('wpar_trig_loghist.png')\n\nplt.close()\n","sub_path":"tcs_epar_hist.py","file_name":"tcs_epar_hist.py","file_ext":"py","file_size_in_byte":5410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"601040733","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 5 19:31:21 2020\n\n@author: Christoffer\n\"\"\"\n\nimport os\nimport json\n\ndef remove(listobj):\n cnt = 0\n objectList = []\n for elements in listobj:\n if elements == \" {\\n\":\n objectList.append(cnt)\n if elements == \" },\\n\" or elements == \" }\\n\":\n objectList.append(cnt)\n cnt = cnt + 1\n return(objectList)\n\ndef replace(listobj):\n #listobj = [element.replace('=', ':') for element in listobj]\n listobj = [element.strip() for element in listobj]\n\n return(listobj)\n\ndef dictify(listobj):\n newDict = {}\n lastKey = ''\n concValue = ''\n closingBracket = True\n cnt = 0\n cnt2 = 0\n tmpArray = []\n tmpDict = {}\n separator = 0\n# for elements in listobj:\n# #print(elements)\n# if elements.find('=') > 0 and closingBracket == True:\n# #print(\"1\")\n# separator = elements.find('=')\n# key = elements[0:separator]\n# value = elements[separator+1:len(elements)]\n# newDict[key] = value\n# lastKey = key\n# concValue = ''\n# cnt = 0\n# elif elements.find('{') >= 0 and cnt2 > 0:\n# #print('2')\n# closingBracket = False\n# cnt = cnt + 1\n# concValue = concValue + elements + '\\n'\n# elif elements.find('}') >= 0:\n# #print('3')\n# cnt = cnt -1\n# if cnt == 0:\n# closingBracket = True\n# concValue = concValue + elements + '\\n'\n# #print(concValue)\n# #print(lastKey)\n# newDict[lastKey] = concValue\n# else:\n# #print(\"4\")\n# concValue = concValue + elements + '\\n'\n# #print(concValue)\n# cnt2 = cnt2 + 1\n \n\n for x in range(len(listobj)):\n if x > 0:\n #Checks if the value is another table\n if listobj[x] == '{':\n print('trigg')\n print(x)\n tmpArray = []\n tmpDict = {}\n closingBracket = False\n \n for y in range(x +1, len(listobj)):\n if listobj[y] == '}' or listobj[y] == '},':\n print('break: ' + str(y))\n print(listobj[y])\n break\n else:\n #print('append: ' + str(y))\n #print(listobj[y])\n tmpArray.append(listobj[y])\n print(tmpArray)\n #newDict[lastKey] = dictify(tmpArray)\n closingBracket = True\n continue\n #Checks if the line is a \"normal\" key/value pair, no nested tables\n elif listobj[x].find('=') > 0 and not (listobj[x].find('{') >= 0 and listobj[x].find('=') >= 0 and listobj[x].find('}') >= 0):\n separator = listobj[x].find('=')\n key = listobj[x][0:separator]\n value = listobj[x][separator+1:len(listobj[x])]\n newDict[key] = value\n lastKey = key\n concValue = ''\n cnt = 0\n #Checks if the line is a nested table\n elif listobj[x].find('{') >= 0 and listobj[x].find('=') >= 0 and listobj[x].find('}') >= 0:\n #{ size = 64, filename = \"__base__/graphics/icons/mip/coal.png\", scale = 0.25, mipmap_count = 4 },\n #['{ size = 64', ' filename = \"__base__/graphics/icons/mip/coal-1.png\"', ' scale = 0.25', ' mipmap_count = 4 }', '']\n #print('test3')\n #newDict = {}\n tmpArray = []\n tmpArray = listobj[x].split(',')\n tmpArray = [element.replace('{', '') for element in listobj]\n tmpArray = [element.replace('}', '') for element in listobj]\n #newDict[lastKey] = dictify(tmpArray)\n \n #print(tmpArray)\n separator = listobj[x].find('=')\n key = listobj[x][0:separator]\n value = listobj[x][separator+1:len(listobj[x])]\n\n elif listobj[x].find('=') > 0 and not (listobj[x].find('{') >= 0 and listobj[x].find('=') >= 0 and listobj[x].find('}') >= 0):\n print('trigg???')\n separator = listobj[x].find('=')\n key = listobj[x][0:separator]\n value = listobj[x][separator+1:len(listobj[x])]\n newDict[key] = value\n lastKey = key\n concValue = ''\n cnt = 0\n elif (listobj[x].find('{') >= 0 and listobj[x].find('=') >= 0 and listobj[x].find('}') >= 0):\n print('test')\n return(newDict) \n\n\ndef removeExtend(listobj):\n if listobj[0] == 'data:extend(\\n':\n listLen = len(listobj)\n listobj.pop(listLen-1)\n listobj.pop(listLen-2)\n listobj.pop(0)\n listobj.pop(0)\n \n return(listobj)\n \ndef writeDictToLuaFile(listobj):\n file_name = r\"C:\\Users\\Christoffer\\Documents\\test2.lua\"\n file = open(file_name, 'w') \n \n file.write('data:extend(\\n')\n file.write('{\\n')\n \n listLen = len(listobj)\n \n for x in range(listLen):\n file.write(' {\\n')\n for key, value in listobj[x].items():\n #print(value)\n file.write(' ' + key + '=' + value + '\\n')\n if x >= (listLen-1):\n file.write(' }\\n')\n else:\n file.write(' },\\n')\n file.write('}\\n')\n file.write(')')\n\n \n\npath = r\"C:\\Users\\Christoffer\\Documents\"\npath = path + r\"\\demo-turret.lua\"\n\nfile = open(path, 'r')\nfileLines = file.readlines()\nfile.close()\n\nfileLen = len(fileLines)\n\nnewFile = removeExtend(fileLines)\nlistOfIndexes = remove(newFile)\nnewFile = replace(newFile)\nelements = len(listOfIndexes) / 2\n\nitemList = []\nfor i in range(int(elements)):\n itemList.append(dictify(newFile[listOfIndexes[(i*2)]:listOfIndexes[(i*2)+1]+1]))\n\n\nnewlist = newFile[listOfIndexes[0]:listOfIndexes[1]+1]\n#newDict = dictify(newlist)\n#writeDictToLuaFile(itemList)\n\n\n\n\n#file_name = r\"C:\\Users\\Christoffer\\Documents\\test2.lua\"\n#file = open(file_name, 'w') \n#\n#for line in fileLines:\n# file.write(line)\n#\n#\n#file.close()\n\n\n\n\n \n \n","sub_path":"t2.py","file_name":"t2.py","file_ext":"py","file_size_in_byte":6217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"305528072","text":"import smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.MIMEImage import MIMEImage\nfrom email.mime.text import MIMEText\n\nmsg = MIMEMultipart()\n\nsenha = \"gama2018\"\nmsg['From'] = \"projetodemonitoramento@gmail.com\"\nmsg['To'] = \"magalhaesrafael07@gmail.com\"\nmsg['Subject'] = \"Sistema de Monitoramento\"\n\nmsg.attach(MIMEImage(file('/home/pi/Monitoramento/imagem0.jpg'.read())))\n\nserver = smtplib.SMTP('smtp.gmail.com: 587')\nserver.starttls()\nserver.login(msg['From'], senha)\nserver.sendmail(msg['From'], msg['To'], msg.as_string())\nserver.quit()\n\nprint (\"Email enviado com sucesso para %s:\" %(msg['To']))\n","sub_path":"Monitoramento/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"295481913","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef load_tune(filename, tune_length):\n \"\"\"\n Load in information about notes and their\n onset times from a text file\n Parameters\n ----------\n filename: string\n Path to file with the tune\n tune_length: float\n Length, in seconds, of the tune\n \n Returns\n -------\n ps: ndarray(N)\n A list of N note numbers\n times: ndarray(N)\n Duration of each note, in increments\n of sixteenth notes\n \"\"\"\n tune = np.loadtxt(filename)\n ps = tune[:, 0]\n times = np.zeros(tune.shape[0])\n times[1::] = np.cumsum(tune[0:-1, 1])\n times = times*tune_length/np.sum(tune[:, 1])\n return ps, times\n\ndef karplus_strong_note(sr, note, duration, decay):\n \"\"\"\n Parameters\n ----------\n sr: int\n Sample rate\n note: int\n Note number. 0 is 440hz concert A\n duration: float\n Seconds of audio\n decay: float \n Decay amount (between 0 and 1)\n\n Returns\n -------\n ndarray(N): Audio samples for this note\n \"\"\"\n N = int(duration*sr)\n y = np.zeros(N)\n f = 440*2**(note/12) #stolen from assignment 1, the eq is 440*2**(note/12)\n T = int(sr/f)#this should calculate the period in samples per f seconds\n # we want to initialize the first T samples as random noise and populate 0 through T with random values\n y[0:T] = np.random.rand(T) #generates T random noise samples\n #next we populate the y array\n for i in range(T, N):\n y[i] = decay*((y[i-T]+y[i-T+1])/2)\n return y\n\ndef fm_synth_note(sr, note, duration, ratio = 2, I = 2, \n envelope = lambda N, sr: np.ones(N),\n amplitude = lambda N, sr: np.ones(N)):\n \"\"\"\n Parameters\n ----------\n sr: int\n Sample rate\n note: int\n Note number. 0 is 440hz concert A\n duration: float\n Seconds of audio\n ratio: float\n Ratio of modulation frequency to carrier frequency\n I: float\n Modulation index (ratio of peak frequency deviation to\n modulation frequency)\n envelope: function (N, sr) -> ndarray(N)\n A function for generating an ADSR profile\n amplitude: function (N, sr) -> ndarray(N)\n A function for generating a time-varying amplitude\n\n Returns\n -------\n ndarray(N): Audio samples for this note\n \"\"\"\n N = int(duration*sr)\n y = np.zeros(N)\n t = np.arange(N)/sr\n fc = 440*2**(note/12)\n fm = fc*ratio\n env= I*envelope(N, sr) #numpy array that is the full time variant\n amp = amplitude(N, sr)\n #y(t) = A(t)cos(2*pi*fc*t+I(t)sin(2*pi*fm*t))\n y = amp*np.cos(2*np.pi*fc*t + env*np.sin(2*np.pi*fm*t))\n return y\n\ndef exp_env(N, sr, lam = 3):\n \"\"\"\n Make an exponential envelope\n Parameters\n ----------\n N: int\n Number of samples\n sr: int\n Sample rate\n lam: float\n Exponential decay rate: e^{-lam*t}\n\n Returns\n -------\n ndarray(N): Envelope samples\n \"\"\"\n return np.exp(-lam*np.arange(N)/sr)\n\ndef drum_like_env(N, sr):\n \"\"\"\n Make a drum-like envelope, according to Chowning's paper\n Parameters\n ----------\n N: int\n Number of samples\n sr: int\n Sample rate\n\n Returns\n -------\n ndarray(N): Envelope samples\n \"\"\"\n t = np.arange(N)/sr\n y = np.zeros(N)\n y = ((t+.025)**2)*np.exp(-12*(t+.025)*3)\n return y\n\ndef wood_drum_env(N, sr):\n \"\"\"\n Make the wood-drum envelope from Chowning's paper\n Parameters\n ----------\n N: int\n Number of samples\n sr: int\n Sample rate\n\n Returns\n -------\n ndarray(N): Envelope samples\n \"\"\"\n y = np.zeros(N)\n y[0:int(sr*0.025)] = np.linspace(1, 0, int(sr*0.025))\n return y\n\ndef dirty_bass_env(N, sr):\n \"\"\"\n Make the \"dirty bass\" envelope from Attack Magazine\n https://www.attackmagazine.com/technique/tutorials/dirty-fm-bass/\n Parameters\n ----------\n N: int\n Number of samples\n sr: int\n Sample rate\n \n Returns\n -------\n ndarray(N): Envelope samples\n \"\"\"\n y = np.zeros(N)\n y[0:int(.25*sr)] = np.exp(-29*np.arange(int(N/2))/sr)\n y[int(.25*sr):int(.5*sr)] = 1-np.exp(-29*np.arange(int(N/2))/sr)\n return y\n\ndef fm_plucked_string_note(sr, note, duration, lam = 3):\n \"\"\"\n Make a plucked string of a particular length\n using FM synthesis\n Parameters\n ----------\n sr: int\n Sample rate\n note: int\n Note number. 0 is 440hz concert A\n duration: float\n Seconds of audio\n lam: float\n The decay rate of the note\n \n Returns\n -------\n ndarray(N): Audio samples for this note\n \"\"\"\n envelope = lambda N, sr: exp_env(N, sr, lam)\n return fm_synth_note(sr, note, duration, \\\n ratio = 1, I = 8, envelope = envelope,\n amplitude = envelope)\n\n\ndef brass_env(N, sr):\n \"\"\"\n Make the brass ADSR envelope from Chowning's paper\n Parameters\n ----------\n N: int\n Number of samples\n sr: int\n Sample rate\n \n Returns\n -------\n ndarray(N): Envelope samples\n \"\"\"\n #N = dur*sr\n #dur = N/sr\n attack = np.linspace(0, 1, int(sr*.1))\n decay = np.linspace(1, .7, int(sr*.1))\n release = np.linspace(.5, 0, int(sr*.1))\n sustain = np.array([])\n L = N - len(attack) - len(decay) - len(release)\n if L > 0:\n sustain = np.linspace(.7, .5, L)\n y = np.concatenate((attack, decay, sustain , release))\n # Duration check\n if len(y) > N:\n y = y[0:N]\n return y\n \"\"\"\n y = np.zeros(N)\n dur = N/sr\n if dur <= 0.3:\n atk = np.linspace(0, 1, int(sr*0.05))\n dec = np.linspace(1, 0.75, (int(sr*0.2)-int(sr*0.05)))\n sus = np.linspace(0.75, 0.75, (int(sr*0.95) - int(sr*0.05)))\n rel = np.linspace(0.75, 0, (int(sr*1) - int(sr*0.95)))\n y = np.concatenate((atk, dec, sus, rel))\n \n else:\n atk = np.linspace(0, 1, int(sr*0.1))\n dec = np.linspace(1, 0.75, int(sr*0.1))\n sus = np.linspace(0.75, 0.7, (int(sr*0.9)-int(sr*0.2)))\n rel = np.linspace(0.7, 0, int(sr*0.1))\n y = np.concatenate((atk, dec, sus, rel))\n return y\n \"\"\"\n\n\ndef fm_bell_note(sr, note, duration):\n \"\"\"\n Make a bell note of a particular length\n Parameters\n ----------\n sr: int\n Sample rate\n note: int\n Note number. 0 is 440hz concert A\n duration: float\n Seconds of audio\n \n Returns\n -------\n ndarray(N): Audio samples for this note\n \"\"\"\n envelope = lambda N, sr: exp_env(N, sr, 0.8)\n return fm_synth_note(sr, note, duration, \\\n ratio = 1.4, I = 2, envelope = envelope,\n amplitude = envelope)\n\ndef fm_brass_note(sr, note, duration):\n \"\"\"\n Make a brass note of a particular length\n Parameters\n ----------\n sr: int\n Sample rate\n note: int\n Note number. 0 is 440hz concert A\n duration: float\n Seconds of audio\n \n Return\n ------\n ndarray(N): Audio samples for this note\n \"\"\"\n \n envelope = lambda N, sr: brass_env(N, sr)\n return fm_synth_note(int(sr), note, duration, \\\n ratio = 1, I = 10, envelope = envelope,\n amplitude = envelope)\n\ndef fm_drum_sound(sr, note, duration, fixed_note = -14):\n \"\"\"\n Make what Chowning calls a \"drum-like sound\"\n Parameters\n ----------\n sr: int\n Sample rate\n note: int\n Note number (which is ignored)\n duration: float\n Seconds of audio\n fixed_note: int\n Note number of the fixed note for this drum\n \n Returns\n ------\n ndarray(N): Audio samples for this drum hit\n \"\"\"\n envelope = lambda N, sr: drum_like_env(N, sr)\n return fm_synth_note(sr, note, duration, \\\n ratio = 1.4, I = 2, envelope = envelope,\n amplitude = envelope)\n\ndef fm_wood_drum_sound(sr, note, duration, fixed_note = -14):\n \"\"\"\n Make what Chowning calls a \"wood drum sound\"\n Parameters\n ----------\n sr: int\n Sample rate\n note: int\n Note number (which is ignored)\n duration: float\n Seconds of audio\n fixed_note: int\n Note number of the fixed note for this drum\n \n Returns\n -------\n ndarray(N): Audio samples for this drum hit\n \"\"\"\n envelope = lambda N, sr: wood_drum_env(N, sr)\n return fm_synth_note(sr, note, duration, \\\n ratio = 1.4, I = 10, envelope = envelope,\n amplitude = envelope)\n\ndef fm_dirty_bass_note(sr, note, duration):\n \"\"\"\n Make a \"dirty bass\" note, based on \n https://www.attackmagazine.com/technique/tutorials/dirty-fm-bass/\n Parameters\n ----------\n sr: int\n Sample rate\n note: int\n Note number (which is ignored)\n duration: float\n Seconds of audio\n \n Returns\n -------\n ndarray(N): Audio samples for this drum hit\n \"\"\"\n \n envelope = lambda N, sr: dirty_bass_env(N, sr)\n return fm_synth_note(sr, note, duration, \\\n ratio = 1, I = 18, envelope = envelope,\n amplitude = envelope) \n\ndef make_tune(filename, sixteenth_len, sr, note_fn):\n \"\"\"\n Parameters\n ----------\n filename: string\n Path to file containing the tune. Consists of\n rows of , where\n the note number 0 is a 440hz concert A, and the\n note duration is in factors of 16th notes\n sixteenth_len: float\n Length of a sixteenth note, in seconds\n sr: int\n Sample rate\n note_fn: function (sr, note, duration) -> ndarray(M)\n A function that generates audio samples for a particular\n note at a given sample rate and duration\n \n \n Returns\n -------\n -------\n ndarray(N): Audio containing the tune\n \"\"\"\n tune = np.loadtxt(filename)\n notes = tune[:, 0]\n durations = tune[:, 1]\n durations_sec = durations*sixteenth_len\n ret = []\n n = len(notes) #number of notes\n for i in range(n):\n x = note_fn(sr, notes[i], durations_sec[i])\n if np.isnan(notes[i]): #if the note is not a number, append 0 into y such that it has no value i.e is silent\n x = np.zeros(int(durations_sec[i]*sr))\n ret = np.concatenate((ret, x))\n else:\n ret = np.concatenate((ret, x))\n return ret ","sub_path":"HW3_Vocoders-main/HW3_Vocoders-main/instruments.py","file_name":"instruments.py","file_ext":"py","file_size_in_byte":10331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"547783881","text":"#导入模块\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#标签样本大小\nsample_size = 50\n#中心位置\nsample_location = 2\n\n#训练次数\ntraining_num=100\n#学习率\nlearning_rate=0.001\n\n#权值\nw=np.array([-1,1])\n#偏置\nb=0\n\n#生成数据样本\nnp.random.seed(0)\nx=np.r_[np.random.randn(sample_size,2)-[sample_location,sample_location],np.random.randn(sample_size,2)+[sample_location,sample_location]]\n\n#生成标签\ny=[-1]*sample_size+[1]*sample_size\n\n#画样本散点图\nfor i in range(len(x)):\n if y[i]==1:\n plt.plot(x[i][0],x[i][1],'rx')\n else:\n plt.plot(x[i][0],x[i][1],'bo')\nplt.title('sample distribution')\nlim_x=plt.xlim(-5,5)\nlim_y=plt.ylim(-4.5,4.5)\n\nx_lab=plt.xlabel('x',size=15)\ny_lab=plt.ylabel('y',size=15)\n\n\nfor i in range(len(x)):\n if y[i]==1:\n plt.plot(x[i][0],x[i][1],'rx')\n else:\n plt.plot(x[i][0],x[i][1],'bo')\n#开始训练\nfor step in range(training_num+1):\n grad_x=np.array([0,0])\n grad_b=0\n \n #每训练10次更新一次分界线\n if step%10==0:\n ref_x=[-10,10]\n ref_y=[0,0]\n for i in range(len(ref_x)):\n ref_y[i]=-(w[0]*ref_x[i]+b)/w[1]\n pp=plt.plot(ref_x,ref_y)\n\n #遍历训练样本集寻找错分样本、\n for j in range(len(x)):\n if np.sign(np.dot(w,x[j])+b)<0 and y[j]!=np.sign(np.dot(w,x[j])+b):\n grad_x=grad_x-x[j]\n grad_b=grad_b+y[j]\n \n #利用梯度下降法更新参数\n w=w+learning_rate*grad_x\n b=b+learning_rate*grad_b\n \nplt.title('training')\n\nlim_x=plt.xlim(-5,5)\nlim_y=plt.ylim(-4.5,4.5)\n\nx_lab=plt.xlabel('x',size=15)\ny_lab=plt.ylabel('y',size=15)","sub_path":"perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"618792357","text":"import json\nimport sys\nimport re\nimport urllib\n\nfrom bs4 import BeautifulSoup\nimport string\n\ndef add(a, b):\n return a + b\n\ndef mycomp(a, b):\n x = str(a[7].text)\n y = str(b[7].text)\n #print x;\n #print y;\n s1 = string.replace(x, \",\", \"\")\n s2 = string.replace(y, \",\", \"\")\n return int(s2) - int(s1)\n\n\ndef contractAsJson(filename):\n jsonQuoteData = \"[]\"\n #return jsonQuoteData\n fh = open(filename)\n soup = BeautifulSoup(fh)\n\n #price = soup.find_all(\"yfs_l84\")\n cur_price = soup.find(class_=\"time_rtq_ticker\")\n currPrice = float(cur_price.find(id=re.compile(\"yfs\")).text)\n\n #urls = soup.find_all(\"a\", {\"href\": re.compile(\"/q/op?\")});\n #urls = soup.find_all(\"a\");\n urls = soup.find_all(\"a\", href = re.compile(\"\\/q\\/o[s,p]\\?s=[A-Za-z]+&m\"));\n dateUrls = []\n\n #print urls\n for link in urls:\n\t #print link.get(\"href\")\n\t link[\"href\"] = \"http://finance.yahoo.com\" + link[\"href\"]\n\t new_link = string.replace(link[\"href\"], '&', '&')\n\t #print new_link\n\t dateUrls.append(new_link)\n#print dateUrls\n\n################find options################################\n tables = soup.find_all(class_=\"yfnc_datamodoutline1\")\n\n table1 = tables[0].find_all(\"tr\")\n table2 = tables[1].find_all(\"tr\")\n mytable = []\n\n for row_index in range(2, len(table1)):\n row = table1[row_index]\n info_list = row.find_all(\"td\")\n #for i in range(0, len(info_list)):\n #print info_list[i].text\n mytable.append(info_list)\n\n for row_index in range(2, len(table2)):\n row = table2[row_index]\n info_list = row.find_all(\"td\")\n #for i in range(0, len(info_list)):\n #print info_list[i].text\n mytable.append(info_list)\n\n #print mytable\n mytable.sort(mycomp)\n option_list = []\n #print \"table row lenth\", len(mytable)\n for row_index in range(0, len(mytable)):\n option = dict()\n option[\"Strike\"] = str(mytable[row_index][0].text)\n symbol = str(mytable[row_index][1].text)\n start = symbol.find(\"1\")\n option[\"Symbol\"] = symbol[:start]\n rest = symbol[start:]\n option[\"Date\"] = re.split('[A-Z]', rest)[0]\n option[\"Type\"] = rest[len(option[\"Date\"])]\n option[\"Last\"] = str(mytable[row_index][2].text)\n option[\"Change\"] = str(mytable[row_index][3].text)\n# if(mytable[row_index][4].text != None):\n# option[\"Bid\"] = str(mytable[row_index][4].text)\n# else:\n# option[\"Bid\"] = \"N/A\" \n option[\"Bid\"] = str(mytable[row_index][4].text)\n option[\"Ask\"] = str(mytable[row_index][5].text)\n option[\"Vol\"] = str(mytable[row_index][6].text)\n option[\"Open\"] = str(mytable[row_index][7].text)\n option_list.append(option)\n\n #print option_list\n \n summary = dict()\n summary[\"currPrice\"] = currPrice\n summary[\"dateUrls\"] = dateUrls\n summary[\"optionQuotes\"] = option_list\n #jsonQuoteData = json.dumps(sorted(summary.iterkeys()))\n #jsonQuoteData = json.dumps(summary)\n jsonQuoteData = json.dumps(summary, sort_keys = True, indent = 4, separators=(',', ': '))\n\n return jsonQuoteData\n\n\n\n\n","sub_path":"project/dummy.py","file_name":"dummy.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"206070898","text":"from firebase import firebase\nimport tensorflow.compat.v1 as tf\nimport pandas as pd\nimport numpy as np\nimport csv\n\ntf.disable_v2_behavior()\n\n\nfirebase = firebase.FirebaseApplication(\"https://mhacks-13-project.firebaseio.com/\")\n\nresult = firebase.get('/users', None)\n\n\n# Set up, populate matrix.\n# Rows = users (learners).\n# Columns = users (teachers).\n\nnum_users = len(result)\nuid_list = []\n\nfor uid, _ in result.items():\n\tuid_list.append(uid)\n\nwith open('uid.csv', 'w') as uid_file:\n\twr = csv.writer(uid_file, quoting=csv.QUOTE_ALL)\n\twr.writerow(uid_list)\n\nvalue_matrix = [[0.0, 0.0, 0.0, 0.0], [0.0, 0.6, 0.8, 1.0], \\\n\t\t\t\t[0.0, 0.0, 0.6, 0.8], [0.0, 0.0, 0.0, 0.6]]\n\nl_t_matrix = pd.DataFrame(0.0, index=np.arange(num_users), columns=np.arange(num_users))\nmax_val = 0.0\n# non_zero = 0\n\nfor i in range(len(uid_list)):\n\tfor j in range(len(uid_list)):\n\t\tlearner_info = result[uid_list[i]]\n\t\tteacher_info = result[uid_list[j]]\n\n\t\tif \"Interests\" in learner_info and \"Skills\" in teacher_info:\n\t\t\tval_lt = 0.0\n\t\t\tfor interest in learner_info[\"Interests\"]:\n\t\t\t\tif interest in teacher_info[\"Skills\"]:\n\t\t\t\t\tval_lt += value_matrix[learner_info[\"Interests\"][interest]]\\\n\t\t\t\t\t\t\t\t\t\t [teacher_info[\"Skills\"][interest]]\n\t\t\tl_t_matrix.at[i, j] = val_lt\n\n\t\t\tif val_lt > max_val:\n\t\t\t\tmax_val = val_lt\n\t\t\t# if val_lt > 0.0:\n\t\t\t# \tnon_zero += 1\n\nif max_val != 0.0:\n\tl_t_matrix = l_t_matrix / max_val # normalize\n\n#print(l_t_matrix)\n#print(max_val)\n#print(non_zero)\n\n\n# Build model.\n\nnum_input = num_users\nnum_hidden_1 = 10\nnum_hidden_2 = 5\n\nX = tf.placeholder(tf.float64, [None, num_input])\n\nweights = {\n 'encoder_h1': tf.Variable(tf.random_normal([num_input, num_hidden_1], dtype=tf.float64)),\n 'encoder_h2': tf.Variable(tf.random_normal([num_hidden_1, num_hidden_2], dtype=tf.float64)),\n 'decoder_h1': tf.Variable(tf.random_normal([num_hidden_2, num_hidden_1], dtype=tf.float64)),\n 'decoder_h2': tf.Variable(tf.random_normal([num_hidden_1, num_input], dtype=tf.float64)),\n}\n\nbiases = {\n 'encoder_b1': tf.Variable(tf.random_normal([num_hidden_1], dtype=tf.float64)),\n 'encoder_b2': tf.Variable(tf.random_normal([num_hidden_2], dtype=tf.float64)),\n 'decoder_b1': tf.Variable(tf.random_normal([num_hidden_1], dtype=tf.float64)),\n 'decoder_b2': tf.Variable(tf.random_normal([num_input], dtype=tf.float64)),\n}\n\n\ndef encoder(x):\n layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['encoder_h1']), biases['encoder_b1']))\n layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['encoder_h2']), biases['encoder_b2']))\n return layer_2\n\ndef decoder(x):\n layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, weights['decoder_h1']), biases['decoder_b1']))\n layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, weights['decoder_h2']), biases['decoder_b2']))\n return layer_2\n\nencoder_op = encoder(X)\ndecoder_op = decoder(encoder_op)\n\ny_pred = decoder_op\ny_true = X\n\nloss = tf.losses.mean_squared_error(y_true, y_pred)\noptimizer = tf.train.RMSPropOptimizer(0.03).minimize(loss)\neval_x = tf.placeholder(tf.int32, )\neval_y = tf.placeholder(tf.int32, )\npre, pre_op = tf.metrics.precision(labels=eval_x, predictions=eval_y)\n\ninit = tf.global_variables_initializer()\nlocal_init = tf.local_variables_initializer()\npred_data = pd.DataFrame()\n\n\n# Train model.\n\nwith tf.Session() as session:\n\tepochs = 100\n\tbatch_size = 25\n\n\tsession.run(init)\n\tsession.run(local_init)\n\n\tnum_batches = int(l_t_matrix.shape[0] / batch_size)\n\tl_t_matrix = np.array_split(l_t_matrix, num_batches)\n\n\tfor i in range(epochs):\n\t\tavg_cost = 0\n\t\tfor batch in l_t_matrix:\n\t\t\t_, l = session.run([optimizer, loss], feed_dict={X: batch})\n\t\t\tavg_cost += l\n\t\tavg_cost /= num_batches\n\n\t\tprint(\"epoch: {} Loss: {}\".format(i + 1, avg_cost))\n\n\tl_t_matrix = np.concatenate(l_t_matrix, axis=0)\n\n\tpreds = session.run(decoder_op, feed_dict={X: l_t_matrix})\n\n\tpreds = pd.DataFrame(preds)\n\tpreds.to_csv('lt_matrix.csv', index=False, header=False)\n\n\tsimple_save(session, 'model', inputs={\"a\":a}, outputs={\"b\":b})","sub_path":"recommender.py","file_name":"recommender.py","file_ext":"py","file_size_in_byte":3962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"544213866","text":"import scrapy\nimport os\nimport re\nfrom tutorial.items import IqiyiItem\n\n# eg: scrapy crawl iqiyi_film -a url=http://www.iqiyi.com/v_19rrm3ae54.html\nclass IqiyiFilmSpider(scrapy.Spider):\n\n name = \"iqiyi_film\"\n # allowed_domains = [\"iqiyi.com\"]\n file_path = ''\n category = None\n # eg: http://www.iqiyi.com/v_19rrm3ae54.html\n def __init__(self, url=None, *args, **kwargs):\n super(IqiyiFilmSpider, self).__init__(*args, **kwargs)\n self.start_urls = [url]\n\n def parse(self, response):\n item = IqiyiItem()\n # item['url'] = response.url\n # item['tvid'] = response.xpath(\"//div/@data-player-tvid\").extract()[-1]\n # item['vid'] = response.xpath(\"//div/@data-player-videoid\").extract()[-1]\n item['tv_name'] = response.xpath(\"//div/@data-qitancomment-title\").extract()[-1]\n item['album_id'] = response.xpath(\"//div/@data-player-albumid\").extract()[-1]\n\n film = item['tv_name']\n if self.category:\n self.file_path = os.path.join(os.getcwd(), 'data', self.category, film)\n else:\n self.file_path = os.path.join(os.getcwd(), 'data', film)\n\n if not os.path.exists(self.file_path):\n os.makedirs(self.file_path)\n \n file_name = os.path.join(self.file_path, 'source.html')\n with open(file_name, 'wb') as f:\n f.write(response.body)\n\n # get detail json\n # url = 'http://cache.video.qiyi.com/jp/vi/' + item['tvid'] + '/' + item['vid'] + '/'\n url = \"http://mixer.video.iqiyi.com/jp/mixin/videos/\" + item['album_id']\n item['url'] = url\n yield scrapy.Request(url, self.parse_detail)\n\n def parse_detail(self, response):\n file_name = os.path.join(self.file_path, 'data.json')\n with open(file_name, 'wb') as f:\n f.write(re.sub('^[^{]*|[^}]*$','',response.body))","sub_path":"tutorial/tutorial/spiders/iqiyi_film.py","file_name":"iqiyi_film.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"261244376","text":"\"\"\"\nConditions and Loops\n\nProblem\nGiven: Two positive integers a and b (a Environment:\n \"\"\"\n Parses environment variables and sets their defaults if they do not exist.\n \"\"\"\n return Environment(\n media_url=get_endpoint(\"MEDIA\"),\n datastore_reader_url=get_endpoint(\"DATASTORE_READER\"),\n datastore_writer_url=get_endpoint(\"DATASTORE_WRITER\"),\n vote_url=get_endpoint(\"VOTE\"),\n )\n\n\ndef get_endpoint(service: str) -> str:\n parts = {}\n for suffix in (\"PROTOCOL\", \"HOST\", \"PORT\", \"PATH\"):\n variable = \"_\".join((service, suffix))\n value = os.environ.get(variable)\n if value is None:\n default = DEFAULTS.get(variable)\n if default is None:\n raise ValueError(f\"Environment variable {variable} does not exist.\")\n parts[suffix] = default\n else:\n parts[suffix] = value\n return f\"{parts['PROTOCOL']}://{parts['HOST']}:{parts['PORT']}{parts['PATH']}\"\n","sub_path":"openslides_backend/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"107258625","text":"# Part of Release Buddy: checksum Commands\n\nimport hashlib\nfrom buddylib import *\n\n#\n# Copyright (c) 2013 Torgny Nyblom \n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along\n# with this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n\ndef buddy_checksum(options, project, version):\n ChangeDir(options, options.Tarballs)\n archives = getArchive(options, project, version)\n for archive in archives:\n with open(os.path.join(options.Tarballs, archive + \".sha256\"), 'w') as f:\n digest = createChecksum(options, archive)\n f.write( digest )\n f.write( \"\\n\" )\n\ndef buddy_checksums(options, projects, version):\n ChangeDir(options, options.Tarballs)\n with open(os.path.join(options.Tarballs, \"sha256sums.txt\"), 'w') as f:\n for project in projects:\n archives = getArchive(options, project, version)\n for archive in archives:\n digest = createChecksum(options, archive)\n f.write( digest )\n f.write( \"\\n\" )\n\n\ndef createChecksum(options, archive):\n info(\"Creating checksum for %s\"%archive)\n crypt = hashlib.sha256()\n\n debug(\"Calculating...\")\n with open( os.path.join(options.Tarballs, archive) ) as f:\n while True:\n block = f.read(256)\n if block == '':\n break\n crypt.update(block)\n digest = crypt.hexdigest()\n info(\"checksum: %s\"%digest)\n return \"%s %s\"%(digest, archive)\n","sub_path":"buddychecksum.py","file_name":"buddychecksum.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"298711110","text":"import argparse\r\nimport os\r\nimport sys\r\nimport logging\r\nimport gzip\r\nimport shutil\r\nfrom functions_reconstructing_macrocomplex import *\r\nfrom Bio.PDB import *\r\n\r\nparser = argparse.ArgumentParser(description = \"\"\"This program models macrocomplex structures of biomolecules formed by proteins. The macrocomplex is build from pairwaise interactions.\"\"\")\r\n\r\nparser.add_argument('-i','--input-directory',\r\n required=True,\r\n dest=\"input_path\",\r\n action=\"store\",\r\n help=\"Directory containig the input structure files.\")\r\n\r\nparser.add_argument('-s', '--stoichiometry',\r\n default=None,\r\n dest=\"stoichiometry\",\r\n action=\"store\",\r\n help=\"Path containing the stoichiometry of the complex.\")\r\n\r\nparser.add_argument('-o','--output-directory',\r\n dest=\"output_path\",\r\n action=\"store\",\r\n type=str,\r\n default=\"output\",\r\n help=\"Directory where the output will be saved.\")\r\n\r\nparser.add_argument('-f','--force',\r\n default=False,\r\n dest=\"force\",\r\n action=\"store\",\r\n help=\"Checks the output-directory doesn't exist before the application is executed.\")\r\n\r\nparser.add_argument('-v','--verbose',\r\n default=False,\r\n dest=\"verbose\",\r\n action=\"store_true\",\r\n help=\"Returns the progression log of the program execution printed in standard error.\")\r\n\r\nparser.add_argument('-ofn', '--output_filename',\r\n dest = \"output_filename\",\r\n action = \"store\",\r\n default = \"final_macrocomplex\",\r\n help = \"Optional. Defines the name of the output file where the final model should be stored.\")\r\n\r\narguments = parser.parse_args()\r\n\r\n\r\nif __name__==\"__main__\":\r\n\r\n absolute_path = os.getcwd()\r\n\r\n try:\r\n os.mkdir(arguments.output_path)\r\n subdirs = ['structures', 'analysis']\r\n for folder in subdirs:\r\n os.mkdir(os.path.join(arguments.output_path, folder))\r\n except FileExistsError:\r\n if arguments.force == False:\r\n print (f\"The {arguments.output_path} already exists.\\n\")\r\n sys.exit(-1)\r\n elif arguments.force == True:\r\n shutil.rmtree(arguments.output_path)\r\n os.mkdir(arguments.output_path)\r\n subdirs = ['structures', 'analysis']\r\n for folder in subdirs:\r\n folder = \"/\" + folder\r\n os.mkdir(os.path.join(arguments.output_path, folder))\r\n\r\n # Create the logging file\r\n logging_storage = arguments.output_path + \"/analysis/macrocomplex_builder.log\"\r\n logging.basicConfig(filename = logging_storage, format = '%(levelname)s:%(message)s', level = logging.DEBUG, filemode = \"w\")\t#move to output folder\r\n logging.debug('...STARTING...')\r\n\r\n if arguments.verbose:\r\n logging.getLogger().addHandler(logging.StreamHandler())\r\n\r\n # Get the list of pdb files in input directory provided\r\n try:\r\n list_files = only_pdb_files(arguments.input_path)\r\n except NotADirectoryError:\r\n logging.info(\"Input path provided could not be found as a directory. Aborting program. Please try again.\")\r\n sys.exit(-1)\r\n\r\n # Get the structures of the PDB files\r\n pdb_structure, molecule_type = read_pdb_files(list_files)\r\n\r\n os.chdir(absolute_path) # get back to main working directory\r\n\r\n # Get the stoichiometry from the file if provided by the user\r\n if arguments.stoichiometry:\r\n logging.info(\"\\nStoichiometry file %s was found. This will be used to build the complex.\\n\" %(arguments.stoichiometry))\r\n try:\r\n stoichiometry_file = {}\r\n with open(arguments.stoichiometry, \"r\") as file:\r\n for line in file:\r\n stoich_info = line.strip().split(\":\")\r\n stoichiometry_file[stoich_info[0]] = int(stoich_info[1])\r\n print(stoichiometry_file)\r\n except FileNotFoundError:\r\n logging.info(\"\\nWe could not find the stoichiometry file provided. Aborting program. Please try again.\")\r\n exit()\r\n else:\r\n logging.info(\"\\nStoichiometry was not provided. The program will use 1 for each chain as default value.\\n\")\r\n stoichiometry_file = {}\r\n for file in pdb_structure:\r\n stoichiometry_file[file] = 1\r\n\r\n # Analyse protein-protein interactions to build complex\r\n if molecule_type == \"PROT\":\r\n logging.info(\"The files provided contain Protein-Protein Interactions.\\n\")\r\n\r\n # get the first file as reference and put it to the end of the list\r\n id_list = list(pdb_structure.keys())\r\n print(id_list)\r\n reference_id = id_list.pop(0)\r\n id_list.append(reference_id)\r\n current_stoichiometry = {reference_id:1}\r\n\r\n # Superimpose C-alphas of those of chains with alignment higher than 0.95\r\n reference_structure = pdb_structure[reference_id] # get the structure of the reference\r\n num_chains = 2 # initial number of chains of the complex\r\n\r\n while (num_chains <= sum(list(stoichiometry_file.values()))): # while the complex has less or same chains as the stoichiometry provided\r\n sample_id = id_list.pop(0) # get interaction to compare with reference and superimpose\r\n if sample_id not in stoichiometry_file:\r\n sample_id = \"\"\r\n continue\r\n if not sample_id in current_stoichiometry: # initialise the count for the structure that is currently being analysed\r\n current_stoichiometry[sample_id] = 0\r\n\r\n sample_structure = pdb_structure[sample_id]\r\n\r\n try:\r\n superimposition, RMSD = superimpose_chains(reference_structure, sample_structure) # superimpose. We get the superimposition with their best RMSD\r\n except:\r\n current_stoichiometry[sample_id] += 1\r\n num_chains += 1\r\n\r\n # If no superimposition\r\n if bool(superimposition) == False:\r\n id_list.append(sample_id) # if the sample could not be superimposed, add it to the end of the list to analysed it again later\r\n continue\r\n\r\n # If there are superimpositions made\r\n for tuple_chains, super_object in superimposition:\r\n logging.info(\"Chain %s of the reference structure and chain %s of the sample structure have been superimposed with a RMSD of %.3f.\\n\" %(tuple_chains[0], tuple_chains[1], RMSD))\r\n chain_to_add = [chain for chain in sample_structure.get_chains() if chain.id != tuple_chains[1]][0]\r\n super_object.apply(chain_to_add.get_atoms()) # apply rotation matrix to moving structure\r\n reference_structure = look_for_clashes (reference_structure, chain_to_add)\r\n\r\n num_chains += 1\r\n\r\n # If the structure is not the same as the stoichoimetry provided, add it to the end of the list to analyse and try to superimpose again later\r\n if current_stoichiometry[sample_id] != stoichiometry_file[sample_id]:\r\n id_list.append(sample_id)\r\n\r\n\r\n store_output (reference_structure[0], arguments.output_path, arguments.output_filename)\r\n logging.info(\"The macrocomplex built has %d chains.\" %(reference_structure[0].__len__()))\r\n","sub_path":"build/scripts-3.8/main_reconstructing_macrocomplex.py","file_name":"main_reconstructing_macrocomplex.py","file_ext":"py","file_size_in_byte":7588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"570450653","text":"# Programmers _ Lv.2 오픈채팅방 2019 KAKAO BLIND RECRUITMENT\n\n\ndef solution(record, id=[], answer=[]):\n for r in record:\n id.append(r.split()[1]) \n dic_id = {x : '' for x in id} # 바뀌는 닉네임을 계속 업데이트하며 아이디와 최종 닉네임을 딕셔너리에 저장\n\n for r in record:\n if len(r.split()) > 2: # Leave일 때 닉네임은 바뀌지 않으므로 제외\n dic_id.update({r.split()[1]:r.split()[2]})\n\n for r in record:\n if r.split()[0] == 'Enter': # Change일 때는 채팅방에 아무런 변화가 없으므로 출력하지 않음\n answer.append(f'{dic_id[r.split()[1]]}님이 들어왔습니다.')\n elif r.split()[0] == 'Leave':\n answer.append(f'{dic_id[r.split()[1]]}님이 나갔습니다.')\n\n return answer","sub_path":"오픈채팅방.py","file_name":"오픈채팅방.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"176701025","text":"import os\nimport utilities as util\nimport globalvar\n\n\"\"\"\nCPU related configurations\n\"\"\"\n\nclass CPU_conf:\n def __init__(self):\n self.str_CPU_code_name = self.__get_CPU_code_name()\n self.str_instruction_supported = self.get_CPU_instructions_supported()\n self.cpu_total_num = self.__get_cpu_total_num()\n self.b_hyperthread_enabled = self.__hyperthread_is_enabled()\n self.b_pstate_disabled = self.__intel_pstate_is_disabled()\n self.b_turbo_disabled = self.__turbo_is_disabled()\n self.b_c6state_disabled = self.__c6state_disabled()\n self.b_c3state_disabled = self.__c3state_disabled()\n self.b_direct_cache_access_enabled = self.__dca_is_enabled()\n self.scaling_governor = self.__get_scaling_governor()\n self.cpu_core_total_num = self.__get_core_total_num()\n self.cores = []\n self.init_all_cpus_conf()\n\n \"\"\"\n CPU related utility functions\n \"\"\"\n\n def __print_lscpu_cmd(self):\n return util.str_cmd_output('lscpu')\n\n def __print_lscpu_e_cmd(self):\n return util.str_cmd_output('lscpu -e')\n\n def __get_lscpu_specific_conf(self, spec):\n return util.str_get_specific_value_after_colon('lscpu', spec)\n\n def get_lscpu_e_specific_conf(self, cpu_id, column):\n output = self.__print_lscpu_e_cmd();\n l = output.split('\\n')\n l_title = l[0].split()\n ll = l[cpu_id + 1].split()\n column_idx = l_title.index(column)\n return ll[column_idx]\n\n def __get_cpu_total_num(self):\n output = self.__print_lscpu_cmd()\n num = self.__get_lscpu_specific_conf('CPU(s)')\n return int(num)\n\n def get_cpu_numa_node_by_cpu_id(self, cpu_id):\n return int(self.get_lscpu_e_specific_conf(cpu_id, 'NODE'))\n\n def get_cpu_core_by_cpu_id(self, cpu_id):\n return int(self.get_lscpu_e_specific_conf(cpu_id, 'CORE'))\n\n def init_all_cpus_conf(self):\n for i in range(self.cpu_total_num ):\n core = self.get_cpu_core_by_cpu_id(i)\n node = self.get_cpu_numa_node_by_cpu_id(i)\n single_cpu = Single_CPU_core_conf(cpu_id = i,\n core_num = core,\n numa_node = node)\n self.cores.append(single_cpu)\n\n def __get_CPU_code_name(self):\n output = self.__print_lscpu_cmd()\n name = self.__get_lscpu_specific_conf('Model name')\n return name\n\n def __hyperthread_is_enabled(self):\n output = self.__print_lscpu_cmd()\n tpc = self.__get_lscpu_specific_conf('Thread(s) per core')\n if int(tpc) == 1:\n return False\n else:\n return True\n\n def __turbo_is_disabled(self):\n output = util.get_cat_command_output('/sys/devices/system/cpu/intel_pstate/no_turbo')\n if output == None:\n return False\n if output == '0':\n return False\n else:\n return True\n\n def __dca_is_enabled(self):\n output = util.str_cmd_output('dmesg | grep dca')\n if output.find('disabled') == -1:\n return True\n else:\n return False\n\n def __get_core_total_num(self):\n if self.b_hyperthread_enabled == True:\n return (self.cpu_total_num / 2)\n else:\n return self.cpu_total_num\n\n def get_CPU_instructions_supported(self):\n pass\n\n def __intel_pstate_is_disabled(self):\n output = util.get_cat_command_output('/boot/config-$(uname -r) | grep -i pstate')\n if output is None:\n return True\n else:\n return False\n\n def __c6state_disabled(self):\n output = util.int_cmd_output('cat /sys/module/intel_idle/parameters/max_cstate')\n if output >= 6:\n return False\n else:\n return True\n\n def __c3state_disabled(self):\n output = util.int_cmd_output('cat /sys/module/intel_idle/parameters/max_cstate')\n if output >= 3:\n return False\n else:\n return True\n\n def __get_scaling_governor(self):\n ret = []\n output = util.get_cat_command_output('/sys/devices/system/cpu/cpu*/cpufreq/scaling_governor')\n if output == None:\n return None\n l = output.split('\\n')\n ret.append(l[0])\n for ll in l:\n if ll not in ret:\n ret.append(ll)\n return ret\n\n def get_single_CPU_conf_by_id(self, id):\n return self.cores[id]\n\nclass Single_CPU_core_conf:\n def __init__(self, cpu_id, core_num, numa_node):\n self.cpu_id = cpu_id\n self.core_num = core_num\n self.numa_node = numa_node\n\n\"\"\"\nMemory related configurations\n\"\"\"\n\nclass Memory_conf:\n def __init__(self):\n self.memroy_total_size = self.__get_memory_total_size()\n self.memory_DIMM_num = self.__get_memory_DIMM_num()\n if self.memory_DIMM_num == 0:\n #Not running in a normal physical host env\n globalvar.NORMAL_PHY_HOST_MEM = False\n return\n self.memory_channels_num = self.__get_memory_channels_num()\n self.memory_DIMM_per_channel = self.memory_DIMM_num / self.memory_channels_num\n self.dmidecode_output = self.__get_dmidecode_output()\n self.dimms = []\n self.__init_memory_DIMMs()\n\n \"\"\"\n Memory related utility functions\n \"\"\"\n def __get_memory_total_size(self):\n cmd = 'cat /proc/meminfo'\n total = util.str_get_specific_value_after_colon(cmd, 'MemTotal')\n return total\n\n def __get_memory_DIMM_num(self):\n cmd = 'dmidecode -t memory | grep Locator | grep DIMM |wc -l'\n return util.int_cmd_output(cmd)\n\n def __get_memory_channels_num(self):\n cmd = 'dmidecode -t memory | grep Locator | grep DIMM | grep 1 |wc -l'\n return util.int_cmd_output(cmd)\n\n def __get_dmidecode_output(self):\n cmd = 'dmidecode -t memory'\n output = util.str_cmd_output(cmd)\n l = output.split('\\n')\n return l\n\n def __init_memory_DIMMs(self):\n for i in range(self.memory_DIMM_num):\n locator = self.__get_mem_dimm_locator(i)\n size = self.__get_mem_dimm_size(i)\n speed = self.__get_mem_dimm_speed(i)\n conf_speed = self.__get_mem_conf_speed(i)\n node = self.__get_mem_bank_locator(i)\n dimm = Memory_DIMM(locator = locator, size = size,\n speed = speed, conf_speed = conf_speed,\n node = node)\n self.dimms.append(dimm)\n\n def __get_mem_dimm_spec_conf(self, conf, index):\n cnt = 0\n for l in self.dmidecode_output:\n if l.find(conf) != -1:\n if cnt == index:\n return l.split(\":\")[1].strip()\n cnt = cnt + 1\n return None\n\n def __get_mem_dimm_locator(self, index):\n return self.__get_mem_dimm_spec_conf(\"Locator: DIMM\", index)\n\n def __get_mem_dimm_size(self, index):\n return self.__get_mem_dimm_spec_conf(\"Size\", index)\n\n def __get_mem_dimm_speed(self, index):\n cnt = 0\n for l in self.dmidecode_output:\n if l.find(\"Speed\") != -1 and l.find(\"Configured\") == -1:\n if cnt == index:\n speed = l.split(\":\")[1].strip()\n if speed != \"Unknown\":\n return int(speed.split(\" \")[0].strip())\n else:\n return speed\n cnt = cnt + 1\n return None\n\n def __get_mem_conf_speed(self, index):\n speed = self.__get_mem_dimm_spec_conf(\"Configured Clock Speed\", index)\n if speed == None:\n return \"Unknown\"\n if speed != \"Unknown\":\n return int(speed.split(\" \")[0].strip())\n else:\n return speed\n\n def __get_mem_bank_locator(self, index):\n return self.__get_mem_dimm_spec_conf(\"Bank Locator\", index)\n\nclass Memory_DIMM:\n def __init__(self, locator, size, speed, conf_speed, node):\n self.locator = locator\n self.memory_size = size\n self.memory_speed = speed\n self.memory_config_speed = conf_speed\n self.bank_node = node\n\n\n\"\"\"\nNIC related configurations\n\"\"\"\n\nclass Single_NIC_conf:\n def __init__(self, lspci_vv_output, code_name, rx_q_num, tx_q_num,\n numa_node, LnkCap, LnkSta, pci_addr,\n cap_mpl, ctl_mpl, mrq, target_link_speed,\n ker_drv):\n\n self.lspci_vv_output = lspci_vv_output\n self.nic_code_name = code_name\n self.rx_queue_num = rx_q_num\n self.tx_queue_num = tx_q_num\n self.NUMA_node = numa_node\n self.LnkCap = LnkCap\n self.LnkSta = LnkSta\n self.pcie_width = 0\n self.pcie_devcap_maxpayloadsize = cap_mpl\n self.pcie_devctl_maxpayloadsize = ctl_mpl\n self.pcie_maxreadreq = mrq\n self.pcie_targetlinkspeed = target_link_speed\n self.pci_address = pci_addr\n self.ker_drv_in_use = ker_drv\n\n\n\"\"\"\nclass Single_NIC_conf_82599(Single_NIC_conf):\n def __init__(self):\n super.__init__(self)\n\"\"\"\n\nclass NICs_conf:\n lspci_nic_cmd = 'lspci | grep Ether'\n\n def __init__(self):\n self.str_nic_pci_conf= self.print_nic_pci_conf()\n self.nic_total_num = self.get_nic_total_num()\n self.nics_conf = []\n self.init_all_nics_conf()\n\n \"\"\"\n NIC related utility functions\n \"\"\"\n def NIC_rx_queue_num(self):\n pass\n\n def NIC_tx_queue_num(self):\n pass\n\n def print_nic_pci_conf(self):\n output = os.popen(self.lspci_nic_cmd, 'r')\n return output.read()\n\n def get_nic_lspci_vv_output(self, pci_addr):\n command = 'lspci -s ' + pci_addr + ' -vv'\n return os.popen(command, 'r').read()\n\n def get_nic_total_num(self):\n command = self.lspci_nic_cmd + '|wc -l'\n output = os.popen(command, 'r')\n return int(output.read())\n\n def get_nic_pci_address(self, list_num):\n output = self.str_nic_pci_conf.splitlines()[list_num]\n return output[0 : 7]\n\n def get_nic_code_name(self, list_num):\n output = self.str_nic_pci_conf.splitlines()[list_num].split(':')[2]\n return output\n\n def get_nic_LnkCap(self, lspci_vv_output):\n loc = lspci_vv_output.rfind('LnkCap')\n str_tmp = lspci_vv_output[loc :]\n loc = str_tmp.find('Speed')\n return str_tmp[loc + 6 : loc + 11]\n\n def get_nic_LnkSta(self, lspci_vv_output):\n loc = lspci_vv_output.find('LnkSta')\n str_tmp = lspci_vv_output[loc :]\n loc = str_tmp.find('Speed')\n return str_tmp[loc + 6 : loc + 11]\n\n def get_nic_numa_node(self, lspci_vv_output):\n loc = lspci_vv_output.find('NUMA node')\n if loc == -1:\n return 0\n else:\n return int(lspci_vv_output[loc + 11 : loc + 12])\n\n def get_nic_devcap_maxpayload(self, lspci_vv_output):\n loc = lspci_vv_output.find('DevCap')\n if loc == -1:\n return None\n maxpayload = lspci_vv_output[loc + 19: loc + 23]\n return int(maxpayload)\n\n def get_nic_devctl_maxpayload(self, lspci_vv_output):\n loc = lspci_vv_output.find('DevCtl')\n if loc == -1:\n return None\n loc1 = lspci_vv_output[loc :].find('MaxPayload')\n if loc1 == -1:\n return None\n maxpayload = lspci_vv_output[loc + loc1 + 11: loc + loc1 + 15]\n return int(maxpayload)\n\n def get_nic_max_read_req(self, lspci_vv_output):\n loc = lspci_vv_output.find('MaxReadReq')\n if loc == -1:\n return None\n loc1 = lspci_vv_output[loc :].find('bytes')\n if loc1 == -1:\n return None\n maxreadreq = lspci_vv_output[loc + 10 : loc + loc1]\n return int(maxreadreq)\n\n def get_nic_target_link_speed(self, lspci_vv_output):\n loc = lspci_vv_output.find('Target Link Speed')\n if loc == -1:\n return None\n loc1 = lspci_vv_output[loc :].find('GT')\n tls = lspci_vv_output[loc + 19 : loc + loc1]\n return tls + 'GT/s'\n\n def get_nic_ker_drv_in_use(self, lspci_vv_output):\n loc = lspci_vv_output.find('Kernel driver in use')\n str_tmp = lspci_vv_output[loc :]\n return str_tmp[22 : 37]\n\n def init_single_nic_conf(self, list_num):\n pci_addr = self.get_nic_pci_address(list_num)\n lspci_vv_output = self.get_nic_lspci_vv_output(pci_addr)\n code_name = self.get_nic_code_name(list_num)\n numa_node = self.get_nic_numa_node(lspci_vv_output)\n LnkCap = self.get_nic_LnkCap(lspci_vv_output)\n LnkSta = self.get_nic_LnkSta(lspci_vv_output)\n devcap_maxpayload = self.get_nic_devcap_maxpayload(lspci_vv_output)\n devctl_maxpayload = self.get_nic_devctl_maxpayload(lspci_vv_output)\n max_read_req = self.get_nic_max_read_req(lspci_vv_output)\n tls = self.get_nic_target_link_speed(lspci_vv_output)\n ker_drv = self.get_nic_ker_drv_in_use(lspci_vv_output)\n\n sig_nic = Single_NIC_conf(lspci_vv_output = lspci_vv_output,\n code_name = code_name, rx_q_num = 0,\n tx_q_num = 0, numa_node = numa_node,\n LnkCap = LnkCap, LnkSta = LnkSta,\n cap_mpl = devcap_maxpayload, ctl_mpl = devctl_maxpayload,\n mrq = max_read_req, target_link_speed = tls,\n pci_addr = pci_addr, ker_drv = ker_drv)\n\n self.nics_conf.append(sig_nic)\n\n def init_all_nics_conf(self):\n for i in range(self.nic_total_num):\n self.init_single_nic_conf(i)\n","sub_path":"testcases/utility/hardware.py","file_name":"hardware.py","file_ext":"py","file_size_in_byte":13688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"228812235","text":"import random\n# helper functions from notes\n\ndef make2dList(rows, cols, value = (0,0)):\n a=[]\n for row in range(rows): a += [[value]*cols]\n return a\n\ndef maxItemLength(a):\n maxLen = 0\n rows = len(a)\n cols = len(a[0])\n for row in range(rows):\n for col in range(cols):\n maxLen = max(maxLen, len(str(a[row][col])))\n return maxLen\n\ndef print2dList(a):\n if (a == []):\n print([])\n return\n rows = len(a)\n cols = len(a[0])\n fieldWidth = maxItemLength(a)\n print(\"[ \", end=\"\")\n for row in range(rows):\n if (row > 0): print(\"\\n \", end=\"\")\n print(\"[ \", end=\"\")\n for col in range(cols):\n if (col > 0): print(\", \", end=\"\")\n formatSpec = \"%\" + str(fieldWidth) + \"s\"\n print(formatSpec % str(a[row][col]), end=\"\")\n print(\" ]\", end=\"\")\n print(\"]\")\n\nclass GameMap(object):\n def __init__(self, width=10, height=10, complexity=2):\n self.wallGrid = []\n self.width = width\n self.height = height\n self.EMPTY = (0,0)#(0,0)\n self.WALL = (1,1) #(1,1)\n self.SAFE = 2\n self.complexity = complexity\n \n def generateMaze(self):\n height = self.height\n width = self.width\n self.wallGrid = make2dList(height, width)\n for row in range(height):\n self.wallGrid[row][0] = self.WALL #left border\n self.wallGrid[row][self.width-1] = self.WALL #right border\n for col in range(self.width):\n self.wallGrid[0][col] = self.WALL #top border\n self.wallGrid[self.height-1][col] = self.WALL #bot border\n print2dList(self.wallGrid)\n self.wallGrid[1][self.width-4] = self.SAFE\n self.wallGrid[1][self.width-3] = self.SAFE #door in upper right\n self.wallGrid[1][self.width-2] = self.SAFE #spawn here or randomly\n self.wallGrid[2][self.width-2] = self.SAFE\n self.wallGrid[self.height-2][1] = self.SAFE #key in bottom right\n self.wallGrid[self.height-2][2] = self.SAFE\n self.wallGrid[self.height-3][1] = self.SAFE\n self.randomizeChamber(0,0,self.width, self.height)\n print2dList(self.wallGrid)\n for row in range(self.height):\n for col in range(self.width):\n val = self.wallGrid[row][col]\n if val == self.EMPTY or val == self.SAFE: \n self.wallGrid[row][col] = (0,0)\n elif val == self.WALL:\n self.wallGrid[row][col] = (1,1)\n self.wallGrid[1][self.width-1] = (1,5) #door\n #START CELL = (1,width-2)\n self.wallGrid[2][self.width-1] = (1,3) #doorinstr\n self.wallGrid[self.height-1][1] = (1,4) #key\n #END CELL = (height-2, 1)\n self.wallGrid[self.height-1][2] = (1,8) #keyinstr\n #print2dList(self.wallGrid)\n for row in range(len(self.wallGrid)):\n for col in range(len(self.wallGrid[0])):\n if self.wallGrid[row][col][1] == 5:\n self.doorPosX, self.doorPosY = col, row\n elif self.wallGrid[row][col][1] == 4:\n self.keyPosX, self.keyPosY = col, row\n \n def randomizeChamber(self, row, col, width, height, depth = 0):\n #print(\"chamber top-left: %d,%d\" %(row, col))\n #print(\"chamber bot-right: %d,%d\"%(row + height-1, col+width-1))\n if width <= 4 or height <= 4 or depth==self.complexity: #split this up and place the walls separately for small spaces\n return None\n randRow = random.randint(row+2, row + height-3)\n randCol = random.randint(col+2, col + width-3)\n #print(\"randRow %d\" %randRow)\n #print(\"randCol %d\" %randCol)\n randCompleteWall = random.randint(1,4)\n wall1hole = random.randint(row+1, randRow-1)\n wall2hole = random.randint(col+1, randCol-1)\n wall3hole = random.randint(randRow+1, row + height-2)\n wall4hole = random.randint(randCol+1, col + width-2) \n for x in range(row+1, row + height-1):\n if self.wallGrid[x][randCol] == self.EMPTY:\n self.wallGrid[x][randCol] = self.WALL \n for y in range(col+1, col + width-1):\n if self.wallGrid[randRow][y] == self.EMPTY:\n self.wallGrid[randRow][y] = self.WALL\n if randCompleteWall != 1:\n #print(\"wall1 hole %d \" %wall1hole)\n self.wallGrid[wall1hole][randCol] = self.SAFE\n self.wallGrid[wall1hole][randCol-1] = self.SAFE\n self.wallGrid[wall1hole][randCol+1] = self.SAFE\n if randCompleteWall != 2:\n #print(\"wall2 hole %d \" %wall2hole)\n self.wallGrid[randRow][wall2hole] = self.SAFE\n self.wallGrid[randRow+1][wall2hole] = self.SAFE\n self.wallGrid[randRow-1][wall2hole] = self.SAFE\n if randCompleteWall != 3:\n #print(\"wall3 hole %d \" %wall3hole)\n self.wallGrid[wall3hole][randCol] = self.SAFE\n self.wallGrid[wall3hole][randCol+1] = self.SAFE\n self.wallGrid[wall3hole][randCol-1] = self.SAFE\n if randCompleteWall != 4:\n #print(\"wall4 hole %d \" %wall4hole)\n self.wallGrid[randRow][wall4hole] = self.SAFE\n self.wallGrid[randRow+1][wall4hole] = self.SAFE\n self.wallGrid[randRow-1][wall4hole] = self.SAFE\n \n #self.randomizeChamber(row, col, width, height)\n self.randomizeChamber(0, 0, randCol, randRow, depth+1)#topleft\n self.randomizeChamber(0, randCol, self.width-randCol, randRow+1, depth+1)#top right\n self.randomizeChamber(randRow, 0, randCol+1, self.height-randRow, depth+1)#botleft\n self.randomizeChamber(randRow, randCol, self.width-randCol, self.height-randRow, depth+1)#botright\n print(\"randomized\")\n \n def testMaze(self):\n self.startCell = (endX, endY) = (self.keyPosX,self.keyPosY-1)\n self.endCell = (startX, startY) = (self.doorPosX-1, self.doorPosY)\n return None#isLegalMaze((startX, startY),(endX, endY))\n \n \"\"\"def isLegalMaze(self,solution = []):\n if the problem is solved then:\n return the solution\nelse:\n for each legal move:\n do the move\n try to recursively solve the problem\n if the problem is solved:\n return the solution # woohoo!\n undo the move\n fail # we tried all legal moves, none worked\"\"\"\n\nfor i in range(1):\n map = GameMap()\n map.generateMaze()\n print2dList(map.wallGrid)\n print(map.testMaze())","sub_path":"foo.py","file_name":"foo.py","file_ext":"py","file_size_in_byte":6546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"98066978","text":"\"\"\"\nimport socket\nfrom numpy import *\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((\"localhost\", 2333))\ns.listen(1)\n\n\ndef detect(str_in):\n\tprint(str_in.decode())\n\n\nprint('Now working...')\n\nwhile True:\n\tconn, address = s.accept()\n\tdata = conn.recv(1024)\n\tconn.close()\n\tdetect(data)\n\"\"\"\n\n\nfrom test import *\nfrom client import *\nimport time\n\n\ndef run_server():\n\tn = int(input('Please input the number of nodes (n > 1): '))\n\tif n < 2:\n\t\traise ValueError('The number of nodes should be greater than 1')\n\tg = Graph(n)\n\tclients = [Client(i) for i in range(n)]\n\twhile True:\n\t\tg.display()\n\t\tstart = time.time()\n\t\tfor i in range(1, n):\n\t\t\tcost, order = dijkstra(0, i, g)\n\t\t\tprint('Node: {}, Cost: {}, Order: {}'.format(i, cost, order))\n\t\t\t# sending message\n\t\t\tclients[0].send(order, clients)\n\t\tend = time.time()\n\t\tprint('Total time: {}s'.format(end - start))\n\t\t# For convenience, use system pause to represent every 10s passed\n\t\tos.system('pause')\n\t\t# Generate a new graph\n\t\tg.generate()\n\n\nif __name__ == '__main__':\n\trun_server()\n","sub_path":"DataStructure/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"362463632","text":"import pandas as pd\nimport numpy as np\nimport datetime \nimport pandas_datareader as web\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\n\nstart = datetime.datetime(2012 , 1 , 1)\nend = datetime.date.today()\n\ngoogle = web.DataReader (\"GOOGL\" , \"yahoo\" , start , end)\n#+------------------------------------------------------------------+\n#| | \n#| 分析google股票自2012年起 只要87日均線>284日均線就買進 |\n#| |\n#| 反之跌破賣出,並計算總獲利截至2019/03/29 |\n#| |\n#+------------------------------------------------------------------+\ngoogle[\"tomorrow\"] = google[\"Close\"].shift(-1)\ngoogle[\"diff\"] = google[\"tomorrow\"] - google[\"Close\"]\ngoogle[\"return\"] = google[\"diff\"] / google [\"Close\"] \ngoogle[\"direction\"] = [1 if google.loc[ei,\"diff\"] > 0 else -1 for ei in google.index]\ngoogle[\"ma87\"] = google[\"Close\"].rolling(87).mean() #87日均線\ngoogle[\"ma284\"] = google[\"Close\"].rolling(284).mean() #284日均線\ngoogle[\"share\"] = [1 if google.loc[ei,\"ma87\"] > google.loc[ei,\"ma284\"] else 0 for ei in google.index] #當ma87>ma284進場\ngoogle[\"profit\"] = [google.loc[ei,\"tomorrow\"] - google.loc[ei , \"Close\"] if google.loc[ei ,\"share\"] ==1 else 0 for ei in google.index]\ngoogle[\"wealth\"]= google[\"profit\"].cumsum()\n\n#+------------------------------------------------------------------+\n#| |\n#| 用 matplotlib模組畫出 價格和兩條均線關係圖 | \n#| |\n#| 2015/7月時候黃金交叉買進 |\n#| |\n#+------------------------------------------------------------------+\n\n\nplt.title(\"GOOGL\",size=30)\nplt.xlabel(\"Time\",size=20)\nplt.ylabel(\"USD\", size= 20)\nplt.plot(google.loc[:,\"Close\"], alpha = 0.5)\nplt.plot(google[\"ma87\"] ,label = \"ma87\", color = \"red\")\nplt.plot(google[\"ma284\"] , color= \"green\")\nplt.legend()\nplt.show()\n\n\nmu = google[\"return\"].mean() #平均值\nsigma = google [\"return\"].std(ddof=1) #標準差\n\n#den = pd.DataFrame()\n# den[\"x\"] = np.arange(-0.1 , 0.1 ,0.01)\n# den[\"pdf\"] = norm.pdf(den[\"x\"] , mu ,sigma)\n# # plt.ylim(0,100)\n# plt.plot(den[\"x\"],den[\"pdf\"])\n# plt.fill_between(x=np.arange(-0.1,-0.01,0.0001),\n# y2=0,\n# y1=norm.pdf(np.arange(-0.1,-0.01,0.0001), mu ,sigma),\n# color=\"pink\",\n# alpha= 0.5,\n# )\n# plt.show()\ndensity_google_cdf = norm.cdf(-0.05 , mu ,sigma)\n\ndensity_google_ppf = norm.ppf(0.05 , mu ,sigma)\n\nmu220=220*mu \nsigma220=220**0.5*sigma\nprobability_drop_20 = norm.cdf(-0.2,mu220,sigma220)\n\nprint(\"一日下跌5%的機率為:\" , density_google_cdf)\nprint(\"每日有5%下跌幅度為:\", density_google_ppf )\nprint(\"一年220約交易日下跌20%機率\",probability_drop_20)","sub_path":"google.py","file_name":"google.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"468532699","text":"from ..utils import DataikuException\nfrom ..utils import DataikuUTF8CSVReader\nfrom ..utils import DataikuStreamedHttpUTF8CSVReader\nimport json\nimport time\nfrom .metrics import ComputedMetrics\nfrom .utils import DSSDatasetSelectionBuilder, DSSFilterBuilder\n\nclass PredictionSplitParamsHandler(object):\n \"\"\"Object to modify the train/test splitting params.\"\"\"\n\n def __init__(self, mltask_settings):\n \"\"\"Do not call directly, use :meth:`DSSMLTaskSettings.get_split_params`\"\"\"\n self.mltask_settings = mltask_settings\n\n def set_split_random(self, train_ratio = 0.8, selection = None, dataset_name=None):\n \"\"\"\n Sets the train/test split to random splitting of an extract of a single dataset\n\n :param float train_ratio: Ratio of rows to use for train set. Must be between 0 and 1\n :param object selection: A :class:`~dataikuapi.dss.utils.DSSDatasetSelectionBuilder` to build the settings of the extract of the dataset. May be None (won't be changed)\n :param str dataset_name: Name of dataset to split. If None, the main dataset used to create the visual analysis will be used.\n \"\"\"\n sp = self.mltask_settings[\"splitParams\"]\n sp[\"ttPolicy\"] = \"SPLIT_SINGLE_DATASET\"\n if selection is not None:\n if isinstance(selection, DSSDatasetSelectionBuilder):\n sp[\"ssdSelection\"] = selection.build()\n else:\n sp[\"ssdSelection\"] = selection\n\n sp[\"ssdTrainingRatio\"] = train_ratio\n sp[\"kfold\"] = False\n\n if dataset_name is not None:\n sp[\"ssdDatasetSmartName\"] = dataset_name\n\n def set_split_kfold(self, n_folds = 5, selection = None, dataset_name=None):\n \"\"\"\n Sets the train/test split to k-fold splitting of an extract of a single dataset\n\n :param int n_folds: number of folds. Must be greater than 0\n :param object selection: A :class:`~dataikuapi.dss.utils.DSSDatasetSelectionBuilder` to build the settings of the extract of the dataset. May be None (won't be changed)\n :param str dataset_name: Name of dataset to split. If None, the main dataset used to create the visual analysis will be used.\n \"\"\"\n sp = self.mltask_settings[\"splitParams\"]\n sp[\"ttPolicy\"] = \"SPLIT_SINGLE_DATASET\"\n if selection is not None:\n if isinstance(selection, DSSDatasetSelectionBuilder):\n sp[\"ssdSelection\"] = selection.build()\n else:\n sp[\"ssdSelection\"] = selection\n\n sp[\"kfold\"] = True\n sp[\"nFolds\"] = n_folds\n\n if dataset_name is not None:\n sp[\"ssdDatasetSmartName\"] = dataset_name\n\n def set_split_explicit(self, train_selection, test_selection, dataset_name=None, test_dataset_name=None, train_filter=None, test_filter=None):\n \"\"\"\n Sets the train/test split to explicit extract of one or two dataset(s)\n\n :param object train_selection: A :class:`~dataikuapi.dss.utils.DSSDatasetSelectionBuilder` to build the settings of the extract of the train dataset. May be None (won't be changed)\n :param object test_selection: A :class:`~dataikuapi.dss.utils.DSSDatasetSelectionBuilder` to build the settings of the extract of the test dataset. May be None (won't be changed)\n :param str dataset_name: Name of dataset to use for the extracts. If None, the main dataset used to create the ML Task will be used.\n :param str test_dataset_name: Name of a second dataset to use for the test data extract. If None, both extracts are done from dataset_name\n :param object train_filter: A :class:`~dataikuapi.dss.utils.DSSFilterBuilder` to build the settings of the filter of the train dataset. May be None (won't be changed)\n :param object test_filter: A :class:`~dataikuapi.dss.utils.DSSFilterBuilder` to build the settings of the filter of the test dataset. May be None (won't be changed)\n \"\"\"\n sp = self.mltask_settings[\"splitParams\"]\n if dataset_name is None:\n raise Exception(\"For explicit splitting a dataset_name is mandatory\")\n if test_dataset_name is None or test_dataset_name == dataset_name:\n sp[\"ttPolicy\"] = \"EXPLICIT_FILTERING_SINGLE_DATASET\"\n train_split ={}\n test_split = {}\n sp['efsdDatasetSmartName'] = dataset_name\n sp['efsdTrain'] = train_split\n sp['efsdTest'] = test_split\n else: \n sp[\"ttPolicy\"] = \"EXPLICIT_FILTERING_TWO_DATASETS\"\n train_split ={'datasetSmartName' : dataset_name}\n test_split = {'datasetSmartName' : test_dataset_name}\n sp['eftdTrain'] = train_split\n sp['eftdTest'] = test_split\n\n if train_selection is not None:\n if isinstance(train_selection, DSSDatasetSelectionBuilder):\n train_split[\"selection\"] = train_selection.build()\n else:\n train_split[\"selection\"] = train_selection\n if test_selection is not None:\n if isinstance(test_selection, DSSDatasetSelectionBuilder):\n test_split[\"selection\"] = test_selection.build()\n else:\n test_split[\"selection\"] = test_selection\n\n if train_filter is not None:\n if isinstance(train_filter, DSSFilterBuilder):\n train_split[\"filter\"] = train_filter.build()\n else:\n train_split[\"filter\"] = train_filter\n if test_filter is not None:\n if isinstance(test_filter, DSSFilterBuilder):\n test_split[\"filter\"] = test_filter.build()\n else:\n test_split[\"filter\"] = test_filter\n\n\nclass DSSMLTaskSettings(object):\n \"\"\"\n Object to read and modify the settings of a ML task.\n\n Do not create this object directly, use :meth:`DSSMLTask.get_settings()` instead\n \"\"\"\n def __init__(self, client, project_key, analysis_id, mltask_id, mltask_settings):\n self.client = client\n self.project_key = project_key\n self.analysis_id = analysis_id\n self.mltask_id = mltask_id\n self.mltask_settings = mltask_settings\n\n def get_raw(self):\n \"\"\"\n Gets the raw settings of this ML Task. This returns a reference to the raw settings, not a copy,\n so changes made to the returned object will be reflected when saving.\n\n :rtype: dict\n \"\"\"\n return self.mltask_settings\n\n def get_split_params(self):\n \"\"\"\n Gets an object to modify train/test splitting params.\n\n :rtype: :class:`PredictionSplitParamsHandler`\n \"\"\"\n return PredictionSplitParamsHandler(self.mltask_settings)\n\n\n def get_feature_preprocessing(self, feature_name):\n \"\"\"\n Gets the feature preprocessing params for a particular feature. This returns a reference to the\n feature's settings, not a copy, so changes made to the returned object will be reflected when saving\n\n :return: A dict of the preprocessing settings for a feature\n :rtype: dict \n \"\"\"\n return self.mltask_settings[\"preprocessing\"][\"per_feature\"][feature_name]\n\n def foreach_feature(self, fn, only_of_type = None):\n \"\"\"\n Applies a function to all features (except target)\n\n :param function fn: Function that takes 2 parameters: feature_name and feature_params and returns modified feature_params\n :param str only_of_type: if not None, only applies to feature of the given type. Can be one of ``CATEGORY``, ``NUMERIC``, ``TEXT`` or ``VECTOR``\n \"\"\"\n import copy\n new_per_feature = {}\n for (k, v) in self.mltask_settings[\"preprocessing\"][\"per_feature\"].items():\n if v[\"role\"] == \"TARGET\" or (only_of_type is not None and v[\"type\"] != only_of_type):\n new_per_feature[k] = v\n else:\n new_per_feature[k] = fn(k, copy.deepcopy(v))\n self.mltask_settings[\"preprocessing\"][\"per_feature\"] = new_per_feature\n\n def reject_feature(self, feature_name):\n \"\"\"\n Marks a feature as rejected and not used for training\n :param str feature_name: Name of the feature to reject\n \"\"\"\n self.get_feature_preprocessing(feature_name)[\"role\"] = \"REJECT\"\n\n def use_feature(self, feature_name):\n \"\"\"\n Marks a feature as input for training\n :param str feature_name: Name of the feature to reject\n \"\"\"\n self.get_feature_preprocessing(feature_name)[\"role\"] = \"INPUT\"\n\n def use_sample_weighting(self, feature_name):\n \"\"\"\n Uses a feature as sample weight\n :param str feature_name: Name of the feature to use\n \"\"\"\n self.remove_sample_weighting()\n if not feature_name in self.mltask_settings[\"preprocessing\"][\"per_feature\"]:\n raise ValueError(\"Feature %s doesn't exist in this ML task, can't use as weight\" % feature_name)\n self.mltask_settings['weight']['weightMethod'] = 'SAMPLE_WEIGHT'\n self.mltask_settings['weight']['sampleWeightVariable'] = feature_name\n self.mltask_settings['preprocessing']['per_feature'][feature_name]['role'] = 'WEIGHT'\n\n\n def remove_sample_weighting(self):\n \"\"\"\n Remove sample weighting. If a feature was used as weight, it's set back to being an input feature\n \"\"\"\n self.mltask_settings['weight']['weightMethod'] = 'NO_WEIGHTING'\n for feature_name in self.mltask_settings['preprocessing']['per_feature']:\n if self.mltask_settings['preprocessing']['per_feature'][feature_name]['role'] == 'WEIGHT':\n self.mltask_settings['preprocessing']['per_feature'][feature_name]['role'] = 'INPUT'\n\n def get_algorithm_settings(self, algorithm_name):\n \"\"\"\n Gets the training settings for a particular algorithm. This returns a reference to the\n algorithm's settings, not a copy, so changes made to the returned object will be reflected when saving.\n\n This method returns a dictionary of the settings for this algorithm.\n All algorithm dicts have at least an \"enabled\" key in the dictionary.\n The 'enabled' key indicates whether this algorithm will be trained\n\n Other settings are algorithm-dependent and are the various hyperparameters of the \n algorithm. The precise keys for each algorithm are not all documented. You can print\n the returned dictionary to learn more about the settings of each particular algorithm\n\n Please refer to the documentation for details on available algorithms.\n\n :param str algorithm_name: Name (in capitals) of the algorithm.\n :return: A dict of the settings for an algorithm\n :rtype: dict \n \"\"\"\n if algorithm_name in self.__class__.algorithm_remap:\n algorithm_name = self.__class__.algorithm_remap[algorithm_name]\n\n return self.mltask_settings[\"modeling\"][algorithm_name.lower()]\n\n def set_algorithm_enabled(self, algorithm_name, enabled):\n \"\"\"\n Enables or disables an algorithm based on its name.\n\n Please refer to the documentation for details on available algorithms.\n\n :param str algorithm_name: Name (in capitals) of the algorithm.\n \"\"\"\n self.get_algorithm_settings(algorithm_name)[\"enabled\"] = enabled\n\n def set_metric(self, metric=None, custom_metric=None, custom_metric_greater_is_better=True, custom_metric_use_probas=False):\n \"\"\"\n Sets the score metric to optimize for a prediction ML Task\n\n :param str metric: metric to use. Leave empty to use a custom metric. You need to set the ``custom_metric`` value in that case\n :param str custom_metric: code of the custom metric\n :param bool custom_metric_greater_is_better: whether the custom metric is a score or a loss\n :param bool custom_metric_use_probas: whether to use the classes' probas or the predicted value (for classification)\n \"\"\"\n if custom_metric is None and metric is None:\n raise ValueError(\"Either metric or custom_metric must be defined\")\n self.mltask_settings[\"modeling\"][\"metrics\"][\"evaluationMetric\"] = metric if custom_metric is None else 'CUSTOM'\n self.mltask_settings[\"modeling\"][\"metrics\"][\"customEvaluationMetricCode\"] = custom_metric\n self.mltask_settings[\"modeling\"][\"metrics\"][\"customEvaluationMetricGIB\"] = custom_metric_greater_is_better\n self.mltask_settings[\"modeling\"][\"metrics\"][\"customEvaluationMetricNeedsProba\"] = custom_metric_use_probas\n\n def save(self):\n \"\"\"Saves back these settings to the ML Task\"\"\"\n\n self.client._perform_empty(\n \"POST\", \"/projects/%s/models/lab/%s/%s/settings\" % (self.project_key, self.analysis_id, self.mltask_id),\n body = self.mltask_settings)\n\nclass DSSPredictionMLTaskSettings(DSSMLTaskSettings):\n __doc__ = []\n algorithm_remap = {\n \"SVC_CLASSIFICATION\" : \"svc_classifier\",\n \"SGD_CLASSIFICATION\" : \"sgd_classifier\",\n \"SPARKLING_DEEP_LEARNING\" : \"deep_learning_sparkling\",\n \"SPARKLING_GBM\" : \"gbm_sparkling\",\n \"SPARKLING_RF\" : \"rf_sparkling\",\n \"SPARKLING_GLM\" : \"glm_sparkling\",\n \"SPARKLING_NB\" : \"nb_sparkling\",\n \"XGBOOST_CLASSIFICATION\" : \"xgboost\",\n \"XGBOOST_REGRESSION\" : \"xgboost\",\n \"MLLIB_LOGISTIC_REGRESSION\" : \"mllib_logit\",\n \"MLLIB_LINEAR_REGRESSION\" : \"mllib_linreg\",\n \"MLLIB_RANDOM_FOREST\" : \"mllib_rf\"\n }\n\nclass DSSClusteringMLTaskSettings(DSSMLTaskSettings):\n __doc__ = []\n algorithm_remap = {\n \"DBSCAN\" : \"db_scan_clustering\",\n }\n\n\n\nclass DSSTrainedModelDetails(object):\n def __init__(self, details, snippet, saved_model=None, saved_model_version=None, mltask=None, mltask_model_id=None):\n self.details = details\n self.snippet = snippet\n self.saved_model = saved_model\n self.saved_model_version = saved_model_version\n self.mltask = mltask\n self.mltask_model_id = mltask_model_id\n\n def get_raw(self):\n \"\"\"\n Gets the raw dictionary of trained model details\n \"\"\"\n return self.details\n\n def get_raw_snippet(self):\n \"\"\"\n Gets the raw dictionary of trained model snippet. \n The snippet is a lighter version than the details.\n \"\"\"\n return self.snippet\n\n def get_train_info(self):\n \"\"\"\n Returns various information about the train process (size of the train set, quick description, timing information)\n\n :rtype: dict\n \"\"\"\n return self.details[\"trainInfo\"]\n\n def get_user_meta(self):\n \"\"\"\n Gets the user-accessible metadata (name, description, cluster labels, classification threshold)\n Returns the original object, not a copy. Changes to the returned object are persisted to DSS by calling\n :meth:`save_user_meta`\n\n \"\"\"\n return self.details[\"userMeta\"]\n\n def save_user_meta(self):\n um = self.details[\"userMeta\"]\n\n if self.mltask is not None:\n self.mltask.client._perform_empty(\n \"PUT\", \"/projects/%s/models/lab/%s/%s/models/%s/user-meta\" % (self.mltask.project_key,\n self.mltask.analysis_id, self.mltask.mltask_id, self.mltask_model_id), body = um)\n else:\n self.saved_model.client._perform_empty(\n \"PUT\", \"/projects/%s/savedmodels/%s/versions/%s/user-meta\" % (self.saved_model.project_key,\n self.saved_model.sm_id, self.saved_model_version), body = um)\n\nclass DSSTreeNode(object):\n def __init__(self, tree, i):\n self.tree = tree\n self.i = i\n\n def get_left_child(self):\n \"\"\"Gets a :class:`dataikuapi.dss.ml.DSSTreeNode` representing the left side of the tree node (or None)\"\"\"\n left = self.tree.tree['leftChild'][self.i]\n if left < 0:\n return None\n else:\n return DSSTreeNode(self.tree, left)\n\n def get_right_child(self):\n \"\"\"Gets a :class:`dataikuapi.dss.ml.DSSTreeNode` representing the right side of the tree node (or None)\"\"\"\n left = self.tree.tree['rightChild'][self.i]\n if left < 0:\n return None\n else:\n return DSSTreeNode(self.tree, left)\n\n def get_split_info(self):\n \"\"\"Gets the information on the split, as a dict\"\"\"\n info = {}\n features = self.tree.tree.get(\"feature\", None)\n probas = self.tree.tree.get(\"probas\", None)\n leftCategories = self.tree.tree.get(\"leftCategories\", None)\n impurities = self.tree.tree.get(\"impurity\", None)\n predicts = self.tree.tree.get(\"predict\", None)\n thresholds = self.tree.tree.get(\"threshold\", None)\n nSamples = self.tree.tree.get(\"nSamples\", None)\n info['feature'] = self.tree.feature_names[features[self.i]] if features is not None else None\n info['probas'] = probas[self.i] if probas is not None else None\n info['leftCategories'] = leftCategories[self.i] if leftCategories is not None else None\n info['impurity'] = impurities[self.i] if impurities is not None else None\n info['predict'] = predicts[self.i] if predicts is not None else None\n info['nSamples'] = nSamples[self.i] if nSamples is not None else None\n info['threshold'] = thresholds[self.i] if thresholds is not None else None\n return info\n \nclass DSSTree(object):\n def __init__(self, tree, feature_names):\n self.tree = tree\n self.feature_names = feature_names\n\n def get_raw(self):\n \"\"\"Gets the raw tree data structure\"\"\"\n return self.tree\n\n def get_root(self):\n \"\"\"Gets a :class:`dataikuapi.dss.ml.DSSTreeNode` representing the root of the tree\"\"\"\n return DSSTreeNode(self, 0)\n\nclass DSSTreeSet(object):\n def __init__(self, trees):\n self.trees = trees\n\n def get_raw(self):\n \"\"\"Gets the raw trees data structure\"\"\"\n return self.trees\n\n def get_feature_names(self):\n \"\"\"Gets the list of feature names (after dummification) \"\"\"\n return self.trees[\"featureNames\"]\n\n def get_trees(self):\n \"\"\"Gets the list of trees as :class:`dataikuapi.dss.ml.DSSTree` \"\"\"\n return [DSSTree(t, self.trees[\"featureNames\"]) for t in self.trees[\"trees\"]]\n\nclass DSSCoefficientPaths(object):\n def __init__(self, paths):\n self.paths = paths\n\n def get_raw(self):\n \"\"\"Gets the raw paths data structure\"\"\"\n return self.paths\n\n def get_feature_names(self):\n \"\"\"Get the feature names (after dummification)\"\"\"\n return self.paths['features']\n\n def get_coefficient_path(self, feature, class_index=0):\n \"\"\"Get the path of the feature\"\"\"\n i = self.paths['features'].index(feature)\n if i >= 0 and i < len(self.paths['path'][0][class_index]):\n n = len(self.paths['path'])\n return [self.paths['path'][j][class_index][i] for j in range(0, n)]\n else:\n return None\n\nclass DSSScatterPlots(object):\n def __init__(self, scatters):\n self.scatters = scatters\n\n def get_raw(self):\n \"\"\"Gets the raw scatters data structure\"\"\"\n return self.scatters\n\n def get_feature_names(self):\n \"\"\"Get the feature names (after dummification)\"\"\"\n feature_names = []\n for k in self.scatters['features']:\n feature_names.append(k)\n return feature_names\n\n def get_scatter_plot(self, feature_x, feature_y):\n \"\"\"Get the scatter plot between feature_x and feature_y\"\"\"\n ret = {'cluster':self.scatters['cluster'], 'x':self.scatters['features'].get(feature_x, None), 'y':self.scatters['features'].get(feature_x, None)}\n return ret\n\nclass DSSTrainedPredictionModelDetails(DSSTrainedModelDetails):\n \"\"\"\n Object to read details of a trained prediction model\n\n Do not create this object directly, use :meth:`DSSMLTask.get_trained_model_details()` instead\n \"\"\"\n\n def __init__(self, details, snippet, saved_model=None, saved_model_version=None, mltask=None, mltask_model_id=None):\n DSSTrainedModelDetails.__init__(self, details, snippet, saved_model, saved_model_version, mltask, mltask_model_id)\n\n def get_roc_curve_data(self):\n roc = self.details.get(\"perf\", {}).get(\"rocVizData\",{})\n if roc is None:\n raise ValueError(\"This model does not have ROC visualization data\")\n\n return roc\n\n def get_performance_metrics(self):\n \"\"\"\n Returns all performance metrics for this model.\n\n For binary classification model, this includes both \"threshold-independent\" metrics like AUC and\n \"threshold-dependent\" metrics like precision. Threshold-dependent metrics are returned at the\n threshold value that was found to be optimal during training.\n\n To get access to the per-threshold values, use the following:\n\n .. code-block:: python\n\n # Returns a list of tested threshold values\n details.get_performance()[\"perCutData\"][\"cut\"]\n # Returns a list of F1 scores at the tested threshold values\n details.get_performance()[\"perCutData\"][\"f1\"]\n # Both lists have the same length\n\n If K-Fold cross-test was used, most metrics will have a \"std\" variant, which is the standard deviation\n accross the K cross-tested folds. For example, \"auc\" will be accompanied with \"aucstd\"\n\n :returns: a dict of performance metrics values\n :rtype: dict\n \"\"\"\n import copy\n clean_snippet = copy.deepcopy(self.snippet)\n for x in [\"gridsearchData\", \"trainDate\", \"topImportance\", \"backendType\", \"userMeta\", \"sessionDate\", \"trainInfo\", \"fullModelId\", \"gridLength\", \"algorithm\", \"sessionId\"]:\n if x in clean_snippet:\n del clean_snippet[x]\n return clean_snippet\n\n\n def get_preprocessing_settings(self):\n \"\"\"\n Gets the preprocessing settings that were used to train this model\n\n :rtype: dict\n \"\"\"\n return self.details[\"preprocessing\"]\n\n def get_modeling_settings(self):\n \"\"\"\n Gets the modeling (algorithms) settings that were used to train this model.\n\n Note: the structure of this dict is not the same as the modeling params on the ML Task\n (which may contain several algorithm)\n\n :rtype: dict\n \"\"\"\n return self.details[\"modeling\"]\n\n def get_actual_modeling_params(self):\n \"\"\"\n Gets the actual / resolved parameters that were used to train this model, post\n hyperparameter optimization.\n\n :return: A dictionary, which contains at least a \"resolved\" key, which is a dict containing the post-optimization parameters\n :rtype: dict\n \"\"\"\n return self.details[\"actualParams\"]\n\n def get_trees(self):\n \"\"\"\n Gets the trees in the model (for tree-based models) \n\n :return: a DSSTreeSet object to interact with the trees\n :rtype: :class:`dataikuapi.dss.ml.DSSTreeSet`\n \"\"\"\n data = self.mltask.client._perform_json(\n \"GET\", \"/projects/%s/models/lab/%s/%s/models/%s/trees\" % (self.mltask.project_key, self.mltask.analysis_id, self.mltask.mltask_id, self.mltask_model_id))\n if data is None:\n raise ValueError(\"This model has no tree data\")\n return DSSTreeSet(data)\n\n def get_coefficient_paths(self):\n \"\"\"\n Gets the coefficient paths for Lasso models\n\n :return: a DSSCoefficientPaths object to interact with the coefficient paths\n :rtype: :class:`dataikuapi.dss.ml.DSSCoefficientPaths`\n \"\"\"\n data = self.mltask.client._perform_json(\n \"GET\", \"/projects/%s/models/lab/%s/%s/models/%s/coef-paths\" % (self.mltask.project_key, self.mltask.analysis_id, self.mltask.mltask_id, self.mltask_model_id))\n if data is None:\n raise ValueError(\"This model has no coefficient paths\")\n return DSSCoefficientPaths(data)\n\n\nclass DSSClustersFacts(object):\n def __init__(self, clusters_facts):\n self.clusters_facts = clusters_facts\n\n def get_raw(self):\n \"\"\"Gets the raws facts data structure\"\"\"\n return self.clusters_facts\n\n def get_cluster_size(self, cluster_index):\n \"\"\"Gets the size of a cluster identified by its index\"\"\"\n return self.clusters_facts[\"clusters\"][cluster_index][\"size\"]\n\n def get_facts_for_cluster(self, cluster_index):\n \"\"\"\n Gets all facts for a cluster identified by its index. Returns a list of dicts\n\n :rtype: list\n \"\"\"\n return self.clusters_facts[\"clusters\"][cluster_index][\"facts\"]\n\n def get_facts_for_cluster_and_feature(self, cluster_index, feature_name):\n \"\"\"\n Gets all facts for a cluster identified by its index, limited to a feature name. Returns a list of dicts\n\n :rtype: list\n \"\"\"\n return [x for x in self.get_facts_for_cluster(cluster_index) if x[\"feature_label\"] == feature_name]\n\n\nclass DSSTrainedClusteringModelDetails(DSSTrainedModelDetails):\n \"\"\"\n Object to read details of a trained clustering model\n\n Do not create this object directly, use :meth:`DSSMLTask.get_trained_model_details()` instead\n \"\"\"\n\n def __init__(self, details, snippet, saved_model=None, saved_model_version=None, mltask=None, mltask_model_id=None):\n DSSTrainedModelDetails.__init__(self, details, snippet, saved_model, saved_model_version, mltask, mltask_model_id)\n\n\n def get_raw(self):\n \"\"\"\n Gets the raw dictionary of trained model details\n \"\"\"\n return self.details\n\n def get_train_info(self):\n \"\"\"\n Returns various information about the train process (size of the train set, quick description, timing information)\n\n :rtype: dict\n \"\"\"\n return self.details[\"trainInfo\"]\n\n def get_facts(self):\n \"\"\"\n Gets the 'cluster facts' data, i.e. the structure behind the screen \"for cluster X, average of Y is Z times higher than average\n\n :rtype: :class:`DSSClustersFacts`\n \"\"\"\n return DSSClustersFacts(self.details[\"facts\"])\n\n def get_performance_metrics(self):\n \"\"\"\n Returns all performance metrics for this clustering model.\n :returns: a dict of performance metrics values\n :rtype: dict\n \"\"\"\n import copy\n clean_snippet = copy.deepcopy(self.snippet)\n for x in [\"fullModelId\", \"algorithm\", \"trainInfo\", \"userMeta\", \"backendType\", \"sessionId\", \"sessionDate\", \"facts\"]:\n if x in clean_snippet:\n del clean_snippet[x]\n return clean_snippet\n\n def get_preprocessing_settings(self):\n \"\"\"\n Gets the preprocessing settings that were used to train this model\n\n :rtype: dict\n \"\"\"\n return self.details[\"preprocessing\"]\n\n def get_modeling_settings(self):\n \"\"\"\n Gets the modeling (algorithms) settings that were used to train this model.\n\n Note: the structure of this dict is not the same as the modeling params on the ML Task\n (which may contain several algorithm)\n\n :rtype: dict\n \"\"\"\n return self.details[\"modeling\"]\n\n def get_actual_modeling_params(self):\n \"\"\"\n Gets the actual / resolved parameters that were used to train this model.\n :return: A dictionary, which contains at least a \"resolved\" key\n :rtype: dict\n \"\"\"\n return self.details[\"actualParams\"]\n\n def get_scatter_plots(self):\n \"\"\"\n Gets the cluster scatter plot data \n\n :return: a DSSScatterPlots object to interact with the scatter plots\n :rtype: :class:`dataikuapi.dss.ml.DSSScatterPlots`\n \"\"\"\n scatters = self.mltask.client._perform_json(\n \"GET\", \"/projects/%s/models/lab/%s/%s/models/%s/scatter-plots\" % (self.mltask.project_key, self.mltask.analysis_id, self.mltask.mltask_id, self.mltask_model_id))\n return DSSScatterPlots(scatters)\n\n\nclass DSSMLTask(object):\n \"\"\"A handle to interact with a MLTask for prediction or clustering in a DSS visual analysis\"\"\"\n def __init__(self, client, project_key, analysis_id, mltask_id):\n self.client = client\n self.project_key = project_key\n self.analysis_id = analysis_id\n self.mltask_id = mltask_id\n\n def delete(self):\n \"\"\"\n Delete the present ML task\n \"\"\"\n return self.client._perform_json(\n \"DELETE\", \"/projects/%s/models/lab/%s/%s/\" % (self.project_key, self.analysis_id, self.mltask_id))\n \n\n def wait_guess_complete(self):\n \"\"\"\n Waits for guess to be complete. This should be called immediately after the creation of a new ML Task\n (if the ML Task was created with wait_guess_complete=False),\n before calling ``get_settings`` or ``train``\n \"\"\"\n while True:\n status = self.get_status()\n if status.get(\"guessing\", \"???\") == False:\n break\n time.sleep(0.2)\n\n\n def get_status(self):\n \"\"\"\n Gets the status of this ML Task\n\n :return: a dict\n \"\"\"\n return self.client._perform_json(\n \"GET\", \"/projects/%s/models/lab/%s/%s/status\" % (self.project_key, self.analysis_id, self.mltask_id))\n \n\n def get_settings(self):\n \"\"\"\n Gets the settings of this ML Tasks\n\n :return: a DSSMLTaskSettings object to interact with the settings\n :rtype: :class:`dataikuapi.dss.ml.DSSMLTaskSettings`\n \"\"\"\n settings = self.client._perform_json(\n \"GET\", \"/projects/%s/models/lab/%s/%s/settings\" % (self.project_key, self.analysis_id, self.mltask_id))\n\n if settings[\"taskType\"] == \"PREDICTION\":\n return DSSPredictionMLTaskSettings(self.client, self.project_key, self.analysis_id, self.mltask_id, settings)\n else:\n return DSSClusteringMLTaskSettings(self.client, self.project_key, self.analysis_id, self.mltask_id, settings)\n\n def train(self, session_name=None, session_description=None):\n \"\"\"\n Trains models for this ML Task\n \n :param str session_name: name for the session\n :param str session_description: description for the session\n\n This method waits for train to complete. If you want to train asynchronously, use :meth:`start_train` and :meth:`wait_train_complete`\n\n This method returns the list of trained model identifiers. It returns models that have been trained for this train\n session, not all trained models for this ML task. To get all identifiers for all models trained across all training sessions,\n use :meth:`get_trained_models_ids`\n\n These identifiers can be used for :meth:`get_trained_model_snippet`, :meth:`get_trained_model_details` and :meth:`deploy_to_flow`\n\n :return: A list of model identifiers\n :rtype: list of strings\n \"\"\"\n train_ret = self.start_train(session_name, session_description)\n self.wait_train_complete()\n return self.get_trained_models_ids(session_id = train_ret[\"sessionId\"])\n\n def ensemble(self, model_ids=[], method=None):\n \"\"\"\n Create an ensemble model of a set of models\n \n :param list model_ids: A list of model identifiers\n :param str method: the ensembling method. One of: AVERAGE, PROBA_AVERAGE, MEDIAN, VOTE, LINEAR_MODEL, LOGISTIC_MODEL\n\n This method waits for the ensemble train to complete. If you want to train asynchronously, use :meth:`start_ensembling` and :meth:`wait_train_complete`\n\n This method returns the identifier of the trained ensemble.\n To get all identifiers for all models trained across all training sessions,\n use :meth:`get_trained_models_ids`\n\n This identifier can be used for :meth:`get_trained_model_snippet`, :meth:`get_trained_model_details` and :meth:`deploy_to_flow`\n\n :return: A model identifier\n :rtype: string\n \"\"\"\n train_ret = self.start_ensembling(model_ids, method)\n self.wait_train_complete()\n return train_ret\n\n\n def start_train(self, session_name=None, session_description=None):\n \"\"\"\n Starts asynchronously a new train session for this ML Task.\n\n :param str session_name: name for the session\n :param str session_description: description for the session\n\n This returns immediately, before train is complete. To wait for train to complete, use ``wait_train_complete()``\n \"\"\"\n session_info = {\n \"sessionName\" : session_name,\n \"sessionDescription\" : session_description\n }\n\n return self.client._perform_json(\n \"POST\", \"/projects/%s/models/lab/%s/%s/train\" % (self.project_key, self.analysis_id, self.mltask_id), body=session_info)\n\n\n def start_ensembling(self, model_ids=[], method=None):\n \"\"\"\n Creates asynchronously a new ensemble models of a set of models.\n\n :param list model_ids: A list of model identifiers\n :param str method: the ensembling method (AVERAGE, PROBA_AVERAGE, MEDIAN, VOTE, LINEAR_MODEL, LOGISTIC_MODEL)\n\n This returns immediately, before train is complete. To wait for train to complete, use :meth:`wait_train_complete`\n\n :return: the model identifier of the ensemble\n :rtype: string\n \"\"\"\n ensembling_request = {\n \"method\" : method,\n \"modelsIds\" : model_ids\n }\n\n return self.client._perform_json(\n \"POST\", \"/projects/%s/models/lab/%s/%s/ensemble\" % (self.project_key, self.analysis_id, self.mltask_id), body=ensembling_request)['id']\n\n\n def wait_train_complete(self):\n \"\"\"\n Waits for train to be complete (if started with :meth:`start_train`)\n \"\"\"\n while True:\n status = self.get_status()\n if status.get(\"training\", \"???\") == False:\n break\n time.sleep(2)\n\n\n def get_trained_models_ids(self, session_id=None, algorithm=None):\n \"\"\"\n Gets the list of trained model identifiers for this ML task.\n\n These identifiers can be used for :meth:`get_trained_model_snippet` and :meth:`deploy_to_flow`\n\n :return: A list of model identifiers\n :rtype: list of strings\n \"\"\"\n full_model_ids = self.get_status()[\"fullModelIds\"]\n if session_id is not None:\n full_model_ids = [fmi for fmi in full_model_ids if fmi.get('fullModelId', {}).get('sessionId', '') == session_id]\n model_ids = [x[\"id\"] for x in full_model_ids]\n if algorithm is not None:\n # algorithm is in the snippets\n model_ids = [fmi for fmi, s in self.get_trained_model_snippet(ids=model_ids).iteritems() if s.get(\"algorithm\", \"\") == algorithm]\n return model_ids\n\n\n def get_trained_model_snippet(self, id=None, ids=None):\n \"\"\"\n Gets a quick summary of a trained model, as a dict. For complete information and a structured object, use :meth:`get_trained_model_detail`\n\n :param str id: a model id\n :param list ids: a list of model ids\n\n :rtype: dict\n \"\"\"\n if id is not None:\n obj = {\n \"modelsIds\" : [id]\n }\n elif ids is not None:\n obj = {\n \"modelsIds\" : ids\n }\n else:\n obj = {}\n\n ret = self.client._perform_json(\n \"GET\", \"/projects/%s/models/lab/%s/%s/models-snippets\" % (self.project_key, self.analysis_id, self.mltask_id),\n body = obj)\n if id is not None:\n return ret[id]\n else:\n return ret\n\n def get_trained_model_details(self, id):\n \"\"\"\n Gets details for a trained model\n \n :param str id: Identifier of the trained model, as returned by :meth:`get_trained_models_ids`\n\n :return: A :class:`DSSTrainedPredictionModelDetails` or :class:`DSSTrainedClusteringModelDetails` representing the details of this trained model id\n :rtype: :class:`DSSTrainedPredictionModelDetails` or :class:`DSSTrainedClusteringModelDetails`\n \"\"\"\n ret = self.client._perform_json(\n \"GET\", \"/projects/%s/models/lab/%s/%s/models/%s/details\" % (self.project_key, self.analysis_id, self.mltask_id,id))\n snippet = self.get_trained_model_snippet(id)\n\n if \"facts\" in ret:\n return DSSTrainedClusteringModelDetails(ret, snippet, mltask=self, mltask_model_id=id)\n else:\n return DSSTrainedPredictionModelDetails(ret, snippet, mltask=self, mltask_model_id=id)\n\n def deploy_to_flow(self, model_id, model_name, train_dataset, test_dataset=None, redo_optimization=True):\n \"\"\"\n Deploys a trained model from this ML Task to a saved model + train recipe in the Flow.\n\n :param str model_id: Model identifier, as returned by :meth:`get_trained_models_ids`\n :param str model_name: Name of the saved model to deploy in the Flow\n :param str train_dataset: Name of the dataset to use as train set. May either be a short name or a PROJECT.name long name (when using a shared dataset)\n :param str test_dataset: Name of the dataset to use as test set. If null, split will be applied to the train set. May either be a short name or a PROJECT.name long name (when using a shared dataset). Only for PREDICTION tasks\n :param bool redo_optimization: Should the hyperparameters optimization phase be done ? Defaults to True. Only for PREDICTION tasks\n :return: A dict containing: \"savedModelId\" and \"trainRecipeName\" - Both can be used to obtain further handles\n :rtype: dict\n \"\"\"\n obj = {\n \"trainDatasetRef\" : train_dataset,\n \"testDatasetRef\" : test_dataset,\n \"modelName\" : model_name,\n \"redoOptimization\": redo_optimization\n }\n return self.client._perform_json(\n \"POST\", \"/projects/%s/models/lab/%s/%s/models/%s/actions/deployToFlow\" % (self.project_key, self.analysis_id, self.mltask_id, model_id),\n body = obj)\n\n\n def redeploy_to_flow(self, model_id, recipe_name=None, saved_model_id=None, activate=True):\n \"\"\"\n Redeploys a trained model from this ML Task to a saved model + train recipe in the Flow. Either \n recipe_name of saved_model_id need to be specified\n\n :param str model_id: Model identifier, as returned by :meth:`get_trained_models_ids`\n :param str recipe_name: Name of the training recipe to update\n :param str saved_model_id: Name of the saved model to update\n :param bool activate: Should the deployed model version become the active version \n :return: A dict containing: \"impactsDownstream\" - whether the active version changed and downstream recipes are impacted \n :rtype: dict\n \"\"\"\n obj = {\n \"recipeName\" : recipe_name,\n \"savedModelId\" : saved_model_id,\n \"activate\" : activate\n }\n return self.client._perform_json(\n \"POST\", \"/projects/%s/models/lab/%s/%s/models/%s/actions/redeployToFlow\" % (self.project_key, self.analysis_id, self.mltask_id, model_id),\n body = obj)\n\n","sub_path":"dataikuapi/dss/ml.py","file_name":"ml.py","file_ext":"py","file_size_in_byte":39424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"270122650","text":"'''\r\nCreated on Jan 30, 2015\r\n\r\n@author: Jeremy\r\n'''\r\n\r\nimport pygame\r\nimport sys\r\nfrom random import randint, choice\r\n\r\n\r\nfrom Player import Player\r\nfrom Food import Food\r\n\r\nclass Game(object):\r\n def __init__(self, screen):\r\n clock = pygame.time.Clock()\r\n self.foodGroup = pygame.sprite.Group()\r\n self.initFood()\r\n self.player = Player()\r\n \r\n\r\n while True:\r\n dt = clock.tick(60)\r\n \r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n sys.exit(0)\r\n if event.type == pygame.KEYDOWN:\r\n if self.player.keydown(event):\r\n continue\r\n elif event.type == pygame.KEYUP:\r\n if self.player.keyup(event):\r\n continue\r\n\r\n self.player.update(dt / 1000.0)\r\n self.foodGroup.update(dt / 1000.0)\r\n screen.fill((200, 200, 200))\r\n self.foodGroup.draw(screen)\r\n self.player.draw(screen)\r\n pygame.display.flip()\r\n \r\n def initFood(self):\r\n for x in range(0, 100):\r\n xDir = choice((-1, 1))\r\n yDir = choice((-1, 1))\r\n self.foodGroup.add(Food(randint(4, 16), randint(40, 600), randint(40, 400), randint(60, 100)*xDir, randint(60, 100)*yDir, 640, 480, randint(1, 255), randint(1, 255), randint(1, 255), self.foodGroup))\r\n \r\n \r\n\r\nif __name__ == '__main__':\r\n pygame.init()\r\n pygame.display.set_caption(\"Cube Man\")\r\n screen = pygame.display.set_mode((640,480))\r\n Game(screen)\r\n \r\n\r\n","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"274956743","text":"from flask_restful import Resource, abort, reqparse\nfrom flask import request, jsonify\nfrom services.statistics import app\nfrom services.statistics.repository.statistics_repository import StatisticsRepository\nimport jsonpickle\nfrom services.statistics.security.security import *\n\nrepo = StatisticsRepository()\nparser = reqparse.RequestParser()\nparser.add_argument(\"type\", type=str)\n\n\nclass StatisticsResource(Resource):\n def get(self):\n if 'token' in request.cookies:\n result = check_if_current_user_is_privileged()\n if result:\n args = parser.parse_args(strict=True)\n if 'type' not in args:\n response = app.make_response(\"Тип возвращаемой статистики не задан\")\n response.status_code = 400\n return response\n stat = repo.get_by_type(args['type'])\n payload = jsonpickle.encode(stat)\n response = app.make_response()\n response.data = payload\n return response\n else:\n response = app.make_response(\"Недостаточные привилегии для данного запроса\")\n response.status_code = 403\n return response\n response = app.make_response(\"Не предоставлен токен при совершении запроса\")\n response.status_code = 403\n return response\n\n def post(self):\n if 'token' in request.cookies:\n result = check_value(current_config.TRUSTED_SERVICE)\n if result:\n payload = jsonpickle.decode(flask.request.data)\n repo.create(payload[\"type\"], payload[\"data\"])\n response = app.make_response(\"OK\")\n response.status_code = 200\n return response\n else:\n response = app.make_response(\"Предоставленный токен не является валидным\")\n response.status_code = 403\n return response\n response = app.make_response(\"Не предоставлен токен при совершении запроса\")\n response.status_code = 403\n return response\n\n","sub_path":"services/statistics/rest_api/statistics_resource.py","file_name":"statistics_resource.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"298791060","text":"import os\nimport sys\nimport unittest\nimport doctest\nimport django\n\nBASE_PATH = os.path.dirname(__file__)\n\ndef main(db_engine='sqlite3'):\n \"\"\"\n Standalone django model test with a 'memory-only-django-installation'.\n You can play with a django model without a complete django app installation.\n http://www.djangosnippets.org/snippets/1044/\n \"\"\"\n os.environ[\"DJANGO_SETTINGS_MODULE\"] = \"django.conf.global_settings\"\n from django.conf import global_settings\n\n global_settings.INSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'jsonfield',\n )\n global_settings.DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.%s' % db_engine,\n 'NAME': 'django-jsonfield',\n }\n } \n\n global_settings.STATIC_URL = \"/static/\"\n global_settings.MEDIA_ROOT = os.path.join(BASE_PATH, 'static')\n global_settings.STATIC_ROOT = global_settings.MEDIA_ROOT\n \n global_settings.SECRET_KEY = '334ebe58-a77d-4321-9d01-a7d2cb8d3eea'\n from django.test.utils import get_runner\n test_runner = get_runner(global_settings)\n\n test_runner = test_runner()\n \n if getattr(django, 'setup', None):\n django.setup()\n \n failures = test_runner.run_tests(['jsonfield'])\n \n sys.exit(failures)\n\ndef test_postgres():\n main('postgresql_psycopg2')\n\nif __name__ == '__main__':\n main()\n","sub_path":"packages/django-jsonfield/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"66662136","text":"import sys\nimport tensorflow as tf\nimport pandas as pd\nfrom sklearn.model_selection import KFold\n\n\ndef tf_model():\n model = tf.keras.models.Sequential()\n model.add(tf.keras.layers.Dense(\n 50, input_shape=(2304,), activation='relu'))\n model.add(tf.keras.layers.Dense(128, activation='sigmoid'))\n model.add(tf.keras.layers.Dense(10, activation='softmax'))\n\n model.compile(loss='sparse_categorical_crossentropy',\n optimizer='adam', metrics=['accuracy'])\n return model\n\n\ntrain = pd.read_csv(\n '../data/train/x_train_gr_smpl_normalized.csv').values / 255.0\ntrain_labels = pd.read_csv('../data/train/y_train_smpl.csv').values.ravel()\n\nif sys.argv[1] == '-kfold': # 10 fold validation\n print('USING 10 FOLD CROSSVALIDATION')\n for train_index, test_index in KFold(10).split(train):\n x_train, x_test = train[train_index], train[test_index]\n y_train, y_test = train_labels[train_index], train_labels[test_index]\n\n model = tf_model()\n model.fit(x_train, y_train, epochs=5)\n\n test_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=2)\n print('Test loss:', test_loss)\n print('Test accuracy:', test_accuracy)\nelif sys.argv[1] == '-testset': # Using test set\n print('USING TEST SETS')\n test = pd.read_csv(\n '../data/test/x_test_gr_smpl_normalized.csv').values / 255.0\n test_labels = pd.read_csv('../data/test/y_test_smpl.csv').values.ravel()\n model = tf.keras.models.Sequential()\n model.add(tf.keras.layers.Dense(\n 2304, input_shape=(2304,), activation='relu'))\n model.add(tf.keras.layers.Dense(128, activation='sigmoid'))\n model.add(tf.keras.layers.Dense(10, activation='softmax'))\n\n model.compile(loss='sparse_categorical_crossentropy',\n optimizer='adam', metrics=['accuracy'])\n print(model.summary())\n model.fit(train, train_labels, epochs=5)\n test_loss, test_accuracy = model.evaluate(test, test_labels, verbose=2)\n print('Test loss:', test_loss)\n print('Test accuracy:', test_accuracy)\nelse:\n print('Invalid arguments.')\n print('Launch script with \"-kfold\" or \"-testset\"')\n","sub_path":"scripts/ann.py","file_name":"ann.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"530554279","text":"import nltk\n\n# chunking tecnica base per entity detection, la quale segmenta e etchetta\n# multi toke in una frase\n\n# data una sentence con i rispettivi POS tag\n# si è costruita una grammatica molto semplice per ricavare i NP\n# che sono i Noun Phrase\ndef nounPhraseChunking(sentence):\n\n #print(sentences)\n\n # divide ogni frase in word_token\n\n tokenized_sentences = nltk.word_tokenize(sentence)\n tagged_sentences =nltk.pos_tag( tokenized_sentences)\n print(tagged_sentences)\n\n # define a simple grammar, di come è fatto NP\n # NP è formato da
opzionale o un pronome possessivo\n # più aggettivi quanti se ne vuole edopo un nome oppure un pronome --> indica I ,he\n # la seconda indica uno o più nomi propri di persona\n\n grammar = \"\"\" NP: {
\", None))\n self.label_40.setText(_translate(\"Form\", \"About Me :) \", None))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_9), _translate(\"Form\", \"Settings\", None))\n self.pushButton_10.setText(_translate(\"Form\", \"Close\", None))\n\n self.pushButton_5.clicked.connect(self.savet)\n self.pushButton.clicked.connect(self.savest)\n\n\nimport addt_rc\nimport asss_rc\nimport clear_st_rc\nimport clear_t_rc\nimport close_rc\nimport delete_s_rc\nimport delete_t_rc\nimport flag_rc\nimport save_s_rc\nimport save_t_rc\nimport searctst_rc\nimport searc_t_rc\nimport settings_rc\nimport update_password_rc\nimport update_s_rc\nimport update_t_rc\n\nif __name__ == \"__main__\":\n import sys\n app = QtGui.QApplication(sys.argv)\n Form = QtGui.QWidget()\n ui = Ui_Form()\n ui.setupUi(Form)\n Form.show()\n sys.exit(app.exec_())\n\n","sub_path":"Source files/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":61123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"489957187","text":"import os\r\nimport pandas as pd\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.tokenize import word_tokenize\r\nimport numpy as np\r\nimport datetime\r\nimport pickle\r\nimport sys\r\nimport emoji\r\nimport dataset_sentiment as ds\r\nimport classifier_sentiment as xs\r\n\r\n\r\nconversation_stored_for_session = []\r\nclean_inst_con_dict ={}\r\nexit_sequence = \"no data read...\"\r\nlabel = {0:\"bad\",1:\"good\"}\r\npath1 = os.path.join(os.getcwd(),\"Con_Sessions\",str(datetime.date.today()),str(datetime.datetime.now().strftime(\"%H_%M_%S\"))+\".csv\")\r\npath2 = os.path.join(os.getcwd(),\"Con_Sessions\",str(datetime.date.today()))\r\npath3 = os.path.join(os.getcwd(),\"Con_Sessions\")\r\npath4 = os.path.join(os.getcwd(),r\"tmp\\Raw_Data.csv\")\r\n\r\ndef chat(inst):\r\n\tinstance_conversion = inst\r\n\tconversation_stored_for_session.append(instance_conversion)\r\n\tprint(conversation_stored_for_session)\r\n\tclean_inst_con = clean_data_for_instance(instance_conversion)\r\n\ttrain_data = create_instance_bag(clean_inst_con)\r\n\tdecideTheinstance(train_data,clean_inst_con)\r\n\r\n\r\ndef clean_data_for_instance(instance_conversion):\r\n\tprint(\"Cleaning\")\r\n\tword_tokens = word_tokenize(instance_conversion)\r\n\tprint(word_tokens)\r\n\tstop_words = set(stopwords.words('english'))\r\n\tclean_instance_conversation = []\r\n\tfor w in word_tokens:\r\n\t\tif not w in stop_words:\r\n\t\t\tclean_instance_conversation.append(w)\r\n\r\n\tprint(clean_instance_conversation)\r\n\treturn clean_instance_conversation\r\n\r\ndef create_instance_bag(clean_con):\r\n\t\r\n\tprint(\"Creating the bag\")\r\n\tverctorizer = CountVectorizer(analyzer = \"word\",\r\n\t\t\t\t\t\t\t\ttokenizer = None,\r\n\t\t\t\t\t\t\t\tpreprocessor = None,\r\n\t\t\t\t\t\t\t\tstop_words = None,\r\n\t\t\t\t\t\t\t\tmax_features = 1000)\r\n\r\n\ttrain_data_feat = verctorizer.fit_transform(clean_con)\r\n\ttrain_data_feat = train_data_feat.toarray()\r\n\treturn train_data_feat\r\n\r\ndef decideTheinstance(train_data,clean_data):\r\n\t#file =open(os.path.join(os.getcwd(),r\"Models\\model.pickle\"),'rb')\r\n\ttry:\r\n\t\tRFC_predict = pickle.load(open(os.path.join(os.getcwd(),r\"Models\\model\"+str(len(clean_data))+\".pickle\"),\"rb\"))\r\n\t\tprint(\"Predicting...\")\r\n\t\tresult = RFC_predict.predict(train_data)\r\n\t\toutput = []\r\n\t\tfor w in result:\r\n\t\t\toutput.append(label[w])\r\n\t\tprint(output)\r\n\texcept FileNotFoundError:\r\n\t\tprint(\"I dont know how to help with...\")\r\n\texcept ValueError:\r\n\t\tprint(\"I dont know how to help with...but I'm learning..so I might know next time\")\r\n\telse:\r\n\t\tprint(\"\\tCome again!!!\\n\\n\")\r\n\tfinally:\r\n\t\tpass\r\n\t\r\n\r\ndef settingUpRawData():\r\n\tprint(\"Got till Here!!!\")\r\n\r\n\tdf = pd.DataFrame(conversation_stored_for_session)\r\n\tdf.to_csv(path4,index = None,header = None,sep =\" \",mode = 'a')\r\n\tds.assignTo()\r\n\tds.alignDataForvariousModels()\r\n\tdata,model = xs.alignDataForvariousModels()\r\n\tfor i in range(len(data)):\r\n\t\txs.classify(model[i],data[i])\r\n\r\n\tprint(\"All models trained!!!\")\r\n\r\n\r\nif __name__ == '__main__':\r\n\tif os.path.exists(path3):\r\n\t\tprint(\"Reading\")\r\n\telse:\r\n\t\tos.mkdir(path3)\r\n\tif os.path.exists(path2):\r\n\t\t\tprint(\"Following the line-up...\")\r\n\telse:\r\n\t\tos.mkdir(path2)\r\n\tprint(\"Hey how is your day...\\n\\n\")\r\n\r\n\tinst = input(\">>>\\t\")\r\n\r\n\ttry:\r\n\t\texit_sequence = pd.read_csv(os.path.join(os.getcwd(),r\"tmp\\escape_seq.csv\"))\r\n\t\texit_sequence = list(exit_sequence[\"Sequence\"])\r\n\texcept FileNotFoundError:\r\n\t\tprint(\"DataNotFound: escape_seq.csv\")\r\n\telse:\r\n\t\tpass\r\n\r\n\t\r\n\tprint(type(inst))\r\n\ttry:\r\n\t\twhile inst not in exit_sequence:\r\n\t\t\tchat(inst)\r\n\t\t\tinst = input(\">>>\\t\")\r\n\texcept TypeError:\r\n\t\tprint(\"I am not used to numbers yet, but I'm learning...\")\r\n\telse:\r\n\t\tpass\r\n\tfinally:\r\n\t\tpass\r\n\r\n\tprint(\"Bye\")\r\n\tsettingUpRawData()","sub_path":"sentiment_analyzer/sentiment_analysis.py","file_name":"sentiment_analysis.py","file_ext":"py","file_size_in_byte":3644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"572470190","text":"#!/usr/bin/env python3\nfrom sys import argv\n\"\"\"\ntake a dalton output file like output_files/NB_rotated_static_gamma_STO-3G_hf.out and extract the\ngamma info\n\"\"\"\n\ndef strip_gamma(k):\n return k.replace(\"gamma(\", \"\").replace(\")\", \"\")\n\n\ndef convert(k):\n \"\"\"convert \"Y;Y,Z,Z\" to (1,1,2,2)\n output is a tuple\n \"\"\"\n convert_axes = {\n \"X\": 0,\n \"Y\": 1,\n \"Z\": 2\n }\n k = k.replace(\";\", \",\")\n parts = k.split(',')\n converted = [convert_axes[part] for part in parts]\n return tuple(converted)\n\n\ndef parse_gamma(gamma_line):\n \"\"\"convert line from dalton to\n (\n (int, int, int, int),\n float\n )\n \"\"\"\n _, k, v = gamma_line.split()\n k = convert(strip_gamma(k))\n v = float(v)\n return (k, v)\n\n\ndef extract_gammas_from_file(filename):\n with open(filename) as f:\n lines = f.readlines()\n gammas = []\n for line in lines:\n if \"@ gamma(\" in line:\n gammas.append(parse_gamma(line))\n return gammas\n\nif __name__ == \"__main__\":\n gamma_output = extract_gammas_from_file(argv[1])\n print(gamma_output)\n \n\n","sub_path":"parse_gammas.py","file_name":"parse_gammas.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"115143413","text":"import os, sys\nimport unittest\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\nbasedir = os.path.abspath(os.path.dirname(__file__))\nfrom app import app\nfrom db import db\nimport json\nfrom datetime import datetime, timedelta\nfrom freezegun import freeze_time\n\nfrom helper_tests import helper\n\nTEST_DB = 'test.db'\n\nclass BasicTests(unittest.TestCase):\n\n ############################\n #### setup and teardown ####\n ############################\n\n # executed prior to each test\n def setUp(self):\n app.config['TESTING'] = True\n app.config['WTF_CSRF_ENABLED'] = False\n app.config['DEBUG'] = False\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'test.db')\n self.app = app.test_client()\n db.init_app(app)\n db.drop_all(app=app)\n db.create_all(app=app)\n\n\n # executed after each test\n def tearDown(self):\n pass\n\n # common methods\n def make_cards_json(self, numCards):\n cards = {}\n count = 0\n for i in range(numCards):\n card = {str(i+1): \"name\"+str(i+1)} # condensed version of the card\n cards.update(card)\n return cards\n\n ###############\n #### tests ####\n ###############\n # /quiz/cardlist\n\n def test_make_quiz_card_list(self):\n cards = self.make_cards_json(5)\n new_quiz_card_list = self.app.post('/quiz/cardlist', data=json.dumps({\n 'quiz_id': 1,\n 'cards': cards\n })\n )\n self.assertEqual(new_quiz_card_list.status_code, 201)\n\n def test_get_quiz_card_list(self):\n cards = self.make_cards_json(6)\n first_quiz_card_list = self.app.post('/quiz/cardlist', data=json.dumps({\n 'quiz_id': 1,\n 'cards': cards\n })\n )\n second_quiz_card_list = self.app.post('/quiz/cardlist', data=json.dumps({\n 'quiz_id': 2,\n 'cards': cards\n })\n )\n lists_list = self.app.get('/quiz/cardlist')\n data = json.loads(lists_list.data.decode())\n self.assertEqual(len(data['response']), 2)\n self.assertEqual(data['response'][0]['cards']['1'], 'name1')\n self.assertEqual(data['response'][0]['cards']['2'], 'name2')\n\n def test_duplicate_quiz_id_for_list(self):\n cards = self.make_cards_json(10)\n first_quiz_card_list = self.app.post('/quiz/cardlist', data=json.dumps({\n 'quiz_id': 1,\n 'cards': cards\n })\n )\n self.assertEqual(first_quiz_card_list.status_code, 201)\n duplicate_quiz_id_list = self.app.post('/quiz/cardlist', data=json.dumps({\n 'quiz_id': 1,\n 'cards': cards\n })\n )\n self.assertEqual(duplicate_quiz_id_list.status_code, 400)\n\n def test_duplicate_cards_in_one_quiz(self):\n cards = self.make_cards_json(10)\n cards['card1'] = \"name100\"\n cards['card2'] = \"name100\"\n new_quiz_card_list = self.app.post('/quiz/cardlist', data=json.dumps({\n 'quiz_id': 1,\n 'cards': cards\n })\n )\n self.assertEqual(new_quiz_card_list.status_code, 400)\n\n def test_get_list_by_id(self):\n cards = self.make_cards_json(10)\n new_quiz_card_list = self.app.post('/quiz/cardlist', data=json.dumps({\n 'quiz_id': 1,\n 'cards': cards\n })\n )\n self.assertEqual(new_quiz_card_list.status_code, 201)\n non_target_list = self.app.get('/quiz/cardlist/' + str(2))\n self.assertEqual(non_target_list.status_code, 400)\n target_list = self.app.get('/quiz/cardlist/' + str(1))\n self.assertEqual(target_list.status_code, 200)\n\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_quizcardlist.py","file_name":"test_quizcardlist.py","file_ext":"py","file_size_in_byte":4464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"276177017","text":"# sky, the ground, and clouds.\nimport tkinter as tk\nfrom random import random, seed, randint\n\n# MAIN PROGRAM\n\n\ndef main():\n # The width and height of the scene window.\n width = 800\n height = 500\n\n # Create the Tk root object.\n root = tk.Tk()\n root.geometry(f\"{width}x{height}\")\n\n # Create a Frame object.\n frame = tk.Frame(root)\n frame.master.title(\"Scene\")\n frame.pack(fill=tk.BOTH, expand=1)\n\n # Create a canvas object that will draw into the frame.\n canvas = tk.Canvas(frame, bg='steelBlue1')\n canvas.pack(fill=tk.BOTH, expand=1)\n\n # Call the draw_scene function.\n draw_scene(canvas, 0, 0, width-1, height-1)\n\n root.mainloop()\n\n# FUNCTION DEFINITION\n\n\ndef draw_scene(canvas, scene_left, scene_top, scene_right, scene_bottom):\n \"\"\"Draw a scene in the canvas. scene_left, scene_top,\n scene_right, and scene_bottom contain the extent in\n pixels of the region where the scene should be drawn.\n Parameters\n scene_left: left side of the region; less than scene_right\n scene_top: top of the region; less than scene_bottom\n scene_right: right side of the region\n scene_bottom: bottom of the region\n Return: nothing\n\n If needed, the width and height of the\n region can be calculated like this:\n scene_width = scene_right - scene_left + 1\n scene_height = scene_bottom - scene_top + 1\n \"\"\"\n\n # Call your functions here, such as draw_sky, draw_ground,\n # draw_snowman, draw_tree, draw_shrub, etc.\n\n # # GROUND\n draw_ground(canvas, scene_right, scene_bottom)\n\n # CLOUDS\n cloud_count = randint(10, 25)\n print(f'Cloud count: {cloud_count}')\n draw_random_clouds(canvas, scene_right, scene_bottom, cloud_count)\n \n # TREE\n tree_center = scene_right * 0.8\n tree_top = scene_bottom - scene_bottom * 0.5\n tree_height = 150\n draw_pine_tree(canvas, tree_center, tree_top, tree_height)\n\n # # RANDOM TREES\n # \"\"\" Draw random pine trees at random locations.\"\"\"\n # draw_random_pine_trees(canvas, tree_count)\n\n\n# Define more functions here, like draw_sky, draw_ground,\n# draw_cloud, draw_tree, draw_kite, draw_snowflake, etc.\ndef draw_ground(canvas, scene_right, scene_bottom):\n ground_left = 0\n ground_top = scene_bottom * 0.7\n ground_right = scene_right\n ground_bottom = scene_bottom\n canvas.create_rectangle(ground_left, ground_top,\n ground_right, ground_bottom,\n outline=\"black\", width=1, fill=\"green\")\n\n\ndef draw_random_clouds(canvas, scene_right, scene_bottom, cloud_count=1, cloud_size=30):\n limit_sky_bottom = int(scene_bottom * 0.7)\n for i in range(cloud_count):\n ii = i + 1\n scene_right_random = randint(0, scene_right)\n scene_bottom_random = randint(0, limit_sky_bottom)\n cloud_size_random = randint(cloud_size, cloud_size * 3)\n \n scene_left_random = scene_right_random - cloud_size_random\n scene_top_random = scene_bottom_random - cloud_size_random\n cloud_random_width = random() + 1\n scene_right_random = scene_right_random * cloud_random_width\n\n canvas.create_oval(scene_left_random, scene_top_random, scene_right_random,\n scene_bottom_random, width=0, fill=\"snow\")\n\n\ndef draw_pine_tree(canvas, peak_x, peak_y, height):\n \"\"\"Draw a single pine tree.\n Parameters\n canvas: The tkinter canvas where this\n function will draw a pine tree.\n peak_x, peak_y: The x and y location in pixels where\n this function will draw the top peak of a pine tree.\n height: The height in pixels of the pine tree that\n this function will draw.\n Return: nothing\n \"\"\"\n trunk_width = height / 10\n trunk_height = height / 8\n trunk_left = peak_x - trunk_width / 2\n trunk_right = peak_x + trunk_width / 2\n trunk_bottom = peak_y + height\n\n skirt_width = height / 2\n skirt_height = height - trunk_height\n skirt_left = peak_x - skirt_width / 2\n skirt_right = peak_x + skirt_width / 2\n skirt_bottom = peak_y + skirt_height\n\n # Draw the trunk of the pine tree.\n canvas.create_rectangle(trunk_left, skirt_bottom,\n trunk_right, trunk_bottom,\n outline=\"gray20\", width=1, fill=\"tan3\")\n\n # Draw the crown (also called skirt) of the pine tree.\n canvas.create_polygon(peak_x, peak_y,\n skirt_right, skirt_bottom,\n skirt_left, skirt_bottom,\n outline=\"gray20\", width=1, fill=\"dark green\")\n\n\n# Call the main function so that\n# this program will start executing.\nif __name__ == '__main__':\n main()\n\n\"\"\" W03 Assignment\nDuring this lesson, you will write code that draws:\n - the sky,\n - the ground,\n - and clouds. \nDuring the next lesson, you will write code that completes the scene. The scene that your program draws may be very different from the example scene above. However, your scene must:\n - be outdoor,\n - the sky must have clouds,\n - and the scene must include repetitive elements such as blades of grass, trees, leaves on a tree, birds, flowers, insects, fish, pickets in a fence, dashed lines on a road, buildings, bales of hay, snowmen, snowflakes, or icicles. Be creative.\n\"\"\"\n","sub_path":"w03-writing-functions/prove-drawingScene/scene.py","file_name":"scene.py","file_ext":"py","file_size_in_byte":5313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"156405451","text":"#!/usr/bin/python3\n\"\"\"This is the new engine DBStorage\"\"\"\nfrom sqlalchemy import create_engine, MetaData\nfrom sqlalchemy.orm import sessionmaker, scoped_session\nfrom models.base_model import BaseModel, Base\nfrom models.user import User\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.place import Place\nfrom models.review import Review\nimport os\n\n\nclass DBStorage:\n \"\"\"DBStorage class\n \"\"\"\n __engine = None\n __session = None\n\n def __init__(self):\n \"\"\"creates the engine\n \"\"\"\n env_nm = os.environ.get('HBNB_ENV')\n user_nm = os.environ.get('HBNB_MYSQL_USER')\n passwd = os.environ.get('HBNB_MYSQL_PWD')\n host = os.environ.get('HBNB_MYSQL_HOST')\n db_nm = os.environ.get('HBNB_MYSQL_DB')\n\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'\n .format(user_nm, passwd, host, db_nm),\n pool_pre_ping=True)\n\n Base.metadata.create_all(self.__engine)\n Session = sessionmaker(bind=self.__engine)\n self.__session = Session()\n if env_nm == \"test\":\n Base.metadata.drop_all(self.__engine)\n\n def all(self, cls=None):\n \"\"\"returns a dictionary\n \"\"\"\n classes = ['State', 'City', 'User', 'Place', 'Review', 'Amenity']\n objs = {}\n\n if cls is None:\n for class_nm in classes:\n query = self.__session.query(eval(class_nm)).all()\n for obj in query:\n key = obj.__class__.__name__ + '.' + obj.id\n objs[key] = obj\n else:\n query = self.__session.query(eval(cls)).all()\n for obj in query:\n key = obj.__class__.__name__ + '.' + obj.id\n objs[key] = obj\n return objs\n\n def new(self, obj):\n \"\"\"adds the object to the current database session\n \"\"\"\n self.__session.add(obj)\n\n def save(self):\n \"\"\"commits all changes of the current database session\n \"\"\"\n self.__session.commit()\n\n def delete(self, obj=None):\n \"\"\"deletes from the current database session obj if not None\n \"\"\"\n if obj:\n self.__session.delete(obj)\n self.save()\n\n def reload(self):\n \"\"\"creates all tables in the database\n \"\"\"\n Base.metadata.create_all(self.__engine)\n session_factory = sessionmaker(bind=self.__engine,\n expire_on_commit=False)\n self.__session = scoped_session(session_factory)\n\n def close(self):\n \"\"\"call remove()\"\"\"\n self.__session.close()\n","sub_path":"models/engine/db_storage.py","file_name":"db_storage.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"32910658","text":"import numpy as np\nfrom scipy.interpolate import SmoothBivariateSpline\nimport h5py\n\n# For rendering\nfrom .gaussmodel import convert_to_gaussians, compute_gig\n\n__all__ = [\"Scene\", \"Source\",\n \"Star\",\n \"SimpleGalaxy\", \"Galaxy\", \"ConformalGalaxy\"]\n\n\nclass Scene(object):\n \"\"\"The Scene holds the sources and provides the mapping between a giant 1-d\n array of parameters and the parameters of each source in each band/image\n \"\"\"\n\n def __init__(self, sources=[]):\n self.sources = sources\n self.identify_sources()\n\n def __repr__(self):\n ss = [str(s) for s in self.sources]\n return \"\\n\".join(ss)\n\n def param_indices(self, sid, filtername=None):\n \"\"\"Get the indices of the relevant parameters in the giant Theta\n vector. Assumes that the order of parameters for each source is\n is [flux1, flux2...fluxN, pos1, pos2, shape1, shape2, ..., shapeN]\n\n :param sid:\n Source ID\n\n :param filtername: (optional, default: None)\n The name of the filter for which you want the corresponding flux\n parameter index. If None (default) then indices for all fluxes are\n returned\n\n :returns theta:\n An array with elements [flux, (shape_params)]\n \"\"\"\n npar_per_source = [s.nparam for s in self.sources[:sid]]\n # get all the shape parameters\n source = self.sources[sid]\n start = int(np.sum(npar_per_source))\n # indices of the shape and position parameters\n inds = range(start + source.nband, start + source.nparam)\n # put in the flux for this source in this band\n inds.insert(0, start + source.filter_index(filtername))\n return inds\n\n def set_all_source_params(self, Theta):\n \"\"\"Loop over sources in the scene, setting the parameters in each\n source based on the relevant subset of Theta parameters.\n \"\"\"\n start = 0\n for source in self.sources:\n end = start + source.nparam\n source.set_params(Theta[start:end])\n start += source.nparam\n\n def get_all_source_params(self):\n \"\"\"Get the total scene parameter vector\n \"\"\"\n plist = [s.get_param_vector() for s in self.sources if not s.fixed]\n params = np.concatenate(plist)\n return params\n\n @property\n def parameter_names(self):\n \"\"\"Get names for all the parameters in the scene\n \"\"\"\n return np.concatenate([s.parameter_names for s in self.sources])\n\n def identify_sources(self):\n \"\"\"Give each source in the scene a unique identification number.\n \"\"\"\n for i, source in enumerate(self.sources):\n source.id = i\n\n\nclass Source(object):\n \"\"\"Parameters describing a source in the celestial plane. For each galaxy\n there are 7 parameters, only some of which may be relevant for changing the\n apparent flux:\n * flux: total flux (possibly a vector)\n * ra: right ascension (degrees)\n * dec: declination (degrees)\n * q, pa: axis ratio squared and position angle\n * n: sersic index\n * r: half-light radius (arcsec)\n\n Methods are provided to return the amplitudes and covariance matrices of\n the constituent gaussians, as well as derivatives of the amplitudes with\n respect to sersic index and half light radius.\n \"\"\"\n\n id = 0\n fixed = False\n radii = np.zeros(1)\n\n # Parameters\n flux = 0. # flux. This will get rewritten on instantiation to have\n # a length that is the number of bands\n ra = 0.\n dec = 0.\n q = 1. # sqrt of the axis ratio, i.e. (b/a)^0.5\n pa = 0. # postion angle (N of E)\n sersic = 0. # sersic index\n rh = 0. # half light radius\n\n def __init__(self, filters=['dummy'], radii=None):\n \"\"\"\n :param filters:\n A list of strings giving the filternames for which you want fluxes.\n These names should correspond to values of the `filtername`\n attribute of PostageStamps, since they will be used to choose the\n appropriate element of the `flux` vector for generating model pixel\n values.\n\n The length of the supplied `filters` list will determine the length\n of the `flux` vector, accessible via the `nband` attribute.\n \"\"\"\n assert type(filters) == list\n self.filternames = filters\n self.flux = np.zeros(len(self.filternames))\n if radii is not None:\n self.radii = radii\n\n def __repr__(self):\n kk, vv = self.parameter_names, self.get_param_vector()\n parstring = [\"{}={}\".format(k, v)\n for k, v in zip(kk, vv)]\n return '{}\\n\\t({})'.format(self.__class__, \",\\n\\t\".join(parstring))\n\n @property\n def nband(self):\n \"\"\"Number of elements of the flux vector (corresponding to the filters\n in `filternames`)\n \"\"\"\n return len(self.filternames)\n\n @property\n def nparam(self):\n \"\"\"Total number of source parameters, including position, shape, and\n flux(es)\n \"\"\"\n return self.npos + self.nshape + self.nband\n\n @property\n def ngauss(self):\n \"\"\"Total number of gaussians used to describe the source.\n \"\"\"\n return len(self.radii)\n\n @property\n def use_gradients(self):\n \"\"\"Which of the 7 gradients (d/dFlux, d/dRA, d/dDec, d/dq, d/dpa,\n d/dsersic, d/drh) will you actually use?\n \"\"\"\n return slice(0, 1 + self.npos + self.nshape)\n\n @property\n def parameter_names(self):\n names = self.filternames + [\"ra\", \"dec\"] + [\"q\", \"pa\", \"n\", \"r\"][:self.nshape]\n names = [\"{}_{}\".format(n, self.id) for n in names]\n return names\n\n def filter_index(self, filtername):\n \"\"\"Returns the index of the element of the `flux` array that\n corresponds to the supplied `filtername`.\n\n :param filtername:\n String giving the name of the filter for which you want the\n corresponding `flux` vector index.\n\n :returns index:\n An integer index that when used to subscript the `flux` attribute\n gives the source flux in `filtername`\n \"\"\"\n return self.filternames.index(filtername)\n\n @property\n def covariances(self):\n raise(NotImplementedError)\n\n @property\n def amplitudes(self):\n \"\"\"Code here for getting amplitudes from a splined look-up table\n (dependent on self.n and self.r). Placeholder code gives them all\n equal amplitudes.\n \"\"\"\n return np.ones(self.ngauss) / (self.ngauss * 1.0)\n\n @property\n def damplitude_dsersic(self):\n \"\"\"Code here for getting amplitude derivatives from a splined look-up\n table (dependent on self.sersic and self.rh)\n \"\"\"\n # ngauss array of da/dsersic\n return np.zeros(self.ngauss)\n\n @property\n def damplitude_drh(self):\n \"\"\"Code here for getting amplitude derivatives from a splined look-up\n table (dependent on self.sersic and self.rh)\n \"\"\"\n # ngauss array of da/drh\n return np.zeros(self.ngauss)\n\n def render(self, stamp, compute_deriv=True, **compute_keywords):\n \"\"\"Render a source on a PostageStamp.\n\n :param stamp:\n A PostageStamp object\n\n :param compute_deriv: (optional, default: True)\n If True, return the gradients of the image with respect to the\n relevant free parameters for the source.\n \"\"\"\n gig = convert_to_gaussians(self, stamp, compute_deriv=compute_deriv)\n im, grad = compute_gig(gig, stamp.xpix.flat, stamp.ypix.flat,\n compute_deriv=compute_deriv, **compute_keywords)\n\n if compute_deriv:\n return im, grad[self.use_gradients]\n else:\n return im, None\n\n\nclass Star(Source):\n \"\"\"This is a represenation of a point source in terms of Scene (on-sky)\n parameters. Only 3 of the 7 full Source parameters are relevant:\n * flux: total flux\n * ra: right ascension (degrees)\n * dec: declination (degrees)\n \"\"\"\n\n radii = np.zeros(1)\n\n # PointSources only have two position parameters.\n npos = 2\n nshape = 0\n\n def set_params(self, theta, filtername=None):\n \"\"\"Set the parameters (flux(es), ra, dec) from a theta array. Assumes\n that the order of parameters in the theta vector is [flux1,\n flux2...fluxN, ra, dec]\n\n :param theta:\n The source parameter values that are to be set. Sequence of length\n either `nband + 2` (if `filtername` is `None`) or 3.\n\n :param filtername: (optional, default: None)\n If supplied, the theta vector is assumed to be 3-element (fluxI,\n ra, dec) where fluxI is the source flux through the filter given by\n `filtername`. If `None` then the theta vector is assumed to be of\n length `Source().nband + 2`, where the first `nband` elements\n correspond to the fluxes.\n \"\"\"\n if filtername is not None:\n nflux = 1\n flux_inds = self.filter_index(filtername)\n else:\n nflux = self.nband\n flux_inds = slice(None)\n msg = \"The length of the parameter vector is not appropriate for this source\"\n assert len(theta) == nflux + 2, msg\n self.flux[flux_inds] = theta[:nflux]\n self.ra = theta[nflux]\n self.dec = theta[nflux + 1]\n\n def get_param_vector(self, filtername=None):\n \"\"\"Get the relevant source parameters as a simple 1-D ndarray.\n \"\"\"\n if filtername is not None:\n flux = [self.flux[self.filter_index(filtername)]]\n else:\n flux = self.flux\n params = np.concatenate([flux, [self.ra], [self.dec]])\n return params\n\n @property\n def covariances(self):\n \"\"\"This just constructs a set of source gaussian covariance matrices\n based on the radii. For point sources these are all zeros, since a\n point source has no size.\n \"\"\"\n # ngauss x 2 x 2\n # this has no derivatives, since the radii are fixed.\n return np.zeros([1, 2, 2])\n\n\nclass SimpleGalaxy(Source):\n \"\"\"Parameters describing a simple gaussian galaxy in the celestial plane\n (i.e. the Scene parameters.) Only 5 of the possible 7 Source parameters are\n relevant:\n * flux: total flux\n * ra: right ascension (degrees)\n * dec: declination (degrees)\n * q, pa: axis ratio squared and position angle\n\n The radial profile is assumed to be a sum of equally weighted gaussians\n with radii given by SimpleGalaxy.radii\n \"\"\"\n\n radii = np.ones(1)\n\n # Galaxies have two position parameters, 2 or 4 shape parameters (pa and q)\n # and nband flux parameters\n npos = 2\n nshape = 2\n\n def set_params(self, theta, filtername=None):\n \"\"\"Set the parameters (flux(es), ra, dec, q, pa) from a theta array.\n Assumes that the order of parameters in the theta vector is [flux1,\n flux2...fluxN, ra, dec, q, pa]\n\n :param theta:\n The source parameter values that are to be set. Sequence of length\n either `nband + 4` (if `filtername` is `None`) or 5 (if a filter is\n specified)\n\n :param filtername: (optional, default: None)\n If supplied, the theta vector is assumed to be 5-element (fluxI,\n ra, dec, q, pa) where fluxI is the source flux through the filter\n given by `filtername`. If `None` then the theta vector is assumed\n to be of length `Source().nband + 4`, where the first `nband`\n elements correspond to the fluxes.\n \"\"\"\n if filtername is not None:\n nflux = 1\n flux_inds = self.filter_index(filtername)\n else:\n nflux = self.nband\n flux_inds = slice(None)\n msg = \"The length of the parameter vector is not appropriate for this source\"\n assert len(theta) == nflux + 4, msg\n self.flux[flux_inds] = theta[:nflux]\n self.ra = theta[nflux]\n self.dec = theta[nflux + 1]\n self.q = theta[nflux + 2]\n self.pa = theta[nflux + 3]\n\n def get_param_vector(self, filtername=None):\n \"\"\"Get the relevant source parameters as a simple 1-D ndarray.\n \"\"\"\n if filtername is not None:\n flux = [self.flux[self.filter_index(filtername)]]\n else:\n flux = self.flux\n params = np.concatenate([flux, [self.ra], [self.dec],\n [self.q], [self.pa]])\n return params\n\n @property\n def covariances(self):\n \"\"\"This just constructs a set of covariance matrices based on the fixed\n radii used in approximating the galaxies.\n \"\"\"\n # ngauss x 2 x 2\n # this has no derivatives, since the radii are fixed.\n return (self.radii**2)[:, None, None] * np.eye(2)\n\n\nclass Galaxy(Source):\n \"\"\"Parameters describing a gaussian galaxy in the celestial plane (i.e. the\n Scene parameters) All 7 Source parameters are relevant:\n * flux: total flux\n * ra: right ascension (degrees)\n * dec: declination (degrees)\n * q, pa: axis ratio squared and position angle\n * n: sersic index\n * r: half-light radius (arcsec)\n\n Methods are provided to return the amplitudes and covariance matrices of\n the constituent gaussians, as well as derivatives of the amplitudes with\n respect to sersic index and half light radius.\n\n The amplitudes and the derivatives of the amplitudes with respect to the\n sersic index and half-light radius are based on splines.\n \"\"\"\n\n radii = np.ones(1)\n\n # Galaxies have 2 position parameters,\n # 2 or 4 shape parameters (pa and q),\n # and nband flux parameters\n npos = 2\n nshape = 4\n\n def __init__(self, filters=['dummy'], radii=None, splinedata=None, free_sersic=True):\n self.filternames = filters\n self.flux = np.zeros(len(self.filternames))\n if radii is not None:\n self.radii = radii\n if splinedata is None:\n raise(ValueError, \"Galaxies must have information to make A(r, n) bivariate splines\")\n else:\n self.initialize_splines(splinedata)\n\n if not free_sersic:\n # Fix the sersic parameters n_sersic and r_h\n self.nshape = 2\n\n def set_params(self, theta, filtername=None):\n \"\"\"Set the parameters (flux(es), ra, dec, q, pa, n_sersic, r_h) from a\n theta array. Assumes that the order of parameters in the theta vector\n is [flux1, flux2...fluxN, ra, dec, q, pa, sersic, rh]\n\n :param theta:\n The source parameter values that are to be set. Sequence of length\n either `nband + npos + nshape` (if `filtername` is `None`) or `1 +\n npos + nshape` (if a filter is specified)\n\n :param filtername: (optional, default: None)\n If supplied, the theta vector is assumed to be 7-element (fluxI,\n ra, dec, q, pa) where fluxI is the source flux through the filter\n given by `filtername`. If `None` then the theta vector is assumed\n to be of length `Source().nband + 6`, where the first `nband`\n elements correspond to the fluxes.\n \"\"\"\n if filtername is not None:\n nflux = 1\n flux_inds = self.filter_index(filtername)\n else:\n nflux = self.nband\n flux_inds = slice(None)\n msg = \"The length of the parameter vector is not appropriate for this source\"\n assert len(theta) == nflux + self.npos + self.nshape, msg\n self.flux[flux_inds] = theta[:nflux]\n self.ra = theta[nflux]\n self.dec = theta[nflux + 1]\n self.q = theta[nflux + 2]\n self.pa = theta[nflux + 3]\n if self.nshape > 2:\n self.sersic = theta[nflux + 4]\n self.rh = theta[nflux + 5]\n\n def get_param_vector(self, filtername=None):\n \"\"\"Get the relevant source parameters as a simple 1-D ndarray.\n \"\"\"\n if filtername is not None:\n flux = [self.flux[self.filter_index(filtername)]]\n else:\n flux = self.flux\n params = np.concatenate([flux, [self.ra, self.dec, self.q, self.pa]])\n if self.nshape > 2:\n params = np.concatenate([params, [self.sersic, self.rh]])\n return params\n\n def initialize_splines(self, splinedata, spline_smoothing=None):\n \"\"\"Initialize Bivariate Splines used to interpolate and get derivatives\n for gaussian amplitudes as a function of sersic and rh\n \"\"\"\n with h5py.File(splinedata, \"r\") as data:\n n = data[\"nsersic\"][:]\n r = data[\"rh\"][:]\n A = data[\"amplitudes\"][:]\n self.radii = data[\"radii\"][:]\n\n nm, ng = A.shape\n self.splines = [SmoothBivariateSpline(n, r, A[:, i], s=spline_smoothing) for i in range(ng)]\n self.rh_range = (r.min(), r.max())\n self.sersic_range = (n.min(), n.max())\n\n @property\n def covariances(self):\n \"\"\"This just constructs a set of covariance matrices based on the fixed\n radii used in approximating the galaxies.\n \"\"\"\n # ngauss x 2 x 2\n # this has no derivatives, since the radii are fixed.\n return (self.radii**2)[:, None, None] * np.eye(2)\n\n @property\n def amplitudes(self):\n \"\"\"Code here for getting amplitudes from a splined look-up table\n (dependent on self.n and self.r). Placeholder code gives them all\n equal amplitudes.\n \"\"\"\n return np.squeeze(np.array([spline(self.sersic, self.rh) for spline in self.splines]))\n\n @property\n def damplitude_dsersic(self):\n \"\"\"Code here for getting amplitude derivatives from a splined look-up\n table (dependent on self.n and self.r)\n \"\"\"\n # ngauss array of da/dsersic\n return np.array([spline(self.sersic, self.rh, dx=1) for spline in self.splines])\n\n @property\n def damplitude_drh(self):\n \"\"\"Code here for getting amplitude derivatives from a splined look-up\n table (dependent on self.n and self.r)\n \"\"\"\n # ngauss array of da/drh\n return np.array([spline(self.sersic, self.rh, dy=1) for spline in self.splines])\n\n\nclass ConformalGalaxy(Galaxy):\n\n \"\"\"Parameters describing a source in the celestial plane, with the shape\n parameterized by the conformal shear vector instead of traditional axis\n ratio and position angle. For each galaxy there are 7 parameters:\n * flux: total flux (possibly a vector)\n * ra: right ascension (degrees)\n * dec: declination (degrees)\n * ep, ec: the eta vector defined by Bernstein & Jarvis 2002, eq 2.10\n * n: sersic index\n * r: half-light radius (arcsec)\n\n Methods are provided to return the amplitudes and covariance matrices of\n the constituent gaussians, as well as derivatives of the amplitudes with\n respect to sersic index and half light radius.\n \"\"\"\n\n # Parameters\n flux = 0. # flux. This will get rewritten on instantiation to have\n # a length that is the number of bands\n ra = 0.\n dec = 0.\n ep = 0. # eta_+ (Bernstein & Jarvis) = \\eta \\cos(2\\phi)\n ec = 0. # eta_x (Bernstein & Jarvis) = \\eta \\sin(2\\phi)\n sersic = 0. # sersic index\n rh = 0. # half light radius\n\n def set_params(self, theta, filtername=None):\n \"\"\"Set the parameters (flux(es), ra, dec, ep, ec, n_sersic, r_h) from a\n theta array. Assumes that the order of parameters in the theta vector\n is [flux1, flux2...fluxN, ra, dec, ep, ec, sersic, rh]\n\n :param theta:\n The source parameter values that are to be set. Sequence of length\n either `nband + npos + nshape` (if `filtername` is `None`) or `1 +\n npos + nshape` (if a filter is specified)\n\n :param filtername: (optional, default: None)\n If supplied, the theta vector is assumed to be 7-element (fluxI,\n ra, dec, ep, ec) where fluxI is the source flux through the filter\n given by `filtername`. If `None` then the theta vector is assumed\n to be of length `Source().nband + 6`, where the first `nband`\n elements correspond to the fluxes.\n \"\"\"\n if filtername is not None:\n nflux = 1\n flux_inds = self.filter_index(filtername)\n else:\n nflux = self.nband\n flux_inds = slice(None)\n msg = \"The length of the parameter vector is not appropriate for this source\"\n assert len(theta) == nflux + self.npos + self.nshape, msg\n self.flux[flux_inds] = theta[:nflux]\n self.ra = theta[nflux]\n self.dec = theta[nflux + 1]\n self.ep = theta[nflux + 2]\n self.ec = theta[nflux + 3]\n if self.nshape > 2:\n self.sersic = theta[nflux + 4]\n self.rh = theta[nflux + 5]\n\n def get_param_vector(self, filtername=None):\n \"\"\"Get the relevant source parameters as a simple 1-D ndarray.\n \"\"\"\n if filtername is not None:\n flux = [self.flux[self.filter_index(filtername)]]\n else:\n flux = self.flux\n params = np.concatenate([flux, [self.ra, self.dec, self.ep, self.ec]])\n if self.nshape > 2:\n params = np.concatenate([params, [self.sersic, self.rh]])\n return params\n\n def etas_from_qphi(self, q, phi):\n \"\"\"Get eta vector from native shape units\n\n :param q: (b/a)^0.5\n :param phi: position angle (radians)\n \"\"\"\n eta = -np.log(q**2)\n eta_plus = eta * np.cos(phi * 2.)\n eta_cross = eta * np.sin(phi * 2.)\n return eta_plus, eta_cross\n\n @property\n def parameter_names(self):\n names = self.filternames + [\"ra\", \"dec\"] + [\"ep\", \"ec\", \"n\", \"r\"][:self.nshape]\n names = [\"{}_{}\".format(n, self.id) for n in names]\n return names\n\n @property\n def q(self):\n \"\"\"(b/a)^0.5 following conventions above\n \"\"\"\n eta = np.hypot(self.ep, self.ec)\n return np.exp(-eta / 2.)\n\n @property\n def pa(self):\n \"\"\"Position angle\n \"\"\"\n return np.arctan2(self.ec, self.ep) / 2.\n\n @property\n def ds_deta(self):\n \"\"\"The Jacobian for d(q, pa) / d(eta_+, eta_x).\n I.e., multiply gradients with respect to q and pa by this to get\n gradients with respect to eta_+, eta_x.\n \"\"\"\n sqrtq = self.q # ugh\n q = (sqrtq)**2\n phi = self.pa\n sin2phi = np.sin(2 * phi)\n cos2phi = np.cos(2 * phi)\n itlq = 1. / (2. * np.log(q))\n ds_de = np.array([[-q * cos2phi, -q * sin2phi],\n [sin2phi * itlq, -cos2phi * itlq]])\n # account for sqrt in q = sqrt(b/a)\n sq = np.array([[0.5 / sqrtq, 0.],\n [0., 1.]])\n\n return np.dot(ds_de.T, sq)\n\n def render(self, stamp, compute_deriv=True, **compute_keywords):\n \"\"\"Render a source on a PostageStamp.\n\n :param stamp:\n A PostageStamp object\n\n :param withgrad: (optional, default: True)\n If True, return the gradients of the image with respect to the\n relevant free parameters for the source.\n \"\"\"\n gig = convert_to_gaussians(self, stamp, compute_deriv=compute_deriv)\n im, grad = compute_gig(gig, stamp.xpix.flat, stamp.ypix.flat,\n compute_deriv=compute_deriv, **compute_keywords)\n\n if compute_deriv:\n # convert d/dq, d/dphi to d/deta_+, d/deta_x\n # FIXME: This is a brittle way to do this!\n grad[3:5, :] = np.matmul(self.ds_deta, grad[3:5, :])\n return im, grad[self.use_gradients]\n else:\n return im, None\n\n\ndef scale_matrix(q):\n \"\"\"q=(b/a)^0.5\n \"\"\"\n return np.array([[1./q, 0],\n [0, q]])\n\n\ndef rotation_matrix(theta):\n costheta = np.cos(theta)\n sintheta = np.sin(theta)\n return np.array([[costheta, -sintheta],\n [sintheta, costheta]])\n\n\ndef scale_matrix_deriv(q):\n \"\"\"q=(b/a)^0.5\n \"\"\"\n return np.array([[-1./q**2, 0],\n [0, 1]])\n\n\ndef rotation_matrix_deriv(theta):\n costheta = np.cos(theta)\n msintheta = -np.sin(theta)\n return np.array([[msintheta, -costheta],\n [costheta, msintheta]])\n\n\ndef dummy_spline(x, y, dx=0, dy=0):\n if (dx > 0) | (dy > 0):\n return 0.\n else:\n return 1.\n","sub_path":"forcepho/sources.py","file_name":"sources.py","file_ext":"py","file_size_in_byte":24665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"188153483","text":"\"\"\"\nhttps://www.codewars.com/kata/5ff0fc329e7d0f0010004c03/train/python\n\"\"\"\n\n\ndef count_diamonds(diamond_map, num_of_diamonds):\n parcels = []\n size = float('inf')\n for up in range(len(diamond_map)):\n inter_sum = [0] * len(diamond_map[0])\n for bottom in range(up, len(diamond_map)):\n inter_sum = [inter_sum[i] + diamond_map[bottom][i] for i in range(len(inter_sum))]\n for col1, col2 in _sliding_window_1d(inter_sum, num_of_diamonds):\n square_of_the_area = (bottom - up + 1) * (col2 - col1 + 1)\n if square_of_the_area < size:\n size = square_of_the_area\n parcels = [[(up, col1), (bottom, col2)]]\n elif square_of_the_area == size:\n parcels.append([(up, col1), (bottom, col2)])\n return sorted(parcels)\n\n\ndef _sliding_window_1d(some_list: list, target_sum: int):\n current_sum = left = 0\n for right in range(len(some_list)):\n current_sum += some_list[right]\n while current_sum - some_list[left] >= target_sum:\n current_sum -= some_list[left]\n left += 1\n if current_sum == target_sum:\n yield left, right\n","sub_path":"test/codewars/4_kyu_Counting_Diamonds.py","file_name":"4_kyu_Counting_Diamonds.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"459720965","text":"\nimport webapp2\n\nfrom google.appengine.api import app_identity\nfrom google.appengine.api import images\nfrom google.appengine.api import mail\nfrom google.appengine.api import users\nfrom google.appengine.ext import blobstore\nfrom google.appengine.ext import ndb\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp import blobstore_handlers\n\nfrom models import Employee as Emp\nfrom models import Role\nfrom querydefs import JinjaEnv\nfrom querydefs import QueryDefs\n\n\nclass UserProfile(webapp2.RequestHandler):\n \"\"\"Handler for admin views.\"\"\"\n def get(self):\n employee = Emp.query(\n Emp.user_id == users.get_current_user().user_id()\n ).get()\n\n projects = []\n qd = QueryDefs()\n\n if employee.projects:\n for project_id in employee.projects:\n if project_id:\n projects.append(qd.get_project_name(project_id))\n if employee.role:\n role = Role.query(Role.key == employee.role).get()\n else:\n role = None\n\n if employee.photo:\n serving_url = images.get_serving_url(blobstore.create_gs_key(employee.photo))\n else:\n serving_url = None\n\n jinjaenv = JinjaEnv()\n template = jinjaenv.get_jinja_env().get_template(\n 'templates/user/userprofile.html'\n )\n template_values = {\n 'employee': employee,\n 'projects': projects,\n 'role': role,\n 'serving_url': serving_url,\n 'is_admin': users.is_current_user_admin(),\n 'url_link': users.create_logout_url('/')\n }\n self.response.write(template.render(template_values))\n","sub_path":"handlers/userprofile.py","file_name":"userprofile.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"510683147","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri May 29 09:03:49 2020\r\n\r\n@author: rpira\r\n\"\"\"\r\n\r\nfrom OptimizedFunction import compile_model\r\nimport pickle\r\n\r\n## Importing the database for the combination of hyper parameters \r\nfilehandler = open('filename_pi.obj', 'rb') \r\nModelInfo = pickle.load(filehandler)\r\n\r\n## Initial values\r\ncount=0\r\ntot=[]\r\nMapeOpt=100\r\nTreasureholdAccuracy=1\r\nTreasholdCount=1000\r\n### Finding the minimum mape with 2 treashhold with radomized search\r\nfor i in range(0,len(ModelInfo)):\r\n count=count+1\r\n saved_model, mape =compile_model(ModelInfo[i])\r\n print(\"Mape=\", mape)\r\n ### Checking if the difference between the current and previous minimum mape\r\n ### is bigger than the desired on, then restart the counter. So we have 2 treashholdhere\r\n if MapeOpt-mape>TreasureholdAccuracy:\r\n count=0\r\n ## Choose the min mape\r\n if mapeTreasholdCount:\r\n break\r\n","sub_path":"HyperParamOptimization/OptimizingHyperParam.py","file_name":"OptimizingHyperParam.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"159452649","text":"\"\"\"\nCreated on 6/22/2018\n@author: Jingchao Yang\n\nLevel Two credibility test include basic event based cross check\nEvent sources includes:\nTwitter embedded text events extraction\nTwitter linked web page text events extraction\n\nGoal is to analysis if events from a same twitter are correlated (same)\n\"\"\"\nfrom psqlOperations import queryFromDB\n\n\ndef checkEvents(eventList1, eventList2):\n \"\"\"if same event found within tweets and url page under same tid\"\"\"\n matchByEvent = []\n for e1 in eventList1:\n tid = e1[2]\n print(tid)\n for e2 in eventList2:\n if e1[-2:] == e2[-2:]:\n event = e1[1]\n print(event)\n matchByEvent.append((tid, event))\n return matchByEvent\n\n\n'''databsed connection variables'''\ndbConnect = \"dbname='harveyTwitts' user='postgres' host='localhost' password='123456'\"\ntw_event_tb = \"test_events\"\nurl_event_tb = \"test_urlevents\"\n\n'''data select from db'''\ntw_events = queryFromDB.get_allData(dbConnect, tw_event_tb)\nprint(\"events from tweets\", len(tw_events))\nurl_events = queryFromDB.get_allData(dbConnect, url_event_tb)\nprint(\"events from tweets\", len(url_events))\n\nmatchEvent = checkEvents(tw_events, url_events)\nprint(\"matched events\", len(matchEvent))\n","sub_path":"analysis_Credibility/level2.py","file_name":"level2.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"253948287","text":"from flask import Flask, g\nfrom flask_sqlalchemy import SQLAlchemy\n\n\ndb = SQLAlchemy()\n\n\ndef create_app():\n app = Flask(__name__)\n app.config.from_mapping(\n SQLALCHEMY_DATABASE_URI='sqlite:////tmp/alayatodo.db',\n SECRET_KEY='development key',\n USERNAME='admin',\n PASSWORD='default',\n SQLALCHEMY_ECHO=True,\n )\n\n db.init_app(app)\n\n from alayatodo import models\n from alayatodo import views\n\n app.register_blueprint(views.bp)\n\n return app\n\ndef init_db():\n db.drop_all()\n db.create_all()\n","sub_path":"alayatodo/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"632008039","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\"\"\"\n\nimport numpy as np\nfrom sklearn.preprocessing import MinMaxScaler\nimport tkinter.filedialog\nimport os\nimport csv\n\nOUTPUT = './deformated.txt'\nNPY_OUTPUT = 'robot.npy'\n\nif __name__==\"__main__\":\n print('dataset maker')\n \n root = tkinter.Tk()\n root.withdraw()\n fType = [(\"dataset\",\"txt\")]\n iDir = os.path.abspath(os.path.dirname(__file__))\n file_path = tkinter.filedialog.askopenfile(filetype=fType, initialdir=iDir)\n \n print('File >>', file_path.name)\n \n #------------------------------\n # raw data set object\n #------------------------------\n raw_data = np.genfromtxt(fname=file_path.name,\n dtype=None,\n names=['role','situ',\n 'bx','by','ax','ay','bx','by','cx','cy','d',\n 'wl','t',\n 'shoot','pass','ballget','clear','active','cover','waitpass'],\n encoding='utf-8',delimiter='\\t',comments='#')\n\n # print(raw_data)\n\n\n #------------------------------\n # extraction alpha dataset\n #------------------------------\n alpha_data = []\n beta_data = []\n gamma_data = []\n for dat in raw_data:\n if dat[0] == 'α':\n tmp = [v for v in dat]\n alpha_data.append(tmp[2:])\n if dat[0] == 'β':\n tmp = [v for v in dat]\n beta_data.append(tmp[2:])\n if dat[0] == 'γ':\n tmp = [v for v in dat]\n gamma_data.append(tmp[2:])\n\n alpha_data = np.array(alpha_data)\n beta_data = np.array(beta_data)\n gamma_data = np.array(gamma_data)\n\n\n\n print('Alpha {} >>'.format(len(alpha_data)*18))\n # print(alpha_data)\n\n #\n # change shape for T-SOM\n #\n alpha_data = alpha_data.flatten(order='F')\n beta_data = beta_data.flatten(order='F')\n gamma_data = gamma_data.flatten(order='F')\n # np.savetxt('test.txt', tmp, encoding='utf-8')\n\n #titin puipui\n alpha_data = np.reshape(alpha_data, (-1, 1))\n beta_data = np.reshape(beta_data, (-1, 1))\n gamma_data = np.reshape(gamma_data, (-1, 1))\n # print(alpha_data.shape)\n\n train_data = np.hstack([alpha_data, beta_data])\n train_data = np.hstack([train_data, gamma_data])\n print('Stacked {}'.format(train_data.shape))\n\n PARAM_NUM = 18\n PRODUCT_NUM = 270\n ROLE_NUM = 3\n print(PARAM_NUM, PRODUCT_NUM, ROLE_NUM)\n train_data = np.reshape(train_data,(PARAM_NUM, PRODUCT_NUM, ROLE_NUM))\n\n print(\"TRAIN DATA {} >>\".format(train_data.shape))\n # print(train_data)\n\n train_data = np.transpose(train_data, (1,2,0))\n\n #debug\n print(train_data[:,0,11]-train_data[:,1,11])\n\n print(\"TRANSPOSED {} >>\".format(train_data.shape))\n # print(train_data)\n\n #------------------------------\n # save to npy\n #------------------------------ \n np.save(NPY_OUTPUT, train_data)\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n","sub_path":"Questionnaire/dataset/dataset_maker.py","file_name":"dataset_maker.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"285316588","text":"#! /usr/bin/env python3\n#\n#test_neuro.py\n#\n\"\"\"Unit tests for neuro.py\"\"\"\n\n#standard modules:\nimport math\nimport unittest\nfrom copy import deepcopy\nfrom random import randrange, randint, random, choice, uniform\nfrom numbers import Number as _Number\nfrom collections.abc import Sequence as _Sequence\n#included modules:\nfrom neuro import *\n\n#global parameters:\n_NUM = 50 #number of invokes per test\n_SIZE = 20 #size coefficient that is describes how big test items must be\n#notive: the size must be at least 3, ERROR othewise\n\n\n\nclass TestNeuralNetwork(unittest.TestCase):\n \n #helping methods:\n __mulsum = lambda W, O: sum(map(lambda o, w: o*w, O, W))\n __sigmoid = lambda x: 1/(1 + math.e**-x)\n @classmethod\n def __out(cls, W, O):\n return cls.__sigmoid(cls.__mulsum(W[:-1], O) + W[-1])\n \n def test_multioutput_sigmoid_backpropagation(self):\n setup = i, j, k = 6, 4, 3\n sp = 0.25 #learning speen coefficient\n alg = Algorithms.SigmoidBackPropagation #current algorithm\n sigmoid = self.__class__.__sigmoid #activation function\n out = self.__class__.__out #output calculator\n mulsum = self.__class__.__mulsum\n N = Network(*setup, n = sp, algorithm = alg)\n # | o | | | | |\n # | o | | | | |\n # | o | | o | | | } NETWORK\n # | o | | o | | o |->output\n # | o | | o | | o |->output\n # | o | | o | | o |->output\n # _________________\n # I J K\n #\n # There are two sets of weighs: the weighs from layer i to j \n # and from j to k respectively\n \n Lyer = N._links #get links\n Outs = N._Network__algorithm._SigmoidBackPropagation__outputs\n Lclc = deepcopy(Lyer)\n sel = tuple(random() for x in range(i)) #testing selection\n res = [0]*k\n res[randint(0, len(res) - 1)] = 1\n learning_outcome = N.learn(sel, res)\n \n #FORWARD PROPAGATION:\n #step i-outputs:\n self.assertSequenceEqual(Outs[0], sel)\n self.assertEqual(len(Outs[0]), i)\n\n #calculate j - outputs:\n j_outs = []\n for n in Lclc[0]:\n j_outs.append(out(n, sel))\n #check j-outputs:\n self.assertSequenceEqual(Outs[1], j_outs)\n self.assertEqual(len(Outs[1]), j)\n\n #calculate k - outputs:\n k_outs = []\n for n in Lclc[1]:\n k_outs.append(out(n, j_outs))\n #check k-outputs:\n self.assertSequenceEqual(Outs[2], k_outs)\n self.assertEqual(len(Outs[2]), k)\n\n #BACK PROPAGATION:\n #calculate new layer:\n k_delta = tuple(map(lambda o, t: o*(1 - o)*(o - t), k_outs, res))\n #init next psy:\n j_psi = []\n for lnj in range(len(Lclc[-2])):\n j_psi.append(\n sum(k_delta[n]*Lclc[-1][n][lnj] \n for n in range(len(k_delta))))\n #correct all weights\n for ln in range(len(Lclc[-1])):\n dw = sp*k_delta[ln]\n for k in range(len(j_outs)):\n Lclc[-1][ln][k] -= j_outs[k]*dw\n Lclc[-1][ln][-1] -= dw\n\n self.assertTrue(len(Lyer[-1]), len(Lclc[-1]))\n self.assertSequenceEqual(Lyer[-1], Lclc[-1])\n\n #calculate new layer:\n j_delta = tuple(\n j_outs[lnj]*(1 - j_outs[lnj])*j_psi[lnj] \n for lnj in range(len(Lclc[-2])))\n for ln in range(len(Lclc[-2])):\n dw = sp*j_delta[ln]\n for k in range(len(sel)):\n Lclc[-2][ln][k] -= sel[k]*dw\n Lclc[-2][ln][-1] -= dw\n\n self.assertTrue(len(Lyer[-2]), len(Lclc[-2]))\n self.assertSequenceEqual(Lyer[-2], Lclc[-2])\n \n #TEST ACTIVATION FUNCTION:\n aouts = tuple(N.activate(sel))\n #calculate j - outputs:\n j_outs = []\n for n in Lclc[0]:\n j_outs.append(out(n, sel))\n #calculate k - outputs:\n k_outs = []\n for n in Lclc[1]:\n k_outs.append(out(n, j_outs))\n \n #check k-outputs:\n self.assertSequenceEqual(aouts, k_outs)\n self.assertEqual(len(aouts), len(k_outs))\n\n\n def ftest_network_structure(self):\n setup = i, j, k = 5, 2, 1\n # | o | | | | |\n # | o | | o | | |\n # | o | | | | o | } NEURONS\n # | o | | o | | |\n # | o | | | | |\n # ___________________\n # I J K\n #\n # So there are two sets of weighs: the weighs from layer i to j \n # and from k to k respectively\n N = Network(setup)\n self.assertEqual(len(N[:]), 2, \n 'wrong structure: the number of weights is wrong')\n self.assertEqual(len(N[0] + N[1]), j + k,\n 'wrong structure: the number of neurons is wrong')\n self.assertEqual(len(N[0][0]) + len(N[0][1]), 12, \n 'wrong struncture: the number the weighs from I to J '\n 'is wrong')\n self.assertEqual(len(N[1][0]), 3, \n 'wrong struncture: the number the weighs ' \n 'from J to K is wrong')\n\n def ftest_network_evaluation(self):\n W = [random() for x in range(12)]\n setup = 5, 2, 1\n ins = [1, 2, 3, 4, 5]\n N = Network(setup)\n bias = 0.05\n N[0][0][:5], N[0][0][-1] = W[:5], bias\n N[0][1][:5], N[0][1][-1] = W[5:10], bias\n N[1][0][:2], N[1][0][-1] = W[10:], bias\n #expected result:\n o1 = out(W[:5] + [bias], ins)\n o2 = out(W[5:10] + [bias], ins)\n oo = sigmoid(o1*W[10] + o2*W[11] + bias)\n #neural network structure validating:\n self.assertTrue((N[0][0][:-1] == W[:5] and \n N[0][1][:-1] == W[5:10] and \n N[1][0][:-1] == W[10:]), 'the weighs are incorrect')\n #evaluate method validating:\n self.assertEqual(next(N.evaluate(ins)), oo, 'invalid output')\n\n def ftest_network_learning_1(self):\n W = [random() for x in range(12)]\n setup = 5, 2, 1\n ins = [1, 2, 3, 4, 5]\n N = Network(setup)\n bias = 0.05\n N[0][0][-1] = N[0][1][-1] = N[1][0][-1] = bias #biases are zeros\n N[0][0][:5] = W[:5]\n N[0][1][:5] = W[5:10]\n N[1][0][:2] = W[10:]\n #expected result:\n o1 = out(W[:5] + [bias], ins)\n o2 = out(W[5:10] + [bias], ins)\n oo = sigmoid(o1*W[10] + o2*W[11] + bias)\n t = 1\n delta_k = oo*(1 - oo)*(oo - t)\n psai_k = W[10]*delta_k, W[11]*delta_k\n W[10] -= o1*delta_k\n W[11] -= o2*delta_k\n\n #hidden layer weighs correction\n #first neuron:\n delta_o1 = o1*(1 - o1)*psai_k[0]\n for i in range(5):\n W[i]-=ins[i]*delta_o1\n delta_o2 = o2*(1 - o2)*psai_k[1]\n for i in range(5, 10):\n W[i]-=ins[i - 5]*delta_o2\n E = N.learn(ins, (t,))\n #error checking:\n self.assertEqual(E, 0.5*(oo - t)**2)\n #weighs correction from k-1 to k:\n self.assertEqual(N[1][0], \n W[10:] + [-delta_k], \n \"invalid weight correction on the output layer\")\n #validating the hidden layer neurons' weithgs:\n self.assertEqual(\n N[0][0],\n W[:5] + [-delta_o1], \n \"invalid weight correction on the hidden layer\")\n self.assertEqual(N[0][1], \n W[5:10] + [-delta_o2],\n \"invalid weight correction on the hidden layer\")\n \n def ftest_network_learning_2(self):\n setup = (6, 2, 3, 1)\n ins = [1, 99, 1, 11, 3, 123]\n t = 1\n \n N = Network(setup)\n W = []\n for i in range(0, len(setup) - 1):\n W.append([random() for x in range(setup[i]*setup[i + 1])])\n for j in range(setup[i + 1]):\n N[i][j][:setup[i]] = W[i][j*setup[i]:(j + 1)*setup[i]]\n\n #structure validating:\n test_i = randint(1, len(setup) - 1)\n self.assertEqual(len(N[test_i-1]), setup[test_i])\n self.assertEqual(len(N[test_i-1][0]) -1, setup[test_i-1])\n\n #forward iteration 1:\n Oi1 = out(W[0][0:6], ins)\n Oi2 = out(W[0][6:12], ins)\n i_outs = Oi1, Oi2\n \n #forward iteration 2:\n Oj1 = out(W[1][0:2], i_outs)\n Oj2 = out(W[1][2:4], i_outs)\n Oj3 = out(W[1][4:6], i_outs)\n j_outs = Oj1, Oj2, Oj3\n \n #forward iteration 3:\n Ok = out(W[2], j_outs)\n\n #backward iteration 1:\n delta_k = Ok*(1 - Ok)*(Ok - t)\n psai = (W[2][0]*delta_k, W[2][1]*delta_k, W[2][2]*delta_k)\n W[2][0] -= Oj1*delta_k\n W[2][1] -= Oj2*delta_k\n W[2][2] -= Oj3*delta_k\n\n #helping func:\n def calc_delta(O, P):\n return list(map(lambda o, p: o*(1 - o)*p, O, P))\n #backward iteration 2:\n delta_J = calc_delta(j_outs, psai)\n psai = ((\n W[1][0]*delta_J[0] + \n W[1][2]*delta_J[1] + \n W[1][4]*delta_J[2]\n ),\n W[1][1]*delta_J[0] + \n W[1][3]*delta_J[1] + \n W[1][5]*delta_J[2])\n\n W[1][0] -= Oi1*delta_J[0]\n W[1][1] -= Oi2*delta_J[0]\n\n W[1][2] -= Oi1*delta_J[1]\n W[1][3] -= Oi2*delta_J[1]\n \n W[1][4] -= Oi1*delta_J[2]\n W[1][5] -= Oi2*delta_J[2]\n\n #backward iteration 3:\n delta_I = calc_delta(i_outs, psai)\n for i in range(len(delta_I)):\n for j in range(6):\n W[0][i*6 + j] -= ins[j - i*6]*delta_I[i]\n\n E = N.learn(ins, (t,))\n self.assertEqual(E,0.5*(Ok-t)**2)\n #layer k checking:\n self.assertEqual(N[2][0], W[2] + [-delta_k])\n #layer j checking:\n self.assertEqual(N[1][0], W[1][0:2] + [-delta_J[0]])\n self.assertEqual(N[1][1], W[1][2:4] + [-delta_J[1]])\n self.assertEqual(N[1][2], W[1][4:6] + [-delta_J[2]])\n #leyar i checking:\n self.assertEqual(N[0][0], W[0][:6] + [-delta_I[0]])\n self.assertEqual(N[0][1], W[0][6:] + [-delta_I[1]])\n\nclass TestMutableNeuralNetwork(unittest.TestCase):\n \n def test_instance(self):\n layers = (5, 4, 1)\n m = MutableNetwork(*layers, n = 0.05)\n\n self.assertSequenceEqual(m.shape, layers)\n self.assertEqual(m.ninps, layers[0])\n self.assertEqual(m.nouts, layers[-1])\n self.assertEqual(m.speed, 0.05)\n self.assertEqual(repr(m), \n \"MutableNetwork({}, {}, {}, n = 0.05)\".format(*layers))\n self.assertTrue(HiddenLayers(m)) #true when the network has at \n #least one hidden layer, false otherwise\n self.assertTrue(InputLayer(m)) #always true\n self.assertTrue(OutputLayer(m)) #alwayes true\n self.assertFalse( #__len__() is called to consider bool value\n HiddenLayers(MutableNetwork(9, 2))) #len == 0 (no h-layers)\n\n self.assertIsNot(InputLayer(m), m.input_layer)\n self.assertIsNot(HiddenLayers(m), m.hidden_layers)\n self.assertIsNot(OutputLayer(m), m.output_layer)\n\n self.assertRaises(ValueError, MutableNetwork, 3) #too few args\n self.assertRaises(ValueError, MutableNetwork, 3, 0, 1) #empty layer\n self.assertRaises(ValueError, MutableNetwork, 8, -4, 1) #negative\n \n self.assertRaises(TypeError, MutableNetwork, 10, 9, 7, 1.01, 3)\n self.assertRaises(TypeError, MutableNetwork, 1.2, 9) #float size\n with self.assertRaises(TypeError):\n #verify that the speed coefficient cannot be non-numbers\n MutableNetwork(3, 2, n = 'str')\n self.assertRaises(TypeError, HiddenLayers, [0, 1])\n self.assertRaises(TypeError, OutputLayer, 99)\n self.assertRaises(TypeError, InputLayer, 'shrub')\n\n def test_primitives(self):\n self.assertIsInstance(Primitives.initweight(), _Number)\n #init sequence test:\n w_cnt = randrange(1, _SIZE)\n weights = Primitives.initweights(w_cnt)\n self.assertIsInstance(weights, _Sequence)\n for w in weights:\n self.assertIsInstance(w, _Number)\n self.assertEqual(len(weights), w_cnt)\n self.assertEqual(len(Primitives.initneuron(w_cnt)), w_cnt + 1)\n #init layer test:\n n_cnt = randrange(1, _SIZE)\n lyr = Primitives.initlayer(n_cnt, w_cnt)\n self.assertEqual(len(lyr), n_cnt)\n for n in lyr:\n self.assertIsInstance(n, _Sequence)\n self.assertEqual(len(n), w_cnt + 1)\n\n #adjusting layer:\n wshift = randrange(1, _SIZE)\n Primitives.adjustlayer(lyr, w_cnt + wshift)\n for n in lyr:\n self.assertIsInstance(n, _Sequence)\n self.assertEqual(len(n), w_cnt + wshift + 1)\n for w in n:\n self.assertIsInstance(w, _Number)\n\n self.assertRaises(ValueError, Primitives.initneuron, 0)\n self.assertRaises(TypeError, Primitives.initlayer, 2.1, 99)\n self.assertRaises(ValueError, Primitives.initlayer, \n randrange(-_SIZE, 1), 99)\n self.assertRaises(ValueError, Primitives.initlayer, 3, \n randrange(-_SIZE, 1))\n self.assertRaises(ValueError, Primitives.adjustlayer, lyr,\n randrange(-_SIZE, 1))\n\n def test_neuron_view_1(self):\n \"\"\"Tests basic operations of NeuronView\"\"\"\n test_nlinks = randrange(1, _SIZE)\n test_seq = Primitives.initneuron(test_nlinks)\n test_view = NeuronView(test_seq)\n eval_view = eval(repr(test_view))\n\n self.assertEqual(eval_view, test_view)\n self.assertSequenceEqual(eval_view, test_view)\n \n self.assertEqual(eval_view, test_seq)\n self.assertSequenceEqual(eval_view, test_seq[:-1])\n\n self.assertEqual(len(test_view), test_nlinks)\n self.assertEqual(test_view.bias, test_seq[-1])\n self.assertSequenceEqual(test_view.weights, test_seq[:-1])\n self.assertSequenceEqual(test_view.tolist(), test_seq)\n \n #simple mutation:\n test_index = randrange(len(test_view))\n test_value = uniform(-_SIZE, _SIZE)\n test_view[test_index] = test_value\n self.assertEqual(test_view[test_index], test_value)\n self.assertEqual(test_view[test_index], test_seq[test_index])\n\n test_seq[test_index] = uniform(-_SIZE, _SIZE)\n self.assertEqual(test_view[test_index], test_seq[test_index])\n self.assertFalse(test_view.tolist() is test_seq) #if copy\n\n #errors:\n self.assertRaises(IndexError, test_view.__getitem__, \n choice([-1, 1])*len(test_seq))\n self.assertRaises(TypeError, test_view.__getitem__, 2.33)\n self.assertRaises(TypeError, test_view.__setitem__, \n \"cowabunga dude!\")\n with self.assertRaises(TypeError):\n test_view.bias = \"Pokemon\"\n\n def test_neuron_view_2(self):\n \"\"\"Tests set and get methods of NeuronView by using mixed slices\"\"\"\n sz = _SIZE\n for x in range(_NUM):\n nlinks = randrange(1, sz)\n links = Primitives.initneuron(nlinks)\n view = NeuronView(links)\n\n tslice = slice(randrange(0, sz), randrange(0, sz), \n choice([1, -1])*randrange(1, 4))\n self.assertSequenceEqual(links[:-1][tslice], view[tslice])\n slice_len = len(range(*tslice.indices(len(view))))\n new_weights = Primitives.initweights(slice_len)\n view[tslice] = new_weights\n \n self.assertSequenceEqual(links[:-1][tslice], new_weights)\n self.assertSequenceEqual(links[:-1][tslice], view[tslice])\n \n self.assertRaises(ValueError, view.__setitem__, tslice, \n [0]*(nlinks + 1))\n self.assertRaises(ValueError, view.__getitem__, \n slice(None, None, 0))\n self.assertRaises(ValueError, view.__setitem__, \n slice(None, None, 0), [])\n self.assertRaises(TypeError, view.__setitem__, \n slice(None, None), ['spam']*len(view))\n\n indx = randrange(len(view))\n with self.assertRaises(TypeError):\n view[randrange(len(view))] = 'S'\n\n self.assertEqual(view[indx:indx], [])\n \n def test_get_hlayer(self):\n for x in range(_NUM):\n M = TestMutableNeuralNetwork.__inititem(minsize = 3)\n L = M.hidden_layers\n test_start = randrange(0, len(L)) #target index\n test_slice = slice(test_start, randrange(test_start, len(L)))\n self.assertTrue(\n all(all(isinstance(n, NeuronView) for n in lyr) \n for lyr in L[test_slice]), \n 'inappropriate type of returning values')\n #check correspondence between M._links[s] and M[s]\n for Mi, Li in zip(M._links[test_slice], L[test_slice]):\n for Mij, Lij in zip(Mi, Li):\n self.assertSequenceEqual(Mij[:-1], Lij) #only weights\n self.assertSequenceEqual(\n Mij[:-1], Lij.weights) #only weights\n self.assertEqual(Mij[-1], Lij.bias) #only bias term\n self.assertSequenceEqual(Mij, Lij.tolist())\n\n #check slices at random layer\n test_layer_index = test_start\n test_layer = tuple(L[test_layer_index])\n test_start = randrange(len(test_layer))\n test_slice = slice(test_start, \n randrange(0, len(test_layer)))\n self.assertTrue(all(\n isinstance(n, NeuronView) for n in test_layer[test_slice]),\n 'inappropriate tupe of returning values')\n for m, n in zip(M._links[test_layer_index][test_slice], \n test_layer[test_slice]):\n self.assertSequenceEqual(m[:-1], n) #only weights\n self.assertSequenceEqual(m[:-1], n.weights) #only weights\n self.assertEqual(m[-1], n.bias) #only bias term\n self.assertSequenceEqual(m, n.tolist())\n \n #weird index combinations:\n self.assertEqual(L[test_layer_index:test_layer_index], tuple())\n self.assertEqual(list(L[test_layer_index, \n test_start:test_start]), [])\n\n self.assertSequenceEqual(tuple(L[test_layer_index, :]), \n tuple(L[test_layer_index]))\n self.assertEqual(list(L[test_layer_index, \n test_slice.start:len(test_layer):-1]), [])\n\n #exceptions:\n self.assertRaises(TypeError, L.__getitem__, (test_slice, 1)\n #the double index notation should not accept slices\n #at the first part\n )\n self.assertRaises(IndexError, L.__getitem__, len(M._links) - 1\n #the hidden layer view allow access by input layer's \n #index\n )\n self.assertRaises(IndexError, L.__getitem__, \n choice([1,-1])*(randrange(0, _SIZE) + len(M._links)),\n #index error is not raised when the given index is\n #out of range\n )\n self.assertRaises(ValueError, L.__getitem__, \n slice(test_slice.start, test_slice.stop, 0)\n ) #slice step cannot be zero\n\n def test_insert_hlayer_1(self):\n \"\"\"\n Verify inserting a new layer using simple sequences\n \"\"\"\n for x in range(_NUM):\n M = TestMutableNeuralNetwork.__inititem()\n L = M.hidden_layers\n test_index = randint(0, len(L)) #target index\n #height of the current layer:\n height = M.shape[test_index] #number of inpurts per neuron\n test_layer = Primitives.initlayer(randrange(1, _SIZE), height)\n L.insert(test_index, test_layer)\n #next layer:\n next_layer = M._links[test_index + 1] #adjusted layer\n inserted_layer = M._links[test_index] #inserted layer\n #if the next layer consistent:\n self.assertTrue(\n all(len(l) - 1 == len(test_layer) for l in next_layer),\n \"lost consistency after insertion\")\n self.assertEqual(inserted_layer, test_layer, \n \"the inserted layer does not match the initial layer\")\n #checking if there is no dependencies between the inserted \n #layer and the source layer:\n self.assertTrue(all(not l is v for l, v in \n zip(test_layer, inserted_layer)), \n \"inserted layer has a dependency on its source\")\n \n fake_layer = Primitives.initlayer(randrange(1, _SIZE), height)\n fake_layer[randrange(len(fake_layer))].append(0) #contains the \n #wrong number of weights\n \n #run with fake values:\n self.assertRaises(ValueError, L.insert, test_index, fake_layer)\n self.assertRaises(TypeError, L.insert, randint(0, len(L)), \n [\"Em-bin-gun-do\", \"Endin-bo-go\"])\n self.assertRaises(ValueError, L.insert, \n test_index, [[0]*height])\n\n def test_insert_hlayer_2(self):\n \"\"\"\n Verify inserting a new layer using mixed sequences \n \"\"\"\n for x in range(_NUM):\n M = TestMutableNeuralNetwork.__inititem()\n L = M.hidden_layers\n test_index = randint(0, len(L)) #target index\n #height of the current layer:\n height = M.shape[test_index]\n test_layer = tuple(choice([tuple, NeuronView, list])(\n Primitives.initweights(height + 1)) for x in range(\n randrange(2, _SIZE)))\n L.insert(test_index, test_layer)\n next_layer = M._links[test_index + 1] #adjusted layer\n self.assertTrue(all(len(l) - 1 == len(test_layer) \n for l in next_layer), \"lost consistency after insertion\")\n \n self.assertRaises(ValueError, L.insert, test_index, \n [NeuronView(Primitives.initweights(height + 2)) \n for x in range(randrange(1, _SIZE))])\n \n def test_delete_hlayer(self):\n for x in range(_NUM):\n M = TestMutableNeuralNetwork.__inititem(minsize = 3)\n L = M.hidden_layers\n test_index = randrange(0, len(L)) #target index\n #delete one lyr:\n del L[test_index]\n links_per_neuron = M.shape[test_index]\n next_layer = M._links[test_index]\n self.assertTrue(all(len(n) - 1 == links_per_neuron \n for n in next_layer), \"lost consistency after deleting\")\n #delete all:\n del L[:]\n self.assertTrue(all(len(n) == M.ninps #'n' is NeuronView \n for n in M.output_layer), \"lost consistency in the \"\n \"output layer after deleting all hidden layers\")\n\n def test_setget_hlayer(self):\n \"\"\"Tests assignment, deletion and evaluation implementations of \n HiddenLayers (__setitem__, __delitem__, __getitem__)\"\"\"\n for x in range(_NUM):\n M = TestMutableNeuralNetwork.__inititem()\n #to ensure that the count of inputs does not changes:\n ninps = M.ninps #initial count of inputs\n H = M.hidden_layers\n shape = M.shape\n start = randrange(len(M) - 1)\n inset = [Primitives.initlayer(\n randrange(1, _SIZE), shape[start])]\n inset.append(Primitives.initlayer(randrange(1, _SIZE), \n len(inset[0])))\n H[start:] = inset\n for o in M.output_layer:\n self.assertEqual(len(o), len(inset[1]))\n #deletion test:\n del H[:]\n for o in M.output_layer:\n self.assertEqual(len(o), ninps)\n\n def test_output_layer_1(self):\n \"\"\"Tests basic operations of OutputLayer\"\"\"\n for x in range(_NUM):\n M = TestMutableNeuralNetwork.__inititem()\n O = M.output_layer\n rindex = randrange(len(O)) #random index\n view = O[rindex]\n tnode = M._links[-1][rindex] #target node\n self.assertSequenceEqual(view, tnode[:-1])\n self.assertEqual(view.bias, tnode[-1])\n #mutaion test:\n windex = randrange(len(view))\n wvalue = randrange(-_SIZE, _SIZE)\n view[windex] = wvalue\n\n self.assertEqual(tnode[windex], wvalue)\n #check how consistency is reestablished after mutation:\n links = M.shape[-2]\n if M.nlayr > 2:\n H = M.hidden_layers\n H[-1, links:] = [Primitives.initneuron(M.shape[-3])]\n b = len(tuple(H[-1, :]))\n else:\n I = M.input_layer\n I.insert(len(I))\n \n self.assertEqual(len(view), links + 1)\n self.assertEqual(len(tnode), links + 2)\n self.assertSequenceEqual(tnode, view)\n\n @staticmethod\n def __inititem(minsize = 2):\n return MutableNetwork(*(\n randrange(1, _SIZE) for x in range(randrange(minsize, _SIZE))))\n\n\n###########################################################################\n### Run tests\n###########################################################################\n\ndef _test():\n unittest.main(verbosity = 2)\n\n#run test:\nif __name__ == '__main__':\n _test()\n","sub_path":"multinet/nn/test_neuro.py","file_name":"test_neuro.py","file_ext":"py","file_size_in_byte":25555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"326553491","text":"import logging\nimport os\nfrom typing import List, Optional, Tuple\n\nimport joblib\nimport numpy as np\nimport pandas as pd\nimport pyarrow as pa\nimport pyarrow.parquet as pq\nimport scipy.sparse as ss\n\nfrom gleams import config\nfrom gleams.feature import encoder, spectrum\nfrom gleams.ms_io import ms_io\n\n\nlogger = logging.getLogger('gleams')\n\n\ndef _peaks_to_features(dataset: str, filename: str,\n metadata: Optional[pd.DataFrame],\n enc: encoder.SpectrumEncoder)\\\n -> Tuple[str, Optional[pd.DataFrame], Optional[List[ss.csr_matrix]]]:\n \"\"\"\n Convert the spectra with the given identifiers in the given file to a\n feature array.\n\n Parameters\n ----------\n dataset : str\n The peak file's dataset.\n filename : str\n The peak file name.\n metadata : Optional[pd.DataFrame]\n DataFrame containing metadata for the PSMs in the peak file to be\n processed. If None, all spectra in the peak file are converted to\n features.\n enc : encoder.SpectrumEncoder\n The SpectrumEncoder used to convert spectra to features.\n\n Returns\n -------\n Tuple[str, Optional[pd.DataFrame], Optional[List[ss.csr_matrix]]]\n A tuple of length 3 containing: the name of the file that has been\n converted, information about the converted spectra (scan number,\n precursor charge, and precursor m/z), the converted spectra.\n If the given file does not exist the final two elements of the tuple\n are None.\n \"\"\"\n peak_filename = os.path.join(\n os.environ['GLEAMS_HOME'], 'data', 'peak', dataset, filename)\n if not os.path.isfile(peak_filename):\n logger.warning('Missing peak file %s, no features generated',\n peak_filename)\n return filename, None, None\n logger.debug('Process file %s/%s', dataset, filename)\n file_scans, file_mz, file_charge, file_encodings = [], [], [], []\n if metadata is not None:\n metadata = metadata.reset_index(['dataset', 'filename'], drop=True)\n for spec in ms_io.get_spectra(peak_filename):\n if ((metadata is None or np.int64(spec.identifier) in metadata.index)\n and spectrum.preprocess(spec, config.fragment_mz_min,\n config.fragment_mz_max).is_valid):\n file_scans.append(spec.identifier)\n file_mz.append(spec.precursor_mz)\n file_charge.append(spec.precursor_charge)\n file_encodings.append(enc.encode(spec))\n scans = pd.DataFrame({'scan': file_scans, 'charge': file_charge,\n 'mz': file_mz})\n scans['scan'] = scans['scan'].astype(np.int64)\n return filename, scans, file_encodings\n\n\ndef convert_peaks_to_features(metadata_filename: str)\\\n -> None:\n \"\"\"\n Convert all peak files listed in the given metadata file to features.\n\n Encoded spectra will be stored as NumPy binary files for each dataset in\n the metadata. A corresponding index file for each dataset containing the\n peak filenames, spectrum identifiers, and indexes in the NumPy binary file\n will be stored as Parquet files.\n\n If both the NumPy binary file and the Parquet index file already exist, the\n corresponding dataset will _not_ be processed again.\n\n Parameters\n ----------\n metadata_filename : str\n The metadata file name. Should be a Parquet file.\n \"\"\"\n metadata = pd.read_parquet(metadata_filename)\n metadata = metadata.set_index(['dataset', 'filename', 'scan'])\n\n enc = encoder.MultipleEncoder([\n encoder.PrecursorEncoder(\n config.num_bits_precursor_mz, config.precursor_mz_min,\n config.precursor_mz_max, config.num_bits_precursor_mass,\n config.precursor_mass_min, config.precursor_mass_max,\n config.precursor_charge_max),\n encoder.FragmentEncoder(\n config.fragment_mz_min, config.fragment_mz_max, config.bin_size),\n encoder.ReferenceSpectraEncoder(\n config.ref_spectra_filename, config.fragment_mz_min,\n config.fragment_mz_max, config.fragment_mz_tol,\n config.num_ref_spectra)\n ])\n\n logger.info('Convert peak files for metadata file %s', metadata_filename)\n feat_dir = os.path.join(os.environ['GLEAMS_HOME'], 'data', 'feature',\n 'dataset')\n if not os.path.isdir(feat_dir):\n try:\n os.makedirs(os.path.join(feat_dir))\n except OSError:\n pass\n dataset_total = len(metadata.index.unique('dataset'))\n for dataset_i, (dataset, metadata_dataset) in enumerate(\n metadata.groupby('dataset', as_index=False, sort=False), 1):\n # Group all encoded spectra per dataset.\n feat_dir = os.path.join(os.environ['GLEAMS_HOME'], 'data', 'feature')\n filename_encodings = os.path.join(\n feat_dir, 'dataset', f'{dataset}.npz')\n filename_index = os.path.join(\n feat_dir, 'dataset', f'{dataset}.parquet')\n if (not os.path.isfile(filename_encodings) or\n not os.path.isfile(filename_index)):\n logging.info('Process dataset %s [%3d/%3d]', dataset, dataset_i,\n dataset_total)\n metadata_index, encodings = [], []\n for filename, file_scans, file_encodings in\\\n joblib.Parallel(n_jobs=-1, backend='multiprocessing')(\n joblib.delayed(_peaks_to_features)\n (dataset, fn, md_fn, enc)\n for fn, md_fn in metadata_dataset.groupby(\n 'filename', as_index=False, sort=False)):\n if file_scans is not None and len(file_scans) > 0:\n metadata_index.extend([(dataset, filename, scan)\n for scan in file_scans['scan']])\n encodings.extend(file_encodings)\n # Store the encoded spectra in a file per dataset.\n if len(metadata_index) > 0:\n ss.save_npz(filename_encodings, ss.vstack(encodings, 'csr'))\n metadata.loc[metadata_index].reset_index().to_parquet(\n filename_index, index=False)\n\n\ndef combine_features(metadata_filename: str) -> None:\n \"\"\"\n Combine feature files for multiple datasets into a single feature file.\n\n If the combined feature file already exists it will _not_ be recreated.\n\n Parameters\n ----------\n metadata_filename : str\n Features for all datasets included in the metadata will be combined.\n Should be a Parquet file.\n \"\"\"\n feat_dir = os.path.join(os.environ['GLEAMS_HOME'], 'data', 'feature')\n feat_filename = os.path.join(feat_dir, os.path.splitext(\n os.path.basename(metadata_filename))[0].replace('metadata', 'feature'))\n if (os.path.isfile(f'{feat_filename}.npz') and\n os.path.isfile(f'{feat_filename}.parquet')):\n return\n datasets = pd.read_parquet(\n metadata_filename, columns=['dataset'])['dataset'].unique()\n logger.info('Combine features for metadata file %s containing %d datasets',\n metadata_filename, len(datasets))\n encodings, indexes = [], []\n for i, dataset in enumerate(datasets, 1):\n logger.debug('Append dataset %s [%3d/%3d]', dataset, i, len(datasets))\n dataset_encodings_filename = os.path.join(\n feat_dir, 'dataset', f'{dataset}.npz')\n dataset_index_filename = os.path.join(\n feat_dir, 'dataset', f'{dataset}.parquet')\n if (not os.path.isfile(dataset_encodings_filename) or\n not os.path.isfile(dataset_index_filename)):\n logger.warning('Missing features for dataset %s, skipping...',\n dataset)\n else:\n encodings.append(ss.load_npz(dataset_encodings_filename))\n indexes.append(pq.read_table(dataset_index_filename))\n ss.save_npz(f'{feat_filename}.npz', ss.vstack(encodings, 'csr'))\n pq.write_table(pa.concat_tables(indexes), f'{feat_filename}.parquet')\n","sub_path":"gleams/feature/feature.py","file_name":"feature.py","file_ext":"py","file_size_in_byte":8073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"457430424","text":"import numpy as np\nimport matplotlib as plt\nimport os\nimport serial\nimport time\nimport h5py\nimport sys\nimport matplotlib.pyplot as plt\nfrom frgpl.camera import camera\nfrom frgpl.stage import stage\nfrom frgpl.kepco import kepco\nfrom frgpl.daq import daq\nfrom frgpl.laser import laser\nfrom frgpl.tec import omega\nimport datetime\nimport time\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom tqdm import tqdm\nimport threading\nimport pdb\nimport winsound\nfrom frgpl.checkPLmaps import plotPL\n\nsoundpath='C:\\\\Users\\\\Operator\\\\Documents\\\\GitHub\\\\Instruments\\\\FRG Hardware\\\\frgpl\\\\frgpl\\\\tada.wav'\n\nroot = 'C:\\\\Users\\\\Operator\\\\Desktop\\\\frgPL'\t\t#default folder to save data\nif not os.path.exists(root):\n\tos.mkdir(root)\ndatafolder = os.path.join(root, 'Data')\nif not os.path.exists(datafolder):\n\tos.mkdir(datafolder)\ncalibrationfolder = os.path.join(root, 'Calibration')\nif not os.path.exists(calibrationfolder):\n\tos.mkdir(calibrationfolder)\n\n\nclass control:\n\n\tdef __init__(self, kepcoport = 'COM5',laserport = 'COM1', spotmapnumber = None):\n\t\t# hardware properties\n\t\tself.kepcoport = kepcoport\n\t\tself.laserport = laserport\n\t\tself.__laserON = False\n\t\tself.__kepcoON = False\n\t\tself.__cameraON = False\n\n\t\t# measurement settings\n\t\tself.bias = 0\t\t\t#bias applied to sample\n\t\tself.laserpower = 0\t#current supplied to laser ###may replace this with n_suns, if calibration is enabled\n\t\tself.saturationtime = 0.5\t#delay between applying voltage/illumination and beginning measurement\n\t\tself.numIV = 20\t\t#number of IV measurements to average\n\t\tself.numframes = 50\t#number of image frames to average\n\t\tself.__temperature = 25\t#TEC stage temperature setpoint (C) during measurement\n\t\tself.temperatureTolerance = 0.2\t#how close to the setpoint we need to be to take a measurement (C)\n\t\tself.maxSoakTime = 60\t# max soak time, in seconds, to wait for temperature to reach set point. If we reach this point, just go ahead with the measurement\n\t\tself.note = ''\n\t\tself._spotMap = None\t# optical power map of laser spot, used for PL normalization\n\t\tself._sampleOneSun = None # fractional laser power with which to approximate one-sun injection levels\n\t\tself._sampleOneSunJsc = None # target Jsc, matching of which is used for one-sun injection level is approximated\n\t\tself._sampleOneSunSweep = None # fractional laser power vs photocurrent (Isc), fit to provide one-sun estimate\n\t\tself.__previewFigure = None\t#handle for matplotlib figure, used for previewing most recent image results\n\t\tself.__previewAxes = [None, None]\t# handle for matplotib axes, used to hold the image and colorbar\n\t\tself.__backgroundImage = None\n\n\t\t# data saving settings\n\t\ttodaysDate = datetime.datetime.now().strftime('%Y%m%d')\n\t\tself.outputDirectory = os.path.join(root, 'Data', todaysDate)\t#default save locations is desktop/frgPL/Data/(todaysDate)\n\t\tself.sampleName = None\n\t\tself.__dataBuffer = [] # buffer to hold data files during sequential measurements of single sample. Held until a batch export\n\n\t\t# stage/positioning constants\n\t\tself.__sampleposition = (52000, 56000)\t#position where TEC stage is centered in camera FOV, um\n\t\tself.__detectorposition = (68000, 117000)\t#delta position between detector and sampleposition, um.\n\t\tself.__fov = (77000, 56000)\t#dimensions of FOV, um\n\n\t\tself.connect()\n\t\tself.loadSpotCalibration(spotmapnumber)\n\t@property\n\tdef temperature(self):\n\t\treturn self.__temperature\n\n\t@temperature.setter\n\tdef temperature(self, t):\n\t\tif self.tec.setSetPoint(t):\n\t\t\tself.__temperature = t\n\t\t\n\n\tdef connect(self):\n\t\tself.camera = camera()\t\t# connect to FLIR camera\n\t\tself.kepco = kepco()\t\t# connect to Kepco\n\t\tself.kepco.set(voltage=0) # set voltage to 0, seems to solve current compliance issues\n\t\tself.laser = laser()\t\t# Connect to OSTECH Laser\n\t\tself.daq = daq()\t\t\t# connect to NI-USB6000 DAQ\n\t\tself.stage = stage(sampleposition = self.__sampleposition)\t\t# connect to FRG stage\n\t\tself.tec = omega()\t\t\t# connect to omega PID controller, which is driving the TEC stage.\n\t\t\n\tdef disconnect(self):\n\t\ttry:\n\t\t\tself.camera.disconnect()\n\t\texcept:\n\t\t\tprint('Could not disconnect camera')\n\n\t\ttry:\n\t\t\tself.kepco.disconnect()\n\t\texcept:\n\t\t\tprint('Could not disconnect Kepco')\n\t\ttry:\n\t\t\tself.laser.disconnect()\n\t\texcept:\n\t\t\tprint('Could not disconnect OSTech Laser')\n\t\ttry:\n\t\t\tself.daq.disconnect()\n\t\texcept:\n\t\t\tprint('Could not disconnect DAQ')\n\t\ttry:\n\t\t\tself.stage.disconnect()\n\t\texcept:\n\t\t\tprint('Could not disconnect stage')\n\t\ttry:\n\t\t\tself.tec.disconnect()\n\t\texcept:\n\t\t\tprint('Could not disconnect TEC controller')\n\n\n\t### basic use functions\n\n\tdef setMeas(self, bias = None, laserpower = None, suns = None, saturationtime = None, temperature = None, numIV = None, numframes = None, note = ''):\n\n\t\tif bias is None:\n\t\t\tbias = self.bias\n\t\tif laserpower is None:\n\t\t\tif suns is None:\n\t\t\t\tlaserpower = self.laserpower\n\t\t\telse:\n\t\t\t\tif self._sampleOneSun is None:\n\t\t\t\t\tprint('Error: can\\'t use \"suns =\" without calibration - please run .findOneSun to calibrate one-sun power level for this sample.')\n\t\t\t\t\treturn False\n\t\t\t\telse:\n\t\t\t\t\tlaserpower = suns * self._sampleOneSun\n\t\t\t\t\tif (laserpower > 1) or (laserpower < 0):\n\t\t\t\t\t\tmaxsuns = 1/self._sampleOneSun\n\t\t\t\t\t\tprint('Error: {0} suns is out of range! Based on laser power and current sample, allowed suns range = 0 - {1}.'.format(suns, maxsuns))\n\t\t\t\t\t\tif laserpower > 1:\n\t\t\t\t\t\t\tprint('Setting to max laser power ({0} suns)'.format(maxsuns))\n\t\t\t\t\t\t\tlaserpower = 1\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint('Setting laser off')\n\t\t\t\t\t\t\tlaserpower = 0\n\t\t\t\t\t\t# return False\n\t\tif saturationtime is None:\n\t\t\tsaturationtime = self.saturationtime\n\t\tif temperature is None:\n\t\t\ttemperature = self.__temperature\n\t\tif numIV is None:\n\t\t\tnumIV = self.numIV\n\t\tif numframes is None:\n\t\t\tnumframes = self.numframes\n\n\n\t\tresult = self.kepco.set(voltage = bias)\n\t\tif result:\n\t\t\tself.bias = bias\n\t\telse:\n\t\t\tprint('Error setting kepco')\n\t\t\t# return False\n\n\t\tresult = self.laser.set(power = laserpower)\n\n\t\tif result:\n\t\t\tself.laserpower = laserpower\n\t\telse:\n\t\t\tprint('Error setting laser')\n\t\t\t# return False\n\n\n\t\tresult = self.tec.setSetPoint(temperature)\n\t\tif result:\n\t\t\tself.__temperature = temperature\n\t\telse:\n\t\t\tprint('Error setting TEC temperature')\n\t\t\t# return False\n\n\n\t\tself.numIV = numIV\n\t\tself.numframes = numframes\n\t\tself.note = note\n\n\tdef takeMeas(self, lastmeasurement = True, preview = True, imputeHotPixels = False):\n\t\t### takes a measurement with settings stored in method (can be set with .setMeas()).\n\t\t#\tmeasurement settings + results are appended to .__dataBuffer\n\t\t#\n\t\t#\tif .__dataBuffer is empty (ie, no measurements have been taken yet), takeMeas() will \n\t\t#\tautomatically take a 0 bias, 0 laser power baseline measurement before the scheduled\n\t\t#\tmeasurement.\n\n\t\tif len(self.__dataBuffer) == 0: # sample is being measured for the first time, take a baseline image\n\t\t\tprint('New sample: taking a 0 bias, 0 illumination baseline image.')\n\t\t\t# store scheduled measurement parameters\n\t\t\tsavedlaserpower = self.laserpower\n\t\t\tsavedbias = self.bias\n\t\t\tsavednote = self.note\n\n\t\t\t# take a 0 bias, 0 laserpower measurement, append to .__dataBuffer\n\t\t\tself.setMeas(bias = 0, laserpower = 0, note = 'automatic baseline image')\n\t\t\tself._waitForTemperature()\n\t\t\tmeasdatetime = datetime.datetime.now()\n\t\t\ttemperature = self.tec.getTemperature()\n\t\t\tim, _, _ = self.camera.capture(frames = self.numframes, imputeHotPixels = imputeHotPixels)\n\t\t\tv, i = self.kepco.read(counts = self.numIV)\n\t\t\tirradiance = self._getOpticalPower()\n\t\t\ttemperature = (temperature + self.tec.getTemperature()) / 2\t#average the temperature from just before and after the measurement. Typically averaging >1 second of time here.\n\t\t\tmeas = {\n\t\t\t\t'sample': \tself.sampleName,\n\t\t\t\t'note':\t\tself.note,\n\t\t\t\t'date': \tmeasdatetime.strftime('%Y-%m-%d'),\n\t\t\t\t'time':\t\tmeasdatetime.strftime('%H:%M:%S'),\n\t\t\t\t'cameraFOV':self.__fov,\n\t\t\t\t'bias':\t\tself.bias,\n\t\t\t\t'laserpower': self.laserpower,\n\t\t\t\t'saturationtime': self.saturationtime,\n\t\t\t\t'numIV':\tself.numIV,\n\t\t\t\t'numframes':self.numframes,\n\t\t\t\t'v_meas':\tv,\n\t\t\t\t'i_meas':\ti,\n\t\t\t\t'image':\tim,\n\t\t\t\t'image_bgcorrected': im-im,\n\t\t\t\t'irradiance_ref': irradiance, \n\t\t\t\t'temperature':\ttemperature,\n\t\t\t\t'temperature_setpoint': self.temperature\n\t\t\t}\n\t\t\tself.__dataBuffer.append(meas)\t\n\t\t\tself.__backgroundImage = im \t#store background image for displaying preview\n\n\t\t\t# restore scheduled measurement parameters + continue \t\n\t\t\tself.setMeas(bias = savedbias, laserpower = savedlaserpower, note = savednote)\n\n\t\tif not self.__laserON and self.laserpower > 0:\n\t\t\tself.laser.on()\n\t\t\tself.__laserON = True\n\t\tif not self.__kepcoON: #and self.bias is not 0:\n\t\t\tself.kepco.on()\t#turn on the kepco source\n\t\t\tself.__kepcoON = True\n\n\t\ttime.sleep(self.saturationtime)\n\n\t\t#take image, take IV meas during image\n\t\tself._waitForTemperature()\n\t\tmeasdatetime = datetime.datetime.now()\n\t\ttemperature = self.tec.getTemperature()\n\t\tim, _, _ = self.camera.capture(frames = self.numframes, imputeHotPixels = imputeHotPixels)\n\t\tv, i = self.kepco.read(counts = self.numIV)\n\t\t#pdb.set_trace()\n\t\tirradiance = self._getOpticalPower()\n\t\ttemperature = (temperature + self.tec.getTemperature()) / 2\t#average the temperature from just before and after the measurement. Typically averaging >1 second of time here.\n\n\t\tif self.__laserON and lastmeasurement:\n\t\t\tself.laser.off()\n\t\t\tself.__laserON = False\n\t\tif self.__kepcoON and lastmeasurement:\n\t\t\tself.kepco.off()\n\t\t\tself.__kepcoON = False\n\n\t\tmeas = {\n\t\t\t'sample': \tself.sampleName,\n\t\t\t'note':\t\tself.note,\n\t\t\t'date': \tmeasdatetime.strftime('%Y-%m-%d'),\n\t\t\t'time':\t\tmeasdatetime.strftime('%H:%M:%S'),\n\t\t\t'cameraFOV':self.__fov,\n\t\t\t'bias':\t\tself.bias,\n\t\t\t'laserpower': self.laserpower,\n\t\t\t'saturationtime': self.saturationtime,\n\t\t\t'numIV':\tself.numIV,\n\t\t\t'numframes':self.numframes,\n\t\t\t'v_meas':\tv,\n\t\t\t'i_meas':\ti,\n\t\t\t'image':\tim,\n\t\t\t'image_bgcorrected': self._backgroundCorrection(im),\n\t\t\t'irradiance_ref': irradiance,\n\t\t\t'temperature': temperature,\n\t\t\t'temperature_setpoint': self.temperature\n\t\t}\n\t\tself.__dataBuffer.append(meas)\n\n\t\tif preview:\n\t\t\tself.displayPreview(self._backgroundCorrection(im), v, i)\n\n\t\treturn im, v, i\n\n\tdef displayPreview(self, img, v, i):\n\t\tdef handle_close(evt, self):\n\t\t\tself.__previewFigure = None\n\t\t\tself.__previewAxes = [None, None]\n\t\t\n\t\tif self.__previewFigure is None:\t#preview window is not created yet, lets make it\n\t\t\tplt.ioff()\n\t\t\tself.__previewFigure, self.__previewAxes[0] = plt.subplots()\n\t\t\tdivider = make_axes_locatable(self.__previewAxes[0])\n\t\t\tself.__previewAxes[1] = divider.append_axes('right', size='5%', pad=0.05)\n\t\t\tself.__previewFigure.canvas.mpl_connect('close_event', lambda x: handle_close(x, self))\t# if preview figure is closed, lets clear the figure/axes handles so the next preview properly recreates the handles\n\t\t\tplt.ion()\n\t\t\tplt.show()\n\n\t\tfor ax in self.__previewAxes:\t#clear the axes\n\t\t\tax.clear()\n\t\timg_handle = self.__previewAxes[0].imshow(img)\n\t\tself.__previewFigure.colorbar(img_handle, cax = self.__previewAxes[1])\n\t\tself.__previewAxes[0].set_title('{0} V, {1} A, {2} Laser'.format(v, i, self.laserpower))\n\t\tself.__previewFigure.canvas.draw()\n\t\tself.__previewFigure.canvas.flush_events()\n\t\ttime.sleep(1e-4)\t\t#pause allows plot to update during series of measurements \n\n\tdef save(self, samplename = None, note = '', outputdirectory = None, reset = True):\n\t\tif len(self.__dataBuffer) == 0:\n\t\t\tprint('Data buffer is empty - no data to save!')\n\t\t\treturn False\n\n\t\t## figure out the sample directory, name, total filepath\n\t\tif samplename is not None:\n\t\t\tself.sampleName = samplename\n\n\t\tif outputdirectory is not None:\n\t\t\tself.outputDirectory = outputdirectory\n\t\tif not os.path.exists(self.outputDirectory):\n\t\t\tos.mkdir(self.outputDirectory)\n\n\t\tfids = os.listdir(self.outputDirectory)\n\t\tsampleNumber = 1\n\t\tfor fid in fids:\n\t\t\tif 'frgPL' in fid:\n\t\t\t\tsampleNumber = sampleNumber + 1\n\n\t\ttodaysDate = datetime.datetime.now().strftime('%Y%m%d')\n\n\t\tif self.sampleName is not None:\n\t\t\tfname = 'frgPL_{0}_{1:04d}_{2}.h5'.format(todaysDate, sampleNumber, self.sampleName)\n\t\telse:\n\t\t\tfname = 'frgPL_{0}_{1:04d}.h5'.format(todaysDate, sampleNumber)\n\t\t\tself.sampleName = ''\n\n\t\tfpath = os.path.join(self.outputDirectory, fname)\n\n\t\t## build each category in h5 file\n\n\t\t### example dataset saved to _dataBuffer by .takeMeas\n\t\t# meas = {\n\t\t# \t'sample': \tself.sampleName,\n\t\t# \t'date': \tmeasdatetime.strftime('%Y-%m-%d'),\n\t\t# \t'time':\t\tmeasdatetime.strftime('%H:%M:%S'),\n\t\t# \t'cameraFOV':self.__fov,\n\t\t# \t'bias':\t\tself.bias,\n\t\t# \t'laserpower': self.laserpower,\n\t\t# \t'saturationtime': self.saturationtime,\n\t\t# \t'numIV':\tself.numIV,\n\t\t# \t'numframes':self.numframes,\n\t\t# \t'v_meas':\tv,\n\t\t# \t'i_meas':\ti,\n\t\t# \t'image':\tim,\n\t\t# }\n\n\t\tnumData = len(self.__dataBuffer)\n\n\t\tdata = {}\n\t\tfor field in self.__dataBuffer[0].keys():\n\t\t\tdata[field] = []\n\t\t### field to store normalized PL images\n\t\t# if self._spotmap is not None:\n\t\t# \tdata['image_norm'] = []\n\n\t\tfor meas in self.__dataBuffer:\n\t\t\tfor field, measdata in meas.items():\n\t\t\t\tdata[field].append(measdata)\n\t\t\t\t### normalize PL images here\n\t\t\t\t# if field is 'image' and self._spotmap is not None:\n\t\t\t\t# \tdata['image_norm']\n\n\n\t\t## write h5 file\n\n\t\twith h5py.File(fpath, 'w') as f:\n\t\t\t# sample info\n\t\t\tinfo = f.create_group('/info')\n\t\t\tinfo.attrs['description'] = 'Metadata describing sample, datetime, etc.'\n\t\t\t\n\t\t\ttemp = info.create_dataset('name', data = self.sampleName.encode('utf-8'))\n\t\t\ttemp.attrs['description'] = 'Sample name.'\n\t\t\t\n\t\t\ttemp = info.create_dataset('notes', data = np.array(note.encode('utf-8')))\n\t\t\ttemp.attrs['description'] = 'Any notes describing each measurement.'\n\n\t\t\tdate = info.create_dataset('date', data = np.array([x.encode('utf-8') for x in data['date']]))\n\t\t\ttemp.attrs['description'] = 'Measurement date.'\n\t\t\t\n\t\t\ttemp = info.create_dataset('time', data = np.array([x.encode('utf-8') for x in data['time']]))\n\t\t\ttemp.attrs['description'] = 'Measurement time of day.'\n\n\n\t\t\t# measurement settings\n\t\t\tsettings = f.create_group('/settings')\n\t\t\tsettings.attrs['description'] = 'Settings used for measurements.'\n\n\t\t\ttemp = settings.create_dataset('vbias', data = np.array(data['bias']))\n\t\t\ttemp.attrs['description'] = 'Nominal voltage bias set by Kepco during measurement.'\n\n\t\t\ttemp = settings.create_dataset('notes', data = np.array([x.encode('utf-8') for x in data['note']]))\n\t\t\ttemp.attrs['description'] = 'Any notes describing each measurement.'\n\n\t\t\ttemp = settings.create_dataset('laserpower', data = np.array(data['laserpower']))\n\t\t\ttemp.attrs['description'] = 'Fractional laser power during measurement. Calculated as normalized laser current (max current = 55 A). Laser is operated at steady state.'\n\n\t\t\ttemp = settings.create_dataset('sattime', data = np.array(data['saturationtime']))\n\t\t\ttemp.attrs['description'] = 'Saturation time for laser/bias conditioning prior to sample measurement. Delay between applying condition and measuring, in seconds.'\n\n\t\t\ttemp = settings.create_dataset('numIV', data = np.array(data['numIV']))\n\t\t\ttemp.attrs['description'] = 'Number of current/voltage measurements averaged by Kepco when reading IV.'\n\n\t\t\ttemp = settings.create_dataset('numframes', data = np.array(data['numframes']))\n\t\t\ttemp.attrs['description'] = 'Number of camera frames averaged when taking image.'\n\n\t\t\ttemp = settings.create_dataset('tempsp', data = np.array(data['temperature_setpoint']))\n\t\t\ttemp.attrs['description'] = 'TEC stage temperature setpoint for each measurement.'\n\n\n\t\t\tif self.stage.position[0] is None:\n\t\t\t\tstagepos = self.__sampleposition\n\t\t\telse:\n\t\t\t\tstagepos = self.stage.position\n\n\t\t\ttemp = settings.create_dataset('position', data = np.array(stagepos))\n\t\t\ttemp.attrs['description'] = 'Stage position during measurement.'\n\n\t\t\tif self._sampleOneSun is not None:\n\t\t\t\tsuns = [x/self._sampleOneSun for x in data['laserpower']]\n\t\t\t\ttemp = settings.create_dataset('suns', data = np.array(suns))\n\t\t\t\ttemp.attrs['description'] = 'PL injection level in terms of suns. Only present if sample was calibrated with .findOneSun to match measured Isc to provided expected value, presumably from solar simulator JV curve.'\n\n\t\t\t# calibrations\n\t\t\tcalibrations = f.create_group('/calibrations')\n\t\t\tcalibrations.attrs['description'] = 'Instrument calibrations to be used for data analysis.'\n\n\t\t\ttemp = settings.create_dataset('samplepos', data = np.array(self.__sampleposition))\n\t\t\ttemp.attrs['description'] = 'Stage position (um)[x,y] where sample is centered in camera field of view'\n\n\t\t\ttemp = settings.create_dataset('detectorpos', data = np.array(self.__detectorposition))\n\t\t\ttemp.attrs['description'] = 'Stage position (um) [x,y] where photodetector is centered in camera field of view'\n\n\t\t\ttemp = settings.create_dataset('camerafov', data = np.array(self.__fov))\n\t\t\ttemp.attrs['description'] = 'Camera field of view (um) [x,y]'\n\n\t\t\tif self._spotMap is not None:\n\t\t\t\ttemp = calibrations.create_dataset('spot', data = np.array(self._spotMap))\n\t\t\t\ttemp.attrs['description'] = 'Map [y, x] of incident optical power across camera FOV, can be used to normalize PL images. Laser power set to 0.5 during spot mapping.'\n\n\t\t\t\ttemp = calibrations.create_dataset('spotx', data = np.array(self._spotMapX))\n\t\t\t\ttemp.attrs['description'] = 'X positions (um) for map of incident optical power across camera FOV, can be used to normalize PL images.'\n\n\t\t\t\ttemp = calibrations.create_dataset('spoty', data = np.array(self._spotMap))\n\t\t\t\ttemp.attrs['description'] = 'Y positions (um) for map of incident optical power across camera FOV, can be used to normalize PL images.'\n\n\t\t\tif self._sampleOneSunSweep is not None:\n\t\t\t\ttemp = calibrations.create_dataset('onesunsweep', data = np.array(self._sampleOneSunSweep))\n\t\t\t\ttemp.attrs['description'] = 'Laser current vs photocurrent, measured for this sample. Column 1: fractional laser current. Column 2: total photocurrent (Isc), NOT current density (Jsc). Only present if sample was calibrated with .findOneSun to match measured Isc to provided expected value, presumably from solar simulator JV curve.'\n\n\t\t\t\ttemp = calibrations.create_dataset('onesun', data = np.array(self._sampleOneSun))\n\t\t\t\ttemp.attrs['description'] = 'Fractional laser current used to approximate a one-sun injection level. Only present if sample was calibrated with .findOneSun to match measured Isc to provided expected value, presumably from solar simulator JV curve.'\n\n\t\t\t\ttemp = calibrations.create_dataset('onesunjsc', data = np.array(self._sampleOneSunJsc))\n\t\t\t\ttemp.attrs['description'] = 'Target Jsc (NOT Isc) used to approximate a one-sun injection level. Only present if sample was calibrated with .findOneSun to match measured Isc to provided expected value, presumably from solar simulator JV curve.'\n\n\t\t\t# raw data\n\t\t\trawdata = f.create_group('/data')\n\t\t\trawdata.attrs['description'] = 'Raw measurements taken during imaging'\n\n\t\t\ttemp = rawdata.create_dataset('image', data = np.array(data['image']), chunks = True, compression = 'gzip')\n\t\t\ttemp.attrs['description'] = 'Raw images acquired for each measurement.'\n\n\t\t\ttemp = rawdata.create_dataset('image_bgc', data = np.array(data['image_bgcorrected']), chunks = True, compression = 'gzip')\n\t\t\ttemp.attrs['description'] = 'Background-subtracted images acquired for each measurement.'\n\n\t\t\ttemp = rawdata.create_dataset('v', data = np.array(data['v_meas']))\n\t\t\ttemp.attrs['description'] = 'Voltage measured during measurement'\n\n\t\t\ttemp = rawdata.create_dataset('i', data = np.array(data['i_meas']))\n\t\t\ttemp.attrs['description'] = 'Current (not current density!) measured during measurement'\n\n\t\t\ttemp = rawdata.create_dataset('irr_ref', data = np.array(data['irradiance_ref']))\n\t\t\ttemp.attrs['description'] = 'Measured irradiance @ photodetector during measurement. Note that the photodetector is offset from the sample FOV. Assuming that the laser spot is centered on the sample, this value is lower than the true sample irradiance. This value should be used in conjunction with a .spotMap() calibration map.'\t\t\t\n\n\t\t\ttemp = rawdata.create_dataset('temp', data = np.array(data['temperature']))\n\t\t\ttemp.attrs['description'] = 'Measured TEC stage temperature during measurement. This value is the average of two temperature measurements, just before and after the image/kepco readings/photodetector readings are made. These two values typically span >1 second'\n\n\t\tprint('Data saved to {0}'.format(fpath))\n\t\tif reset:\n\t\t\tself._sampleOneSun = None\n\t\t\tself._sampleOneSunSweep = None\n\t\t\tself._sampleOneSunJsc = None\n\t\t\tself.samplename = None\n\t\t\tself.__backgroundImage = None\n\n\t\t\tprint('Note: sample name and one sun calibration results have been reset to None')\n\t\t\n\t\tself.__dataBuffer = []\n\n\t\treturn fpath\n\n\t### tile imaging\n\tdef tileImages(self, xmin, xmax, numx, ymin, ymax, numy, frames = 100):\n\t\tx0, y0 = self.stage.position\n\t\txp = [int(x) for x in np.linspace(x0+xmin, x0+xmax, numx)]\n\t\typ = [int(y) for y in np.linspace(y0+ymin, y0+ymax, numy)]\n\t\tims = np.zeros((numy, numx, 512, 640))\n\t\tself.stage.moveto(x = xp[0], y = yp[0])\n\t\ttime.sleep(5) #sometimes stage says its done moving too early, expect that on first move which is likely a longer travel time\n\n\t\tflip = True #for snaking\n\t\tfor m, y in tqdm(enumerate(yp), total = numy, desc = 'Y', leave = False):\n\t\t\tif flip:\n\t\t\t\tflip = False\n\t\t\telse:\n\t\t\t\tflip = True\n\t\t\tself.stage.moveto(y = y)\n\t\t\tfor n, x in tqdm(enumerate(xp), total = numx, desc = 'X', leave = False):\n\t\t\t\tif flip:\n\t\t\t\t\tnn = -n-1\n\t\t\t\t\txx = xp[nn]\n\t\t\t\telse:\n\t\t\t\t\tnn = n\n\t\t\t\t\txx = x\n\t\t\t\tself.stage.moveto(x = xx)\n\t\t\t\tims[m,nn], _, _ = self.camera.capture(frames = frames)\n\t\tself.stage.moveto(x = x0, y = y0)\n\t\treturn ims, xp, yp\n\n\t### calibration methods\n\n\tdef findOneSun(self, jsc, area):\n\t\t### finds fraction laser power for which measured jsc = target value from solar simulator JV testing.\n\t\t# jsc: short circuit current density in mA/cm^2 (positive)\n\t\t# area: active area cm^2\n\t\tif jsc < 1:\n\t\t\tprint('Please provide jsc in units of mA/cm^2, and area in units of cm^2')\n\t\t\treturn False\n\n\t\tisc = -jsc * area / 1000 \t#negative total current in amps, since kepco will be measuring total photocurrent as amps\n\n\t\tlaserpowers = np.linspace(0,1, 7)[1:]\t#skip 0, lean on lower end to reduce incident power\n\t\tself.kepco.set(voltage = 0)\n\n\t\tlaserjsc = np.zeros(len(laserpowers))\n\n\t\tself.laser.set(power = laserpowers[0])\t\t#set to first power before turning on laser\n\t\tself.laser.on()\n\t\tself.kepco.on()\n\t\tfor idx, power in enumerate(laserpowers):\n\t\t\tself.laser.set(power = power)\n\t\t\ttime.sleep(self.saturationtime)\n\t\t\t_,laserjsc[idx] = self.kepco.read(counts = 25) \n\t\tself.laser.off()\n\t\tself.kepco.off()\n\n\t\t#pdb.set_trace()\n\n\t\tpfit = np.polyfit(laserjsc, laserpowers, 2)\n\t\tp = np.poly1d(pfit)\t#polynomial fit object where x = measured jsc, y = laser power applied\n\t\t\n\t\tself._sampleOneSun = p(isc)\n\t\tself._sampleOneSunSweep = [laserpowers, laserjsc]\n\t\tself._sampleOneSunJsc = jsc\n\n\t\t#pdb.set_trace()\n\n\t\treturn p(isc), laserpowers, laserjsc\t#return laser power to match target jsc\n\n\tdef calibrateSpot(self, numx = 21, numy = 21, rngx = None, rngy = None, laserpower = 0.5, export = True):\n\t\t### maps an area around the sample FOV, finds the optical power at each point\n\t\tprint(\"calibration starting\")\n\n\t\tif not self.stage._homed:\n\t\t\tprint('Homing stage')\n\t\t\tself.stage.gohome()\n\t\t#default calibration area range = camera FOV\n\t\tif rngx is None:\n\t\t\trngx = self.__fov[0]\n\t\tif rngy is None:\n\t\t\trngy = self.__fov[1]\n\n\t\txpos = np.linspace(self.__detectorposition[0] - (rngx/2), self.__detectorposition[0] + (rngx/2), numx).astype(int)\n\t\typos = np.linspace(self.__detectorposition[1] - (rngy/2), self.__detectorposition[1] + (rngy/2), numy).astype(int)\n\t\t\n\t\tself.laser.set(power = laserpower)\n\t\tself._spotMap = np.zeros((numy, numx))\n\t\tself._spotMapX = xpos\n\t\tself._spotMapY = ypos\n\t\t\n\t\tprint('Moving to start position ({0}, {1})'.format(xpos[0], ypos[0]))\n\t\tif not self.stage.moveto(x = xpos[0], y = ypos[0]):\n\t\t\tprint('Error moving stage to starting position ({0}, {1}) - stage is probably not homed. run method ._stage.gohome()'.format(xpos[0], ypos[0]))\t\t\n\t\t\treturn False\n\n\t\tself.laser.on()\n\t\tflip = 1\n\t\tfor m, x in tqdm(enumerate(xpos), desc = 'X', total = len(xpos), leave = False):\n\t\t\tflip = flip * -1\n\t\t\tself.stage.moveto(x = x)\n\t\t\tfor n in tqdm(range(len(ypos)), desc = 'Y', total = len(ypos), leave = False):\n\t\t\t\tif flip > 0:\t\t#use nn instead of n, accounts for snaking between lines\n\t\t\t\t\tnn = len(ypos) - n - 1\n\t\t\t\telse:\n\t\t\t\t\tnn = n\n\t\t\t\tself.stage.moveto(y = ypos[nn])\n\t\t\t\tself._spotMap[nn,m] = self._getOpticalPower()/100 # suns\n\t\tself.laser.off()\n\n\t\tself.stage.moveto(x = self.__sampleposition[0], y = self.__sampleposition[1])\t#return stage to camera FOV\n\n\t\tif export:\n\t\t\tself.saveSpotCalibration(note = 'Autosaved by calibrateSpot')\n\n\tdef saveSpotCalibration(self, note = ''):\n\t\tfids = os.listdir(calibrationfolder)\n\t\tsampleNumber = 1\n\t\tfor fid in fids:\n\t\t\tif 'frgPL_spotCalibration' in fid:\n\t\t\t\tsampleNumber = sampleNumber + 1\n\n\t\ttodaysDate = datetime.datetime.now().strftime('%Y%m%d')\n\t\ttodaysTime = datetime.datetime.now().strftime('%H:%M:%S')\n\t\tfname = 'frgPL_spotCalibration_{0}_{1:04d}.h5'.format(todaysDate, sampleNumber)\n\t\tfpath = os.path.join(calibrationfolder, fname)\n\n\t\t## write h5 file\n\n\t\twith h5py.File(fpath, 'w') as f:\n\t\t\t# sample info\n\t\t\tinfo = f.create_group('/info')\n\t\t\tinfo.attrs['description'] = 'Metadata describing sample, datetime, etc.'\n\t\t\t\n\t\t\t# temp = info.create_dataset('name', data = self.sampleName.encode('utf-8'))\n\t\t\t# temp.attrs['description'] = 'Sample name.'\n\t\t\t\n\t\t\ttemp = info.create_dataset('notes', data = note.encode())\n\t\t\ttemp.attrs['description'] = 'Any notes describing each measurement.'\n\n\t\t\ttemp = info.create_dataset('date', data = todaysDate.encode())\n\t\t\ttemp.attrs['description'] = 'Measurement date.'\n\t\t\t\n\t\t\ttemp = info.create_dataset('time', data = todaysTime.encode())\n\t\t\ttemp.attrs['description'] = 'Measurement time of day.'\n\n\n\t\t\t# calibrations\n\t\t\tcalibrations = f.create_group('/calibrations')\n\t\t\tcalibrations.attrs['description'] = 'Instrument calibrations to be used for data analysis.'\n\n\t\t\ttemp = calibrations.create_dataset('samplepos', data = np.array(self.__sampleposition))\n\t\t\ttemp.attrs['description'] = 'Stage position (um)[x,y] where sample is centered in camera field of view'\n\n\t\t\ttemp = calibrations.create_dataset('detectorpos', data = np.array(self.__detectorposition))\n\t\t\ttemp.attrs['description'] = 'Stage position (um) [x,y] where photodetector is centered in camera field of view'\n\n\t\t\ttemp = calibrations.create_dataset('camerafov', data = np.array(self.__fov))\n\t\t\ttemp.attrs['description'] = 'Camera field of view (um) [x,y]'\n\n\t\t\ttemp = calibrations.create_dataset('spot', data = np.array(self._spotMap))\n\t\t\ttemp.attrs['description'] = 'Map [y, x] of incident optical power across camera FOV, can be used to normalize PL images. Laser power set to 0.5 during spot mapping.'\n\n\t\t\ttemp = calibrations.create_dataset('spotx', data = np.array(self._spotMapX))\n\t\t\ttemp.attrs['description'] = 'X positions (um) for map of incident optical power across camera FOV, can be used to normalize PL images.'\n\n\t\t\ttemp = calibrations.create_dataset('spoty', data = np.array(self._spotMapY))\n\t\t\ttemp.attrs['description'] = 'Y positions (um) for map of incident optical power across camera FOV, can be used to normalize PL images.'\n\n\t\tprint('Data saved to {0}'.format(fpath))\t\n\n\tdef loadSpotCalibration(self, calibrationnumber = None):\n\t\tfids = os.listdir(calibrationfolder)\n\t\tcalnum = []\n\t\tfor fid in fids:\n\t\t\tif 'frgPL_spotCalibration' in fid:\n\t\t\t\tcalnum.append(int(fid.split('_')[3].split('.')[0]))\n\t\t\telse:\n\t\t\t\tcalnum.append(0)\n\n\t\tif len(calnum) == 0:\n\t\t\tprint('Could not find any calibration files! No spotmap loaded')\n\t\t\treturn False\n\n\t\tcalfile = fids[calnum.index(max(calnum))]\t#default to most recent calibration\n\t\t\n\t\tif calibrationnumber is not None:\n\t\t\ttry:\n\t\t\t\tcalfile = fids[calnum.index(calibrationnumber)]\n\t\t\texcept:\n\t\t\t\tprint('Could not find calibration {0}: defaulting to most recent calibration {1}'.format(calibrationnumber, max(calnum)))\n\t\tfpath = os.path.join(calibrationfolder, calfile)\n\t\t## write h5 file\n\n\t\twith h5py.File(fpath, 'r') as f:\n\t\t\tself._spotMap = f['calibrations']['spot'][:]\n\t\t\tself._spotMapX = f['calibrations']['spotx'][:]\n\t\t\tself._spotMapT = f['calibrations']['spoty'][:]\n\n\t\tprint('Loaded calibration {0} from {1}.'.format(calnum[fids.index(calfile)], fpath))\n\t\treturn True\n\n\t### group measurement methods\n\n\tdef takeRseMeas(self, vmpp, voc, vstep = 0.005):\n\t\t# generate list of biases spanning from vmpp to at least voc, with intervals of vstep\n\t\tbiases = [vmpp + (voc-vmpp)/2]\n\t\twhile biases[-1] < voc + 0.07:\t\t#go to 70 mV (about 10% of starting Voc) higher voltage than Voc, better fitting/calibration constant is linear\n\t\t\tbiases.append(biases[-1] + vstep)\n\n\t\twith tqdm(total = len(biases), desc = 'Rse EL', leave = False) as pb:\n\t\t\tfor bias in biases[0:-1]:\t#measure all but last with lastmeasurement = True (doesnt turn kepco off between measurements). Last measurement is normal\n\t\t\t\tself.setMeas(bias = bias, laserpower = 0, note = 'part of Rse measurement series')\n\t\t\t\tself.takeMeas(lastmeasurement = False)\n\t\t\t\tpb.update(1)\n\n\t\t\tself.setMeas(bias = biases[-1], laserpower = 0, note = 'part of Rse measurement series')\n\t\t\tself.takeMeas(lastmeasurement = True)\t\t\n\t\t\tpb.update(1)\n\n\tdef takePLIVMeas(self, vmpp, voc, jsc, area):\n\t\t### Takes images at varied bias and illumination for PLIV fitting of cell parameters\n\t\t### based on https://doi.org/10.1016/j.solmat.2012.10.010\n\n\t\tif self._sampleOneSun is None:\n\t\t\tself.findOneSun(jsc = jsc, area = area)\t\t# calibrate laser power to one-sun injection by matching jsc from solar simulator measurement\n\n\t\t# full factorial imaging across voltage (vmpp - voc) and illumination (0.2 - 1.0 suns). 25 images\n\t\tallbiases = np.append(0,np.linspace(vmpp, voc, 5))\t\t#range of voltages used for image generation (including short-circuit image at each intensity)\n\t\tallsuns = np.linspace(0.2, 1, 5)\t\t\t#range of suns (pl injection) used for image generation\n\n\t\tself.setMeas(bias = 0, suns = 1, temperature = 25, note = 'PLIV - open circuit PL image')\n\t\t# this should work, something else is going wrong occasionally.\n\t\tself.kepco.set(current = 0) # does not work as takeMeas will reset the voltage setting based on setMeas parameters. Better to set voc directly in setMeas.\n\t\t#pdb.set_trace()\n\t\tself.takeMeas()\n\n\t\twith tqdm(total = allbiases.shape[0] * allsuns.shape[0], desc = 'PLIV', leave = False) as pb:\n\t\t\tfor suns in allsuns:\n\t\t\t\tfor bias in allbiases:\n\t\t\t\t\tself.setMeas(bias = bias, suns = suns, temperature = 25, note = 'PLIV')\n\t\t\t\t\tself.takeMeas(lastmeasurement = False)\n\t\t\t\t\tpb.update(1)\n\n\n\t\tself.laser.off()\t#turn off the laser and kepco\n\t\tself.kepco.off()\n\n\t\t#self.save(samplename = 'Test_GG_Al_10_PLIV', note = '', reset = True) # remove this for a regular measurement with takePVRD2Meas\n\n\n\tdef takePVRD2Meas(self, samplename, note, vmpp, voc, jsc, area = 22.1, vstep = 0.005):\n\t\t#reset in case previous measurement was cancelled midway\n\t\tself.__dataBuffer = []\n\t\tself._sampleOneSun = None\n\t\tself._sampleOneSunSweep = None\n\t\tself._sampleOneSunJsc = None\n\t\tself.__backgroundImage = None\n\n\t\tself.takeRseMeas(\n\t\t\tvmpp = vmpp,\n\t\t\tvoc = voc,\n\t\t\tvstep = vstep\n\t\t\t)\n\n\t\tself.takePLIVMeas(\n\t\t\tvmpp = vmpp,\n\t\t\tvoc = voc,\n\t\t\tjsc = jsc,\n\t\t\tarea = area\n\t\t\t)\n\n\t\tself.setMeas(\n\t\t\tbias = -12,\n\t\t\tlaserpower = 0,\n\t\t\tnote = 'Reverse Bias EL'\n\t\t\t)\n\t\tself.takeMeas()\n\n\t\t#figure out the directory to save data to\n\t\tstoredOutputDir = self.outputDirectory\n\t\tself.outputDirectory = os.path.join(root, 'PVRD2 Degradation Study')\n\t\tif not os.path.exists(self.outputDirectory):\n\t\t\tos.mkdir(self.outputDirectory)\n\t\ttodaysDate = datetime.datetime.now().strftime('%Y%m%d')\n\t\tself.outputDirectory = os.path.join(root, 'PVRD2 Degradation Study', todaysDate)\n\t\tif not os.path.exists(self.outputDirectory):\n\t\t\tos.mkdir(self.outputDirectory)\n\n\t\tfpath=self.save(samplename = samplename, note = note, reset = True)\n\n\t\tself.outputDirectory = storedOutputDir\n\n\t\twinsound.PlaySound(soundpath,winsound.SND_FILENAME)\n\t\tplotPL(fpath) # plot images to check the measurement\n\n\t### helper methods\n\tdef _waitForTemperature(self):\n\t\trefreshDelay = 0.5\t#how long to wait between temperautre checks, in seconds\n\t\treachedTemp = False\n\n\t\tstartTime = time.time()\n\t\twhile (not reachedTemp) and (time.time() - startTime <= self.maxSoakTime):\n\t\t\tcurrentTemp = self.tec.getTemperature()\n\t\t\tif np.abs(currentTemp - self.temperature) <= self.temperatureTolerance:\n\t\t\t\treachedTemp = True\n\t\t\telse:\n\t\t\t\ttime.sleep(refreshDelay)\n\n\t\tif not reachedTemp:\n\t\t\tprint('Did not reach {0} C within {1} seconds: starting measurement anyways.'.format(self.temperature, self.maxSoakTime))\n\n\t\treturn True\n\n\tdef _getOpticalPower(self):\n\t\t### reads signal from photodetector, converts to optical power using calibration vs thorlabs Si power meter (last checked 2019-08-20)\n\t\tcalibrationFit = [-0.1145, 9.1180]; #polyfit of detector reading vs (Si power meter / detector reading), 2019-08-20\n\t\tvoltage, _, _ = self.daq.acquire()\n\t\tpower = voltage * (calibrationFit[0]*voltage + calibrationFit[1])\t#measured optical power, units of mW/cm^2\n\n\t\treturn power\n\n\tdef _backgroundCorrection(self, img):\n\t\timg = img - self.__backgroundImage\n\t\timg[img<0] = 0\n\n\t\treturn img\n\t#def normalizePL(self):\n\t### used laser spot power map to normalize PL counts to incident optical power\n","sub_path":"FRG Hardware/frgpl/frgpl/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":33142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"148549684","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win-amd64\\egg\\ResultDashboard\\Dashboard\\DistMetricPVTab.py\n# Compiled at: 2020-03-15 13:04:26\n# Size of source mod 2**32: 15125 bytes\nimport dash_html_components as html\nfrom ResultDashboard.Dashboard.DashContent import *\nfrom ResultDashboard.Dashboard.DashPlot import *\nimport dash_core_components as dcc\nfrom dash.dependencies import Input, Output, State\nimport dash_daq as daq, dash_table\n\nclass DistMetricPVTab:\n\n def __init__(self, app, DataObject):\n self.app = app\n self.DataObject = DataObject\n self.content = html.Div([\n self.FirstLayer(),\n self.SecondLayer(),\n self.ThirdLayer(),\n self.FourthLayer(),\n self.FifthLayer()])\n\n def FirstLayer(self):\n self.Heading_content = 'System Level Risk Metrics'\n self.Detail_content = 'Percentage time average customer would experience violations are defined as risk metrics. Violations are categorized into three types: Voltage violation (any voltage magnitude above 1.1 pu and below 0.9 pu) , line violation (loading aboove 100%) and transformer violation (above 100%). SARDI_voltage, SARDI_line, SARDI_transformer represent System Average Risk Duration Index for voltage, line and transformer violation respectievely. SARDI_aggregated represents System Average Risk Duration Index for all violations. Knowing how PV deployement would alter these risk metrics can better inform PV deployement decisions. Base case means no PV. PV scenarios is defined by two components. For e.g. 10%-100% PV scenario means that 10% of total customers (chosen uniformly randomly) have installed PV with a capcity to meet 100% of their annual energy need when they do not have PV in their system.'\n left_col = html.Div([Paragraph(self.Heading_content, self.Detail_content).layout(), html.Div([dcc.Graph(figure=(LinePlot((self.DataObject.ViolationDict), ylabel='Risk Metric (%)').layout()))])], className='col')\n self.Heading_content = 'Percentage Energy Loss'\n self.Detail_content = 'Percentage energy Loss is an indicator of efficiency. Loss in the energy is a loss in economic reveune and also increases loss of life of an equipment (such as conductors and transformers). Along with risk metrics we also need to see how PV deployment affects percentage energy loss. Higher deployement of PV would increase loading in the distribution network thus increasing loss in the system. SE_line, SE_transformer and SE represent system energy loss for line elements (including both conductors and cables), system energy loss for transformers and overall system energy loss. Accuracy of these results depend on accuracy ofparameters of component such as resistance, reactance, capacitance, percentage loss during full load and no load of transformer etc. Furthermore, how accurate load profiles are also has an impact. Field measurements could certainly help validating these results.'\n right_col = html.Div([Paragraph(self.Heading_content, self.Detail_content).layout(), html.Div([dcc.Graph(figure=(LinePlot((self.DataObject.Efficiency), ylabel='Energy Loss (%)').layout()))])], className='col')\n return html.Div([left_col, right_col], className='row margin-top-20')\n\n def SecondLayer(self):\n self.Heading_content = 'Percentage Loss of Life of Transformer'\n self.Detail_content = 'Transformer loss of life is a function of hot-spot temperature inside transformer element. Hot spot temperature further depends on loading pattern which certainly would be affected by PV deployment. IEEE C57.92-1981 provides detail description on how to compute loss of life from loading pattern. Here we have assumed life of transformer is determined by deterioration of insulating material because of temperature. The numbers are reliable only if the loadings are normal (meaning not severly high for long period of time). This may not be highly accurate now however provides relative understanding pattern in loss of life because of PV deployement providing more support to PV deployement decision.'\n left_col = html.Div([Paragraph(self.Heading_content, self.Detail_content).layout(), html.Div([dcc.Graph(figure=(LinePlot((self.DataObject.Lossoflife), ylabel='Loss of Life - DTs (%)').layout()))])], className='col')\n self.Heading_content = 'Percentage Overgeneration by PV'\n self.Detail_content = 'Higher deployment of PV can cause reverse power flow in the system which can accumulate at the substation level. If there is a limit on reverse power flow because of storage constraints or market constraints or any other constraints deploying PV above certain percentage of overgeneration might be infesabile to utility. This metric further complements the PV deployement decesion by providing more insight on PV overgeneration. For now we have not included storage in the system. Furthermore, more advanced protection scheme might be necessary to allow reverse power flow in the system.'\n right_col = html.Div([Paragraph(self.Heading_content, self.Detail_content).layout(), html.Div([dcc.Graph(figure=(LinePlot((self.DataObject.overgeneration), ylabel='PV Overgeneration (%)').layout()))])], className='col')\n return html.Div([left_col, right_col], className='row margin-top-20')\n\n def ThirdLayer(self):\n self.Heading_content = 'Time Series System Level Metrics: Understading daily variation of system level risk metrics'\n self.Detail_content = \"Now let's take a look at above metrics in time-series mode. How would above metrics vary in time at different PV scenarios would help us identify day when they are highly impacted. You can select PV scenarios and observe metric variation in the graph.Note you can multi-select parameters to observe. Values are aggregated for day.\"\n col = html.Div([Paragraph(self.Heading_content, self.Detail_content).layout(),\n html.Div([\n html.Div([html.H6('Select System Level Metric'),\n dcc.Dropdown(id='Metric', options=[{'label':key, 'value':key} for key in self.DataObject.SystemMetrics],\n value=[\n 'SARDI_aggregated'],\n multi=True,\n style={'color': '#000000'})],\n className='col DropDown'),\n html.Div([html.H6('Select PV Penetration Scenario'),\n dcc.Dropdown(id='PVScenario', options=[{'label':key, 'value':key} for key in self.DataObject.Scenarios],\n value='Base',\n style={'color': '#000000'})],\n className='col H6 DropDown')],\n className='row'),\n html.Div([dcc.Graph(id='TimeSeriesSystemLevelMetric')])])\n return col\n\n def FourthLayer(self):\n TimeStamps = list(self.DataObject.SystemLevelMetricsTimeSeries['Base']['TimeStamp'])\n self.Heading_content = 'Time Series Asset Level Metric: Scatter plot on top of network map'\n self.Detail_content = 'Now that we know what the system level distribution metric look like, it is also important to know which asset are at vulnerable state or which asset is actually causing problem. The Scatter plot on top of network allows utility which components are vulnerable and where they are located and at what time. User can use dropdown menu to select different PV scenarios.'\n col = html.Div([Paragraph(self.Heading_content, self.Detail_content).layout(),\n html.Div([\n html.Div([html.H6('Select Asset Level Metric'),\n dcc.Dropdown(id='AssetMetric', options=[{'label':key, 'value':key} for key in self.DataObject.AssetLevelMetrics],\n value='NVRI',\n style={'color': '#000000'})],\n className='col DropDown'),\n html.Div([html.H6('Select PV Penetration Scenario'),\n dcc.Dropdown(id='PVScenario2', options=[{'label':key, 'value':key} for key in self.DataObject.Scenarios],\n value='Base',\n style={'color': '#000000'})],\n className='col H6 DropDown')],\n className='row'),\n html.Div([html.H6('Slide for observing temporal change'),\n daq.Slider(id='TimeIndex', min=0, max=(len(TimeStamps)), value=3, step=1, marks={str(val):{'label': TimeStamps[val].strftime('%m-%d')} for val in range(0, len(TimeStamps), 6)}, size=1100)],\n style={'margin-left':'50px', \n 'margin-right':'10px'}),\n html.Div([dcc.Graph(id='AssetLevelMetricHeatMap')], style={'margin-top': '30px'})])\n return col\n\n def FifthLayer(self):\n self.Heading_content = 'Asset Level Metric: Table and Aggregated Map'\n self.Detail_content = ' The aggreagted metric for an asset is listed in table on the right and shown in the form of scatter heatmap on the left. Size and color both help to identify vulnerable component. The components are selected based on the metric you selected to observe in time series asset level metric.'\n col = html.Div([Paragraph(self.Heading_content, self.Detail_content).layout(),\n html.Div([\n dash_table.DataTable(id='interactiveTable', columns=[], data=[], sort_action='native', column_selectable='single', sort_mode='multi',\n page_action='native',\n page_current=0,\n page_size=10,\n style_header={'backgroundColor':'rgb(30, 30, 30)', 'fontWeight':'bold'},\n style_cell={'backgroundColor':'rgb(30, 30, 30)', \n 'color':'white'})],\n className='col DropDown'),\n html.Div([dcc.Graph(id='AssetLocation')], className='col')],\n className='row')\n return col\n\n def layout(self):\n return self.content\n\n def MarkerDict(self, Data, title):\n SizeArray = [0 + 40 * (value - min(Data)) / (max(Data) - min(Data)) for value in Data]\n return dict(color=Data, showscale=True, colorscale=[\n [\n 0, '#21c7ef'], [0.33, '#76f2ff'], [0.66, '#ff6969'], [1, '#ff1717']],\n cmin=(min(Data)),\n cmax=(max(Data)),\n size=SizeArray,\n colorbar=dict(x=0.85, len=0.7, title=dict(text=title, font={'color':'#737a8d', \n 'family':'Open Sans', 'size':16}),\n titleside='top',\n tickmode='array',\n tickvals=[\n min(Data), max(Data)],\n ticktext=[\n '{:,.2f}'.format(min(Data)), '{:,.2f}'.format(max(Data))],\n ticks='outside',\n thickness=25,\n tickfont={'family':'Open Sans', \n 'color':'#737a8d', 'size':16}))\n\n def Callbacks(self):\n\n @self.app.callback(Output('TimeSeriesSystemLevelMetric', 'figure'), [Input('PVScenario', 'value'), Input('Metric', 'value')])\n def UpdateTimeSeriesPlot(PVscenario, Metric):\n ScenarioData = self.DataObject.SystemLevelMetricsTimeSeries[PVscenario]\n DataDict = {'TimeStamp': ScenarioData['TimeStamp']}\n for metric in Metric:\n DataDict[metric] = ScenarioData[metric]\n\n return TimeSeriesLinePlot(DataDict, ylabel='Metric in %').layout()\n\n @self.app.callback([Output('interactiveTable', 'data'), Output('interactiveTable', 'columns')], [\n Input('AssetMetric', 'value'), Input('PVScenario2', 'value')])\n def update_table(Metric, PVScenario):\n DataFrameSelected = self.DataObject.AssetMetricsAggregated[PVScenario][Metric]\n columns = [{'name':col, 'id':col, 'selectable':True} for col in ['Component', Metric]]\n DataDict = [{'Component': DataFrameSelected['Metrics'].tolist()[index], Metric: DataFrameSelected['Values'].tolist()[index]} for index in range(len(DataFrameSelected))]\n return (DataDict, columns)\n\n @self.app.callback([Output('AssetLevelMetricHeatMap', 'figure'), Output('AssetLocation', 'figure')], [\n Input('AssetMetric', 'value'), Input('PVScenario2', 'value'), Input('TimeIndex', 'value')])\n def UpdateAssetMetricOverNetwork(Metric, PVScenario, TimeIndex):\n DataSelected = self.DataObject.AssetMetricsTimeSeries[PVScenario][Metric].loc[TimeIndex]\n PVcoordinates = self.DataObject.PVcoordinates[PVScenario]\n AggregatedAssetData = self.DataObject.AssetMetricsAggregated[PVScenario][Metric]\n if Metric in ('NVRI', ):\n ComponentCoordinates = self.DataObject.NodeCoordinatesDict\n if Metric in ('TVRI', 'TE', 'TLOF', 'TOG'):\n ComponentCoordinates = self.DataObject.TransformerCoordinatesDict\n if Metric in ('LE', 'LVRI'):\n ComponentCoordinates = self.DataObject.LineCoordintesDict\n if Metric in ('CRI', ):\n ComponentCoordinates = self.DataObject.CustomerCoordinatesDict\n MetricArray = [DataSelected[keys] for keys in ComponentCoordinates.keys()]\n x_coordinate = [values['x'] for keys, values in ComponentCoordinates.items()]\n y_coordinate = [values['y'] for keys, values in ComponentCoordinates.items()]\n return (\n GeoScatterMap((self.DataObject.x_lines), (self.DataObject.y_lines), x_coordinate, y_coordinate, (self.DataObject.initial_x), (self.DataObject.initial_y), marker=(self.MarkerDict(MetricArray, Metric)), height=800, zoom=14).layout(),\n GeoScatterMap((self.DataObject.x_lines), (self.DataObject.y_lines), x_coordinate, y_coordinate, (self.DataObject.initial_x),\n (self.DataObject.initial_y), marker=(self.MarkerDict(AggregatedAssetData['Values'].tolist(), Metric))).layout())","sub_path":"pycfiles/EMeRGE-1.4a0-py3.7/DistMetricPVTab.cpython-37.py","file_name":"DistMetricPVTab.cpython-37.py","file_ext":"py","file_size_in_byte":13571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"528619766","text":"#!/usr/bin/python\n\nfrom Bio import SeqIO\nfrom itertools import count\nimport sys\n\nfake_header = \"NS500502:001:HT3KMBGXY:{n}:{n:05}:{n:05}:{n:04} {r}:N:0:CTGAAGCT+AGGATAGG\"\n\nwith open(sys.argv[1], 'r') as forward:\n with open(sys.argv[2], 'r') as reverse:\n try:\n fw = open(sys.argv[3], 'w')\n rw = open(sys.argv[4], 'w')\n except IndexError:\n fw = rw = sys.stdout\n for fr, rv, ind in zip(SeqIO.parse(forward, 'fastq'), SeqIO.parse(reverse, 'fastq'), count()):\n fr.id = fr.name = fake_header.format(n=ind, r=1)\n rv.id = rv.name = fake_header.format(n=ind, r=2)\n fr.description = rv.description = ''\n SeqIO.write(fr, fw, 'fastq')\n SeqIO.write(rv, rw, 'fastq')\n","sub_path":"python/03_fake_header.py","file_name":"03_fake_header.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"566730652","text":"# coding: utf-8\n\nimport pandas as pd\nimport os.path, argparse\n\n\nif __name__=='__main__':\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('assignment_path', type=str, help='Path to the csv file containing classification info.')\n\tparser.add_argument('data_path', type=str, help='Path to the tsv file containing full data classified.')\n\tparser.add_argument('--subdata', type=str, default=None, help='Path to a file containing subdata to be output.')\n\tparser.add_argument('--sep', type=str, default='\\t', help='Separator of the subdata file. tab stop by default (i.e., tsv).')\n\targs = parser.parse_args()\n\n\n\tdf_assign = pd.read_csv(args.assignment_path)\n\n\tdf_data = pd.read_csv(args.data_path, encoding='utf-8', sep='\\t')\n\n\t# df_assign.loc[:,'lemma'] = df_data.lemma\n\tdf_assign.loc[:,'DISC'] = df_data.DISC\n\tdf_assign.loc[:,'IdNum'] = df_data.loc[:,'rank']\n\n\tif args.subdata is None:\n\t\tdatafile_name = os.path.splitext(os.path.basename(args.data_path))[0]\n\telse:\n\t\tdf_subdata = pd.read_csv(args.subdata, encoding='utf-8', sep=args.sep)\n\t\tdf_assign = pd.merge(df_subdata, df_assign, how='left', on='IdNum')\n\t\tdf_assign = df_assign.drop(columns='customer_id').drop_duplicates()\n\t\tdatafile_name = os.path.splitext(os.path.basename(args.subdata))[0]\n\n\tresult_dir = os.path.dirname(args.assignment_path)\n\tclassification_filename = datafile_name+'_posterior-classification.tsv'\n\tdf_assign.to_csv(os.path.join(result_dir, classification_filename), index=False, encoding = 'utf-8', sep='\\t')\n","sub_path":"code/analysis/English/posterior_predict_classification_CELEX_from_IdNum.py","file_name":"posterior_predict_classification_CELEX_from_IdNum.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"635872174","text":"\"\"\"Contains neural network training sets.\n\"\"\"\n\nimport sys\n\ndef sample(data):\n\treturn getattr(sys.modules[__name__], '{}_sample'.format(data))\n\ndef weights(data):\n\treturn getattr(sys.modules[__name__], '{}_WEIGHTS'.format(data.upper()))\n\ndef xor_sample():\t\n\tyield [0, 0], [0]\n\tyield [0, 1], [1]\n\tyield [1, 0], [1]\n\tyield [1, 1], [0]\n\nXOR_WEIGHTS = (2, 2, 1), \"\"\"1 -1\n\t\t-1 1\n\n\t\t1\n\t\t1\n\t\t\"\"\"\n\ndef and_sample():\n\tyield [0, 0], [0]\n\tyield [0, 1], [0]\n\tyield [1, 0], [0]\n\tyield [1, 1], [1]\n\ndef or_sample():\n\tyield [0, 0], [0]\n\tyield [0, 1], [1]\n\tyield [1, 0], [1]\n\tyield [1, 1], [1]\n","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"123346556","text":"#Nathan Jones\n#GRAND CENTRAL v3 - TGG TEACH EDITION\n#2018\n\nfrom datetime import datetime\n\nimport time\nimport sys\nimport os.path\nimport os\nimport string \nimport random\nimport statistics\nimport itertools\nimport datetime\n\ndef SCROLL():\n\n Scroll=\"\\n\"*70\n print(Scroll)\n\ndef SCROLL2():\n\n Scroll2=\"\\n\"*10\n print(Scroll2)\n\ndef SCROLL3():\n\n Scroll3=\"\\n\"*28\n print(Scroll3) \n\ndef TEST_GRADE_GEN():\n\n print(\"\"\"\n████████╗███████╗███████╗████████╗ \n╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝ \n ██║ █████╗ ███████╗ ██║ \n ██║ ██╔══╝ ╚════██║ ██║ \n ██║ ███████╗███████║ ██║ \n ╚═╝ ╚══════╝╚══════╝ ╚═╝ \n \n ██████╗ ██████╗ █████╗ ██████╗ ███████╗ \n██╔════╝ ██╔══██╗██╔══██╗██╔══██╗██╔════╝ \n██║ ███╗██████╔╝███████║██║ ██║█████╗ \n██║ ██║██╔══██╗██╔══██║██║ ██║██╔══╝ \n╚██████╔╝██║ ██║██║ ██║██████╔╝███████╗ \n ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚══════╝ \n \n ██████╗ ███████╗███╗ ██╗███████╗██████╗ █████╗ ████████╗ ██████╗ ██████╗ \n██╔════╝ ██╔════╝████╗ ██║██╔════╝██╔══██╗██╔══██╗╚══██╔══╝██╔═══██╗██╔══██╗\n██║ ███╗█████╗ ██╔██╗ ██║█████╗ ██████╔╝███████║ ██║ ██║ ██║██████╔╝\n██║ ██║██╔══╝ ██║╚██╗██║██╔══╝ ██╔══██╗██╔══██║ ██║ ██║ ██║██╔══██╗\n╚██████╔╝███████╗██║ ╚████║███████╗██║ ██║██║ ██║ ██║ ╚██████╔╝██║ ██║\n ╚═════╝ ╚══════╝╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝\n\"\"\")\n SCROLL2()\n GRADE_GEN()\n\ndef GRADE_GEN():\n\n RES=[]\n\n print((\"SYSTEM TIME: \")+str(datetime.datetime.now()))\n print(\" \")\n F_NAME=input(\"ENTER FIRST NAME: \")\n L_NAME=input(\"ENTER LAST NAME: \")\n AGE=input(\"ENTER AGE: \")\n FORM=input(\"ENTER FORM: \")\n print(\" \")\n\n x = 0\n print(\" \")\n while (x == 0):\n DATA=input(\"TEST SCORE: \")\n RES.append(int(DATA))\n LOOP=input(\"Do You Have Another? Y/N \")\n if LOOP ==\"n\".upper():\n print(RES)\n x = x+1\n elif LOOP ==\"y\".upper():\n print(RES)\n x = 0\n\n print(\" \")\n statistics.stdev(RES)\n print((\"Standard Deviation: \")+str(statistics.stdev(RES)))\n statistics.mean(RES)\n print((\"Mean of Results: \")+str(statistics.mean(RES)))\n \n\n if statistics.mean(RES) <= 25:\n GRADE=(\"D\")\n \n elif statistics.mean(RES) <= 50:\n GRADE=(\"C\")\n\n elif statistics.mean(RES) <= 60:\n GRADE=(\"B\")\n \n elif statistics.mean(RES) >= 80:\n GRADE=(\"A\")\n \n print(\" \")\n print(\"SAVING...\")\n r=open(\"TEST SCORE FOR \"+str(L_NAME),\"w\")\n r.write((\"FIRST NAME: \")+F_NAME+(\"\\n\"))\n r.write((\"LAST NAME: \")+L_NAME+(\"\\n\"))\n r.write((\"AGE: \")+AGE+(\"\\n\"))\n r.write((\"FORM: \")+FORM+(\"\\n\"))\n r.write((\"GRADE: \")+GRADE+(\"\\n\"))\n r.close()\n print(\"SAVE COMPLETE!\")\n NEXT_STAGE()\n\ndef NEXT_STAGE():\n\n print(\" \")\n print((\"SYSTEM TIME: \")+str(datetime.datetime.now()))\n print(\" \")\n answer = input(\"Would You Like To Enter Another Person? Y/N \")\n if answer == \"Y\":\n SCROLL()\n print(\"LOADING...\")\n print(\" \")\n GRADE_GEN()\n print(\" \")\n \n\n if answer == \"N\":\n SCROLL()\n print(\"GOODBYE!...\")\n print(\" \")\n SCROLL()\n print(\"LOADING...\")\n time.sleep(5)\n os.startfile(\"C:\\\\Users\\\\natda\\\\OneDrive\\\\Sixth Form\\\\Computer Science\\\\CODE\\GRAND CENTRAL v3\\\\GRAND_CENTRAL_v3-TEACH\\\\TK_TEACH_v3.py\")\n sys.exit()\n\n else:\n SCROLL()\n NEXT_STAGE()\n\nTEST_GRADE_GEN()\n","sub_path":"GRAND_CENTRAL_v3-TEACH/TGG-t.py","file_name":"TGG-t.py","file_ext":"py","file_size_in_byte":5772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"358435526","text":"# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n File Name: vis_callback on CPLID_Detect\n Description :\n Author : Wayne\n Date: 2018/5/21\n Create by : PyCharm\n Check status: https://waynehfut.github.io\n-------------------------------------------------\n\"\"\"\n__author__ = 'Wayne'\nimport pylab as pl\nfrom IPython import display\nfrom keras.callbacks import Callback\n\n\nclass DrawCallback(Callback):\n def __init__(self, runtime_plot=True):\n super().__init__()\n self.init_loss = None\n self.runtime_plot = runtime_plot\n\n self.xdata = []\n self.ydata = []\n\n def _plot(self, epoch=None):\n epochs = self.params.get(\"epochs\")\n pl.ylim(0, int(self.init_loss * 2))\n pl.xlim(0, epochs)\n\n pl.plot(self.xdata, self.ydata)\n pl.xlabel('Epoch {}/{}'.format(epoch or epochs, epochs))\n pl.ylabel('Loss {:.4f}'.format(self.ydata[-1]))\n\n def _runtime_plot(self, epoch):\n self._plot(epoch)\n\n display.clear_output(wait=True)\n display.display(pl.gcf())\n pl.gcf().clear()\n\n def plot(self):\n self._plot()\n pl.show()\n\n def on_epoch_end(self, epoch, logs=None):\n logs = logs or {}\n loss = logs.get(\"loss\")\n if self.init_loss is None:\n self.init_loss = loss\n self.xdata.append(epoch)\n self.ydata.append(loss)\n if self.runtime_plot:\n self._runtime_plot(epoch)\n","sub_path":"VisCallback.py","file_name":"VisCallback.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"311466962","text":"#!/usr/bin/env python\nimport os\nimport argparse\nimport random\nfrom math import *\nimport numpy as np\n# add path\nimport sys\n\ncwd = os.getcwd()\nsys.path.append(cwd)\n\nfrom scene_elements import *\n\n## Define mass\nLarge = 1000000000.0\nSmall = 1.0\n\n## Add arguments\nparser = argparse.ArgumentParser(description='Create my scene')\nparser.add_argument(\"-f\", \"--filename\", type=str, help=\"define the name of output file\")\n\ndef main():\n \n args = parser.parse_args()\n filename = args.filename\n \n ## initial setup\n duration=20.0; integrator=\"forward-backward-euler\"; dt=0.005; bg_color=[0.0, 0.0, 0.1]\n init = []\n init.append(\"\")\n init.append(\"\")\n init.append(\"\".format(duration))\n init.append(\"\".format(integrator, dt))\n init.append(\"\")\n ## define background color.\n r, g, b = bg_color\n init.append(\"\".format(r, g, b))\n ## define viewpoint\n init.append(\"\")\n ## define collision type\n init.append(\"\")\n #init.append(\"\")\n init.append(\"\")\n \n scene = init\n #############################################################\n # Add content here #\n ############################################################# \n # load pixel files\n # pixel = np.load(\"dispicableme.npy\")\n \n # pixel = pixel[:,10:34,:]\n \n # add half plane\n #scene += add_halfplane([0,0], [1,0])\n #scene += add_halfplane([50,0], [-1,0])\n #scene += add_halfplane([0,50], [0,-1])\n #scene += add_halfplane([0,0], [0,1])\n \n base_id = 2*0\n # Part 2: starry night\n # add static large particles\n num_large = 6\n p_r = 0.2\n radius = 0.5\n delta_ang = 2*pi/num_large\n offset_ang = 1.0*pi/num_large\n # add particles\n for i in range(num_large):\n m = Large\n x, y = radius*cos(delta_ang*i+offset_ang), radius*sin(delta_ang*i+offset_ang)\n vx, vy = 0.0, 0.0##v_init*y/radius, -v_init*x/radius\n duration = None\n scene += add_particle(i+base_id, m, x, y, vx, vy, 0, p_r, bg_color, duration)\n \n # add random distributed small particles\n num_small = 1500\n num_flow = 6\n delta_ang = 2*pi/num_flow\n offset_ang = 0.0*pi/num_flow\n radius = [2, 3, 4]\n p_r = 0.2\n num_color = 7\n colors = [(0.4, 0.6, 0.6), (0.6, 0.4, 0.4), (0.8, 0.2, 0.2), (0.5, 0.5, 0.5), (0.3, 0.7, 0.7)]\n for i in range(num_small):\n m = Small\n r = random.uniform(1.0,2)#radius[rand_idx]\n px, py = r*cos(delta_ang*i+offset_ang), r*sin(delta_ang*i+offset_ang)\n vx, vy = 0.0, 0.0\n # other info\n fixed = 0\n cr = float(i%num_color)/num_color\n color = [0.8*cr, cr, 1-cr]\n duration = None\n scene += add_particle(i+num_large+base_id, m, px, py, vx, vy, fixed, p_r, color, duration)\n \n # add vortex force\n kbs = 6\n kvc = 10.0\n for i in range(num_large):\n for j in range(num_large, num_small+num_large):\n scene += add_vortexforce(i+base_id, j+base_id, kbs, kvc)\n \n # add particles\n \n base_id = num_small + num_large\n num_row = 100\n num_col = 100\n idx = 0\n for i in range(num_row):\n for j in range(num_col):\n px = i - 50\n py = j - 50\n m = 1\n duration = None\n cr = 1-0.8*random.random()#float(i%num_color)/num_color\n color = [0.8*cr, cr, 1-cr]\n if (px < -1 or px > 1) and (py<-1 or py>1):\n scene += add_particle(idx+base_id, m, px, py, 0.0, 0.0, 0, 0.25, color, duration)\n idx += 1\n \n \n # add gravity\n # add_gravity(i, j, G)\n #G = 10.118419\n #for i in range(num_particle):\n # scene += add_gravity(i+base, base+num_particle, G)\n \n # add simple gravity\n # scene += add_simplegravity(0.0, -1.0)\n #############################################################\n # End of content #\n ############################################################# \n \n # add end mark into scene\n scene += end_scene()\n \n # write scene into .xml file\n with open(os.path.join(\"../../scenes/\", filename), \"w\") as output:\n for line in scene:\n output.write(line)\n output.write(\"\\n\")\n # END OF CODE\n\n \nif __name__ == \"__main__\":\n main()","sub_path":"src/scenemake/week6_vortex.py","file_name":"week6_vortex.py","file_ext":"py","file_size_in_byte":4683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"150553196","text":"# Copyright (c) 2011-2013, The Tor Project\n# See LICENSE for the license.\n\n# Updated on 25.01.14-28.01.14 to add SOCKS 5 support.\n# Cleaned some parts of the code and abstracted quite a bit to handle the most important SOCKS5\n# functionality like\n# - username/password authentication\n# - gssapi authentication (planned)\n# - CONNECT command (the normal case, there are others: UDP ASSOCIATE and BIND, but they aren't as important. Maybe I will add them\n# in the future. If anyone wants to implement them, the basic structure is already here and the SOCKSv5ClientProtocol should be\n# rather easy extensible (how the actual connection, listening for incoming connections (BIND) and opening a UDP connection (UDP ASSOCIATE)\n# is done in the twisted world, is another question.\n# Added:\n# - SOCKSv4ClientFactory was renamed to SOCKSClientFactory and abstracted to handle all SOCKS 4/4a SOCKS5 (It is still ONE protocol, so one Factory should be logical correct)\n# - added SOCKS5ClientFactory\n# - SOCKSClientProtocol is the base class for all three protocols\n# - SOCKSv4aClientProtocol inherits from SOCKSv4ClientProtocol. I made the deliberate choice to differ between SOCKS 4 and 4a, altough 4a has the exactly same functionality as 4,\n# it might be the case that servers only speak version 4.\n# References:\n# A actively maintained, most recent version of PySocks from https://github.com/Anorov/PySocks\n# The original version of socksclient.py:\n\n# Author: Nikolai Tschacher\n# Contact: incolumitas.com\n\nimport inspect\nimport socket\nimport re\nimport struct\nfrom zope.interface import implements\nfrom twisted.internet import defer\nfrom twisted.internet.interfaces import IStreamClientEndpoint, IReactorTime\nfrom twisted.internet.protocol import Protocol, ClientFactory\nfrom twisted.internet.endpoints import _WrappingFactory\n\nclass SOCKSError(Exception):\n def __init__(self, val):\n self.val = val\n def __str__(self):\n return repr(self.val)\n\nclass SOCKSClientProtocol(Protocol):\n '''\n Base class for SOCKS protocols 4, 4a and 5\n '''\n buf = ''\n\n def noteTime(self, event):\n if self._timer:\n self._timestamps[event] = self._timer.seconds()\n\n def abort(self, errmsg):\n self.transport.loseConnection()\n self.handshakeDone.errback(SOCKSError('SOCKS %s: %s' % (self.proxy_config['version'], errmsg)))\n\n def isHostname(self, string):\n dns_label_regex = re.compile(r'^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{,63}(?H\", port)\n self.transport.write(msg)\n self.noteTime('RELAY_REQUEST_SENT')\n self.protocol_state = 'connection_requested'\n\n def verifySocksReply(self, data):\n where = 'SOCKS5 verifySocksReply'\n\n if len(data) < 10: # all hostname are longer than a IPv4 address\n self.abort('Too few data from server %s.' % where)\n else:\n version, reply, rsv, address_type = struct.unpack('!BBBB', data[:4])\n\n if version != 0x5:\n self.abort('Invalid version')\n return False\n\n if reply != 0x0:\n self.abort('Server reply indicates failure. Reason: %s' % self.SOCKS5_ERRORS.get(reply, \"Unknown error\"))\n return False\n\n if address_type == 0x1: # handle IPv4 address\n self.bound_address, self.bound_port = socket.inet_ntoa(data[4:8]),\\\n struct.unpack('>H', data[8:10])[0]\n elif address_type == 0x3: # handle domain name\n dns_name_len = ord(data[4:5])\n self.bound_address, self.bound_port = data[5:dns_name_len],\\\n struct.unpack('>H', data[(5+dns_name_len):(5+dns_name_len+2)])[0]\n elif address_type == 0x4: # handle Ipv6 address\n self.bound_address, self.bound_port = socket.inet_ntop(socket.AF_INET6, data[4:20]),\\\n struct.unpack('>H', data[20:22])[0]\n\n self.protocol_state = 'connection_verified'\n return True\n\n def connectionMade(self):\n self.noteTime('CONNECTED')\n self.noteTime('NEGOTIATE_AUTH_METHOD')\n self.negotiateAuthenticationMethod()\n\n def dataReceived(self, data):\n self.buf += data\n\n if self.protocol_state == 'do_auth':\n self.authenticate(data)\n elif self.protocol_state == 'check_auth':\n self.checkAuth(data)\n\n if self.protocol_state == 'authenticated':\n host = self.postHandshakeEndpoint._host\n port = self.postHandshakeEndpoint._port\n self.sendRelayRequest(host, port)\n elif self.protocol_state == 'connection_requested':\n if self.verifySocksReply(data):\n self.setupRelay()\n\n\nclass SOCKSv4ClientProtocol(SOCKSClientProtocol):\n SOCKS4_ERRORS = {\n 0x5B: \"Request rejected or failed\",\n 0x5C: \"Request rejected because SOCKS server cannot connect to identd on the client\",\n 0x5D: \"Request rejected because the client program and identd report different user-ids\"\n }\n def sendRelayRequest(self, host, port):\n username = self.proxy_config['version_specific']['username']\n ver, cmd, username = 0x4, 0x1, [b'\\x00', username.encode()+b'\\x00'][not not username]\n try:\n addr = socket.inet_aton(host)\n except socket.error:\n self.abort('Not a valid IPv4 address.')\n return False\n msg = struct.pack('!BBH', ver, cmd, port) + addr + username\n self.transport.write(msg)\n self.noteTime('REQUEST')\n\n def verifySocksReply(self, data):\n \"\"\"\n Return True on success and False on need-more-data or error.\n In the case of an error, the connection is closed and the\n handshakeDone errback is invoked with a SOCKSError exception\n before False is returned.\n \"\"\"\n if len(data) < 8:\n return False\n if ord(data[0]) != 0x0:\n self.abort('Expected 0 bytes')\n return False\n status = ord(data[1])\n if status != 0x5a:\n self.abort('Relay request failed. Reason=%s.' % self.SOCKS4_ERRORS.get(data[0], 'Unknown error'))\n return False\n return True\n\n def connectionMade(self):\n self.noteTime('CONNECT')\n self.noteTime('NEGOTIATE')\n self.sendRelayRequest(self.postHandshakeEndpoint._host, self.postHandshakeEndpoint._port)\n\n def dataReceived(self, data):\n self.buf += data\n if self.verifySocksReply(data):\n self.setupRelay()\n\nclass SOCKSv4aClientProtocol(SOCKSv4ClientProtocol):\n '''Only extends SOCKS 4 to remotely resolve hostnames.'''\n\n def sendRelayRequest(self, host, port):\n username = self.proxy_config['version_specific']['username']\n ver, cmd, username = 0x4, 0x1, [b'\\x00', username.encode()+b'\\x00'][not not username]\n try:\n addr = socket.inet_aton(host)\n except socket.error:\n addr = '\\x00\\x00\\x00\\x01'\n dnsname = '%s\\x00' % host\n msg = struct.pack('!BBH', ver, cmd, port) + addr + username + dnsname\n else:\n msg = struct.pack('!BBH', ver, cmd, port) + addr + username\n self.transport.write(msg)\n self.noteTime('REQUEST')\n\nclass SOCKSClientFactory(ClientFactory):\n\n def __init__(self, proxy_config):\n self.proxy_config = proxy_config\n if self.proxy_config['version'] == '4':\n self.protocol = SOCKSv4ClientProtocol\n elif self.proxy_config['version'] == '4a':\n self.protocol = SOCKSv4aClientProtocol\n elif self.proxy_config['version'] == '5':\n self.protocol = SOCKSv5ClientProtocol\n\n def buildProtocol(self, addr):\n r = ClientFactory.buildProtocol(self, addr)\n r.proxy_config = self.proxy_config\n r.postHandshakeEndpoint = self.postHandshakeEndpoint\n r.postHandshakeFactory = self.postHandshakeFactory\n r.handshakeDone = self.handshakeDone\n r._timestamps = self._timestamps\n r._timer = self._timer\n return r\n\nclass SOCKSWrapper(object):\n '''\n Generic class to wrap all 3 SOCKS protocol versions 4, 4a, 5 around a TCP connection\n '''\n implements(IStreamClientEndpoint)\n\n factory = SOCKSClientFactory\n\n def __init__(self, reactor, endpoint, proxy_config, timestamps=None):\n self._host = proxy_config['host']\n self._port = proxy_config['port']\n self._proxy_config = proxy_config\n\n self._reactor = reactor\n self._endpoint = endpoint\n self._timestamps = None\n self._timer = None\n if timestamps is not None:\n self._timestamps = timestamps\n self._timer = IReactorTime(reactor)\n\n def noteTime(self, event):\n if self._timer:\n self._timestamps[event] = self._timer.seconds()\n\n def connect(self, protocolFactory):\n \"\"\"\n Return a deferred firing when the SOCKS connection is established.\n \"\"\"\n\n def createWrappingFactory(f):\n \"\"\"\n Wrap creation of _WrappingFactory since __init__() doesn't\n take a canceller as of Twisted 12.1 or something.\n \"\"\"\n if len(inspect.getargspec(_WrappingFactory.__init__)[0]) == 3:\n def _canceller(deferred):\n connector.stopConnecting()\n deferred.errback(\n error.ConnectingCancelledError(\n connector.getDestination()))\n return _WrappingFactory(f, _canceller)\n else: # Twisted >= 12.1.\n return _WrappingFactory(f)\n\n self.noteTime('START')\n try:\n # Connect with an intermediate SOCKS factory/protocol,\n # which then hands control to the provided protocolFactory\n # once a SOCKS connection has been established.\n f = self.factory(self._proxy_config)\n\n f.postHandshakeEndpoint = self._endpoint\n f.postHandshakeFactory = protocolFactory\n f.handshakeDone = defer.Deferred()\n f._timestamps = self._timestamps\n f._timer = self._timer\n wf = createWrappingFactory(f)\n self._reactor.connectTCP(self._host, self._port, wf)\n self.noteTime('SOCKET')\n return f.handshakeDone\n except:\n return defer.fail()\n","sub_path":"socksclient.py","file_name":"socksclient.py","file_ext":"py","file_size_in_byte":16432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"356831092","text":"# coding: utf-8\n\n\"\"\"\nLicensed to Cloudera, Inc. under one\nor more contributor license agreements. See the NOTICE file\ndistributed with this work for additional information\nregarding copyright ownership. Cloudera, Inc. licenses this file\nto you under the Apache License, Version 2.0 (the\n\"License\"); you may not use this file except in compliance\nwith the License. You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass Cluster(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'name': 'str',\n 'instances': 'list[Instance]',\n 'services': 'list[Service]',\n 'url': 'str',\n 'instances_url': 'str',\n 'health': 'Health',\n 'feature_availability': 'dict(str, str)'\n }\n\n attribute_map = {\n 'name': 'name',\n 'instances': 'instances',\n 'services': 'services',\n 'url': 'url',\n 'instances_url': 'instancesUrl',\n 'health': 'health',\n 'feature_availability': 'featureAvailability'\n }\n\n def __init__(self, name=None, instances=None, services=None, url=None, instances_url=None, health=None, feature_availability=None): # noqa: E501\n \"\"\"Cluster - a model defined in Swagger\"\"\" # noqa: E501\n\n self._name = None\n self._instances = None\n self._services = None\n self._url = None\n self._instances_url = None\n self._health = None\n self._feature_availability = None\n self.discriminator = None\n\n self.name = name\n if instances is not None:\n self.instances = instances\n if services is not None:\n self.services = services\n if url is not None:\n self.url = url\n if instances_url is not None:\n self.instances_url = instances_url\n if health is not None:\n self.health = health\n if feature_availability is not None:\n self.feature_availability = feature_availability\n\n @property\n def name(self):\n \"\"\"Gets the name of this Cluster. # noqa: E501\n\n Cluster name # noqa: E501\n\n :return: The name of this Cluster. # noqa: E501\n :rtype: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name):\n \"\"\"Sets the name of this Cluster.\n\n Cluster name # noqa: E501\n\n :param name: The name of this Cluster. # noqa: E501\n :type: str\n \"\"\"\n if name is None:\n raise ValueError(\"Invalid value for `name`, must not be `None`\") # noqa: E501\n\n self._name = name\n\n @property\n def instances(self):\n \"\"\"Gets the instances of this Cluster. # noqa: E501\n\n Instances comprising this cluster # noqa: E501\n\n :return: The instances of this Cluster. # noqa: E501\n :rtype: list[Instance]\n \"\"\"\n return self._instances\n\n @instances.setter\n def instances(self, instances):\n \"\"\"Sets the instances of this Cluster.\n\n Instances comprising this cluster # noqa: E501\n\n :param instances: The instances of this Cluster. # noqa: E501\n :type: list[Instance]\n \"\"\"\n\n self._instances = instances\n\n @property\n def services(self):\n \"\"\"Gets the services of this Cluster. # noqa: E501\n\n Services that belong to this cluster # noqa: E501\n\n :return: The services of this Cluster. # noqa: E501\n :rtype: list[Service]\n \"\"\"\n return self._services\n\n @services.setter\n def services(self, services):\n \"\"\"Sets the services of this Cluster.\n\n Services that belong to this cluster # noqa: E501\n\n :param services: The services of this Cluster. # noqa: E501\n :type: list[Service]\n \"\"\"\n\n self._services = services\n\n @property\n def url(self):\n \"\"\"Gets the url of this Cluster. # noqa: E501\n\n Optional URL for cluster in Cloudera Manager # noqa: E501\n\n :return: The url of this Cluster. # noqa: E501\n :rtype: str\n \"\"\"\n return self._url\n\n @url.setter\n def url(self, url):\n \"\"\"Sets the url of this Cluster.\n\n Optional URL for cluster in Cloudera Manager # noqa: E501\n\n :param url: The url of this Cluster. # noqa: E501\n :type: str\n \"\"\"\n\n self._url = url\n\n @property\n def instances_url(self):\n \"\"\"Gets the instances_url of this Cluster. # noqa: E501\n\n Optional URL for cluster instances in Cloudera Manager # noqa: E501\n\n :return: The instances_url of this Cluster. # noqa: E501\n :rtype: str\n \"\"\"\n return self._instances_url\n\n @instances_url.setter\n def instances_url(self, instances_url):\n \"\"\"Sets the instances_url of this Cluster.\n\n Optional URL for cluster instances in Cloudera Manager # noqa: E501\n\n :param instances_url: The instances_url of this Cluster. # noqa: E501\n :type: str\n \"\"\"\n\n self._instances_url = instances_url\n\n @property\n def health(self):\n \"\"\"Gets the health of this Cluster. # noqa: E501\n\n Overall cluster health # noqa: E501\n\n :return: The health of this Cluster. # noqa: E501\n :rtype: Health\n \"\"\"\n return self._health\n\n @health.setter\n def health(self, health):\n \"\"\"Sets the health of this Cluster.\n\n Overall cluster health # noqa: E501\n\n :param health: The health of this Cluster. # noqa: E501\n :type: Health\n \"\"\"\n\n self._health = health\n\n @property\n def feature_availability(self):\n \"\"\"Gets the feature_availability of this Cluster. # noqa: E501\n\n Availability information for features # noqa: E501\n\n :return: The feature_availability of this Cluster. # noqa: E501\n :rtype: dict(str, str)\n \"\"\"\n return self._feature_availability\n\n @feature_availability.setter\n def feature_availability(self, feature_availability):\n \"\"\"Sets the feature_availability of this Cluster.\n\n Availability information for features # noqa: E501\n\n :param feature_availability: The feature_availability of this Cluster. # noqa: E501\n :type: dict(str, str)\n \"\"\"\n allowed_values = [\"UNKNOWN\", \"UNAVAILABLE\", \"AVAILABLE\"] # noqa: E501\n if not set(feature_availability.values()).issubset(set(allowed_values)):\n raise ValueError(\n \"Invalid values in `feature_availability` [{0}], must be a subset of [{1}]\" # noqa: E501\n .format(\", \".join(map(str, set(feature_availability.values()) - set(allowed_values))), # noqa: E501\n \", \".join(map(str, allowed_values)))\n )\n\n self._feature_availability = feature_availability\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, Cluster):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"python-client/cloudera/director/v9/models/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":8874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"288747842","text":"# Game class for the tic tac toe game\nclass Game(object):\n # when constructing a Game object there is an optional paramter for player_first\n # if player_first is 1, the player makes the first move, the player is \"X\"\n # if player_first is 0 (default), the computer makes the first move, the computer is \"X\"\n def __init__(self, player_first = 0):\n # the board 2-d list holds the game board\n self.board = [[\" \", \" \", \" \"],[\" \", \" \", \" \"],[\" \", \" \", \" \"]]\n # indicates if the marker to be used by the player and computer\n self.player_first = player_first\n # if move_count gets to 9 without a winner the game is a draw\n self.move_count = 0\n # set the marker for the player and computer accordingly\n if self.player_first:\n self.player_marker = \"X\"\n self.comp_marker = \"O\"\n else:\n self.player_marker = \"O\"\n self.comp_marker = \"X\"\n \n # when invoked AI_move claims the first available space for the computer\n # returns True to indicate game over\n # return False to indicate continue game\t\n def AI_move(self):\n for row in range(len(self.board)): \n for col in range(len(self.board[row])):\n if self.board[row][col] == \" \":\n return self.place_move(self.comp_marker, (row, col))\n # when invoked player_move claims the space indicated by coordinates\n # returns True to indicate game over\n # returns False to indicate continue game\n def player_move(self, coordinates):\n return self.place_move(self.player_marker, coordinates)\n \n # when invoked place_move changes the board to the indicated marker at the indicated coordinates\n # return True to indicate game over\n # return False to indicate continue game\n def place_move(self, marker, coordinates):\n self.board[coordinates[0]][coordinates[1]] = marker\n return self.check_board(coordinates)\n\n # when invoked print_board prints the information stored in board as a formated tic tac toe board\n def print_board(self):\n '''\n count = 0;\n for line in self.board:\n for pos in range(len(line)):\n print(line[pos], end='')\n if pos == 2:\n print()\n else:\n print(\"|\", end='')\n if count < 2:\n print(\"_|_|_\")\n else:\n print(\" | |\")\n count += 1\n '''\n print(self.board_to_str(), end='')\n\n # when invoked board_to_str converts the board into a string and returns the string object\n def board_to_str(self):\n ret_str = \"\"\n count = 0;\n for line in self.board:\n for pos in range(len(line)):\n ret_str += line[pos]\n if pos == 2:\n ret_str += \"\\n\"\n else:\n ret_str += \"|\"\n if count < 2:\n ret_str += \"_|_|_\\n\"\n else:\n ret_str += \" | | \\n\"\n count += 1\n return ret_str\n\n # when invoked check_coords checks to see if the coordinates are valid for the board\n # returns True if the coordinates are valid\n # returns False if the coordinates are not valid\n def check_coords(self, coordinates):\n return self.board[coordinates[0]][coordinates[1]] == \" \"\n\n # when invoked check_board checks the board to see if there is a winner or stalemate\n # checks possible states based on the most recent move\n # if there is a winner an appropriate message is printed\n # return 1 if there is a winner \n # return -1 if there is a stalemate\n # return 0 if there is not a winner\n def check_board(self, coordinates):\n # increment the move count\n self.move_count += 1\n # flag to indicate win condition\n win_flag = 0\n # check the row of the most recent move\n prev_pos = self.board[coordinates[0]][0]\n for i in range(len(self.board[coordinates[0]])-1):\n curr_pos = self.board[coordinates[0]][i+1]\n if curr_pos != prev_pos:\n win_flag = 0 \n break\n else:\n win_flag = 1\n prev_pos = curr_pos\n # check to see if the entire row matched\n if win_flag:\n # there was a winner\n self.print_winner(curr_pos)\n return 1\n\n # the row did not have a winner check the column \n prev_pos = self.board[0][coordinates[1]]\n for i in range(len(self.board[coordinates[1]])-1):\n curr_pos = self.board[i+1][coordinates[1]]\n if curr_pos != prev_pos:\n win_flag = 0\n break\n else:\n win_flag = 1\n prev_pos = curr_pos\n # check to seee if the entire column matched\n if win_flag:\n # there was a winner\n self.print_winner(curr_pos)\n return 1\n # the column did not have a winner check to see if the coordinates match a diagonal\n if coordinates == (0,0) or coordinates == (1,1) or coordinates == (2,2):\n # check to seee if the entire diagonal matched\n if self.board[0][0] == self.board[1][1] and self.board[1][1] == self.board[2][2]:\n # there was a winner\n self.print_winner(curr_pos)\n return 1\n elif coordinates == (2,0) or coordinates == (1,1) or coordinates == (0,2):\n # check to seee if the entire diagonal matched\n if self.board[2][0] == self.board[1][1] and self.board[1][1] == self.board[0][2]:\n # there was a winner\n self.print_winner(curr_pos)\n return 1 \n # there was not a winner check for a draw\n for row in self.board:\n for col in row:\n if col == \" \":\n # there is still a blank space \n return 0\n # a blank space was not found there was a draw\n print(\"Stalemate! It could have been worse!\")\n return -1\n \n \n def print_winner(self, marker):\n # check to see if the winning marker belongs to the computer or player\n if self.player_marker == marker:\n # the player won\n print(\"Congrats! You won!\")\n else:\n # the computer won\n print(\"You lost! Better luck next time!\")\n'''\n# main to test the class\ndef main():\n print(\"Lets play Tic Tac Toe!\")\n input_flag = 1\n while (input_flag):\n player_first = input(\"Would you like to go first? Y/n: \")\n if isinstance(player_first, str):\n player_first.upper()\n if player_first == \"Y\" or player_first == \"N\":\n input_flag = 0\n else:\n print(\"Please make a valid selection!\")\n else:\n print(\"Please make a valid selection!\")\n if player_first == \"Y\":\n game = Game(1)\n moves = 0\n else:\n game = Game()\n game.AI_move()\n moves = 1\n game_flag = 1\n while(game_flag):\n game.print_board()\n input_flag = 1\n while (input_flag):\n coor_raw = input(\"Enter the coordinates for your move seperated by a space (e.g. \\\"0 2\\\"): \")\n try:\n coordinates_raw = coor_raw.split()\n coordinates = (int(coordinates_raw[0]), int(coordinates_raw[1]))\n if coordinates[0] >= 0 and coordinates[0] <= 2 and coordinates[1] >= 0 and coordinates[1] <= 2:\n input_flag = 0\n else:\n # invalid input\n print(\"Please enter valid coordinates between 0 and 2!\")\n except TypeError: \n print(\"TypeError: Please enter valid coordinates between 0 and 2!\")\n if game.player_move(coordinates):\n game_flag = 0\n moves += 1\n if moves == 9:\n break\n if game.AI_move():\n game_flag = 0\n moves += 1\n if moves == 9:\n game_flag = 0\n game.print_board()\nmain() \n'''\n","sub_path":"TTT_Game.py","file_name":"TTT_Game.py","file_ext":"py","file_size_in_byte":8162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"186841835","text":"'''\nFibonaci\nDe rij van Fibonacci is genoemd naar Leonardo van Pisa, bijgenaamd Fibonacci, die de rij noemt in zijn boek Liber abaci uit 1202. De rij begint met 0 en 1 en vervolgens is elk\nvolgende element van de rij steeds de som van de twee voorgaande elementen. Bij de rij gebruiken we de notatie fn voor het aangeven van het n-de element van de rij. f9 is\nbijvoorbeeld gelijk aan 34. De eerste elementen van de rij zijn dan als volgt:\n0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584\nImplementeer een functie die fn uitrekent gegeven integer n. De functie moet recursief zijn.\n\nMeer oefenen met recursie: implementeer de eerdere sorteer-bereken-controleer opdrachten met recursieve functies.\n'''\n\ndef fibonaci(list, grote,grond):\n if len(list) < grote:\n list.append(list[grond] + list[grond + 1])\n grond += 1\n fibonaci(list, grote, grond)\n else:\n print(list)\n return\n return\n\nlist = [0,1]\nn = 15\ngrond = 0\nfibonaci(list, n,grond)\n\n'''\n#for functie voor fibonaci\nfor i in range(n):\n print(i)\n list.append(list[i]+list[i+1])\n print(list)\n '''","sub_path":"Opdracht 1/fibonaci.py","file_name":"fibonaci.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"491438889","text":"import os\nimport sys\nimport json\nimport pprint\nimport collections\nimport traceback\nimport datetime\nimport time\nimport uuid\nimport datetime\nimport copy\nimport logging\n\nimport zmq\nimport gpudb\n\nlogger = logging.getLogger(\"kml-bbox-sdk\")\nlogger.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandlerC = logging.StreamHandler(sys.stdout)\nhandlerC.setFormatter(formatter)\nlogger.addHandler(handlerC)\n\nclass KineticaBlackBox(object):\n \"\"\"Kinetica black box class.\"\"\"\n\n socket = None\n schema_inbound = None\n schema_outbound = None\n sink_table_audit = None\n sink_table_results = None\n be_quiet = False\n\n def __init__(self, bb_module, bb_method,\n schema_inbound, schema_outbound,\n zmq_dealer_host, zmq_dealer_port,\n db_table_audit, db_table_results, db_conn_str,\n db_user = \"\", db_pass = \"\", be_quiet = False ):\n \"\"\"Construct a new KineticaBlackBox object.\n\n :param bb_module:\n :type bb_module: dict\n :param bb_method:\n :type bb_method: dict\n :param schema_inbound:\n :type schema_inbound: str\n :param schema_outbound:\n :type schema_outbound: str\n :param zmq_dealer_host:\n :type zmq_dealer_host: str\n :param zmq_dealer_port:\n :type zmq_dealer_port: str\n :param db_table_audit:\n :type db_table_audit: str\n :param db_table_results:\n :type db_table_results: str\n :param db_host: Default \"127.0.0.1\".\n :type db_host: str\n :param db_port: Default \"9191\".\n :type db_port: str\n :param db_user: optional\n :type db_user: str\n :param db_pw: optional\n :type db_pw: str\n\n \"\"\"\n\n logger.info(\"Initializing KineticaBlackBox\")\n logger.info(f\"zmq_dealer_host: {zmq_dealer_host}\")\n logger.info(f\"zmq_dealer_port: {zmq_dealer_port}\")\n logger.info(f\"db_table a: {db_table_audit}\")\n logger.info(f\"db_table r: {db_table_results}\")\n logger.info(f\"db_conn_str: {db_conn_str}\")\n logger.info(f\"db_user: {db_user}\")\n logger.info(f\"db_pass: *******\")\n logger.info(f\"schema_inbound: {schema_inbound}\")\n logger.info(f\"schema_outbound: {schema_outbound}\")\n logger.info(f\"bb_module: {bb_module}\")\n logger.info(f\"bb_method: {bb_method}\")\n\n if be_quiet:\n import logging\n logger.setLevel(logging.INFO)\n\n self.be_quiet = be_quiet\n self.schema_inbound = schema_inbound\n self.schema_outbound = schema_outbound\n\n self.bb_module = bb_module\n self.bb_method = bb_method\n\n # Prepare DB Communications\n logger.info(f\"Attempting to connect to DB at {db_conn_str} to push to {db_table_audit}\")\n if db_user == 'no_cred' or db_pass == 'no_cred':\n db=gpudb.GPUdb(encoding='BINARY',\n host=db_conn_str)\n else:\n db=gpudb.GPUdb(encoding='BINARY',\n host=db_conn_str,\n username=db_user,\n password=db_pass)\n\n self.sink_table_audit = gpudb.GPUdbTable(name = db_table_audit, db = db)\n \n logger.info(f\"DB Results Table {db_table_results}\")\n if db_table_results == \"NOT_APPLICABLE\": \n logger.info(f\"All results will be persisted to Audit DB Table {db_table_audit}\")\n self.sink_table_results = None\n else:\n self.sink_table_results = gpudb.GPUdbTable(name = db_table_results, db = db)\n logger.info(f\"Established connection to sink table\")\n logger.info(self.sink_table_results)\n\n logger.info(self.sink_table_results)\n if self.sink_table_results is None:\n logger.info(f\"All results will be persisted to Audit DB Table only\") \n else:\n logger.info(f\"All results will be persisted to both Audit and output DB Tables {db_table_results}\")\n\n\n logger.info(\"Prepping response with with schema\")\n logger.info(json.dumps(json.loads(schema_outbound)))\n\n # Prepare ZMQ Communications\n zmq_dealer_uri = f\"tcp://{zmq_dealer_host}:{zmq_dealer_port}\"\n context = zmq.Context()\n self.socket = context.socket(zmq.PULL)\n #logger.info(\"Listening for incoming requests on topic: %s via %s\" % (topicfilter,topic_source))\n self.socket.connect(zmq_dealer_uri)\n #self.socket.setsockopt_string(zmq.SUBSCRIBE, topicfilter)\n # end __init__\n\n\n def run(self):\n \"\"\"Run the black box.\"\"\"\n\n schema_decoder = json.dumps(json.loads(self.schema_inbound))\n outfields = json.loads(self.schema_outbound)[\"fields\"]\n\n method_to_call = getattr(__import__(self.bb_module), self.bb_method)\n logger.info(f\"Dynamically loaded function {self.bb_method} from module {self.bb_module} for lambda application\")\n\n block_request_count = 0\n response_count=0\n while True:\n try:\n\n mpr = self.socket.recv_multipart()\n block_request_count += 1\n\n parts_received = len(mpr)\n logger.info(f\"Processing insert notification with {parts_received-1} frames, block request {block_request_count}\")\n \n audit_records_insert_queue=[]\n for mindex, m in enumerate(mpr[1:]): \n inference_inbound_payload=gpudb.GPUdbRecord.decode_binary_data(schema_decoder, m)[0]\n response_count += 1\n\n # wipe out all previous results\n results_package = collections.OrderedDict()\n if 'guid' not in inference_inbound_payload:\n inference_inbound_payload['guid'] = str(uuid.uuid4())\n inference_inbound_payload['receive_dt'] = datetime.datetime.now().replace(microsecond=100).isoformat(' ')[:-3]\n logger.debug(f\"Assigned GUID {inference_inbound_payload['guid']} to serial-free inbound\")\n #results_package[\"guid\"]=inference_inbound_payload['guid']\n #results_package[\"receive_dt\"]=inference_inbound_payload['receive_dt']\n logger.info(f\"Processing frame {1+mindex} of {parts_received}: Message count # {response_count} {inference_inbound_payload['guid']}\")\n\n results_package[\"success\"]=0 # we start with the assumption of failure\n for afield in outfields:\n results_package[afield[\"name\"]]=None\n # by default send back all inputs as well as our calculated outputs\n\n # TODO: Replace this with a deep copy: https://docs.python.org/2/library/copy.html\n for k,v in inference_inbound_payload.items():\n results_package[k]=v\n\n process_start_dt=datetime.datetime.now().replace(microsecond=100).isoformat(' ')[:-3]\n if not self.be_quiet:\n logger.debug(\"\\tDecoded task %s off wire for inference\" % inference_inbound_payload[\"guid\"])\n for k,v in inference_inbound_payload.items():\n logger.debug(\"\\t%s: %s\" % (k,v))\n\n # -------------------------------------------------------------------------\n # BLACKBOX INTERACTION - **STARTING**\n\n inMap = inference_inbound_payload\n #if not self.be_quiet:\n # logger.debug (\"\\tSending to blackbox:\")\n # for ki,vi in inMap.items():\n # logger.debug(\"\\t %s: %s\" % (ki,vi))\n\n inference_success=False\n results_package[\"success\"]=0\n results_package[\"process_start_dt\"]=process_start_dt\n\n try:\n outMaps = method_to_call(inMap)\n\n\n inference_success=True\n results_package[\"success\"]=1\n process_end_dt=datetime.datetime.now().replace(microsecond=100).isoformat(' ')[:-3]\n results_package[\"process_end_dt\"]=process_end_dt\n\n # this enables us to handle responses from blackbox functions\n # that may not return lists, but only single {} outs\n if not isinstance(outMaps, list):\n logger.info (\"Received lone dictionary function output, force listifying\")\n outMaps = [outMaps,]\n else:\n logger.info (f\"Received list of {len(outMaps)} dictionary outputs\")\n\n\n for outMap in outMaps:\n lineitem = copy.deepcopy(results_package)\n for k,v in outMap.items():\n lineitem[k]=v\n audit_records_insert_queue.append(lineitem)\n\n if not self.be_quiet:\n logger.debug (\"\\tResults received from blackbox:\")\n for ko,vo in outMap.items():\n logger.debug(\"\\t %s: %s\" % (ko,vo))\n logger.debug (\"\\t>> Completed\")\n\n except Exception as e:\n # TODO: As discussed at code review on 3 Jan 2019, push stack trace and input body to store_only field in output table\n logger.error(e)\n error_type, error, tb = sys.exc_info()\n logger.error(traceback.format_tb(tb))\n traceback.print_exc(file=sys.stdout)\n results_package[\"errorstack\"]=\"\\n\".join(traceback.format_tb(tb)) \n if e:\n results_package[\"errorlog\"]=str(e)\n audit_records_insert_queue.append(results_package)\n\n # -------------------------------------------------------------------------\n # BLACKBOX INTERACTION - **COMPLETED**\n\n logger.debug(\"Sending response back to DB:\")\n #logger.debug(results_package)\n #audit_records_insert_queue.append(results_package)\n\n _ = self.sink_table_audit.insert_records(audit_records_insert_queue)\n if self.sink_table_results is None:\n logger.info(f\"Response sent back to DB audit table\")\n else:\n _ = self.sink_table_results.insert_records(audit_records_insert_queue)\n logger.info(f\"Response sent back to DB output table and audit table\") \n\n # TODO: examine insert_status and determine if DB insert was a filure\n \n logger.info(f\"Completed Processing block request {block_request_count}\")\n\n except Exception as e:\n # TODO: As discussed at code review on 3 Jan 2019, push stack trace and input body to store_only field in output table\n logger.error(e)\n error_type, error, tb = sys.exc_info()\n logger.error(traceback.format_tb(tb))\n traceback.print_exc(file=sys.stdout)\n\n # end run\n\n# end class KineticaBlackBox\n\n","sub_path":"sdk/kinetica_black_box.py","file_name":"kinetica_black_box.py","file_ext":"py","file_size_in_byte":11529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"50610200","text":"'''\nThis file creates annual means of tau in wombat_jra-iaf_mom025 and concatenates the result in one file.\nTakes data from\n/g/data1a/v45/mtc599/mom5/dec16b/OUTPUTr0/\nand places the outputs in\n/g/data/e14/erd561/wombat_jra-iaf_mom025/\n\nEarl Duran \ncreated: 14-Mar-18\ne.duran@unsw.edu.au\n'''\n\nimport os\n\ninput_path = '/g/data1a/v45/mtc599/mom5/dec16b/OUTPUTr0/'\n\nfile_number = list(range(1958, 2015, 1))\n\noutput_path = '/g/data/e14/erd561/wombat_jra-iaf_mom025/'\n\npls = os.listdir(output_path)\n \nvar = ['u', 'v', 'temp', 'salt', 'eta_t', 'mld_rho']\nx_axis = ['xu_ocean', 'xu_ocean', 'xt_ocean', 'xt_ocean', 'xt_ocean', 'xt_ocean']\ny_axis = ['yu_ocean', 'yu_ocean', 'yt_ocean', 'yt_ocean', 'yt_ocean', 'yt_ocean']\n\nfor n in file_number:\n input_data_path = input_path\n if n in [1984,1985,1986]:\n input_data_path += 'ocean_surface_' + str(n) + '_01.nc ' + \\\n input_path + 'ocean_surface_' + str(n) + '_07.nc'\n else:\n input_data_path += 'ocean_surface_' + str(n) + '_01.nc'\n \n for v,x,y in zip(var,x_axis,y_axis):\n output_data = v + '_' + str(n) + '.nc'\n output_data_path = output_path + output_data\n\n if output_data not in pls:\n os.system('ncra -d ' + y + ',-60.0,-20.0 -d ' + x + ',-260.0,-190.0 -v ' \\\n + v + ' ' + input_data_path + ' ' + output_data_path)\n print(output_data_path + ' OK')\n\n\nfor v,x,y in zip(var,x_axis,y_axis):\n output_data = v + '_' + str(file_number[0]) + '-' + str(file_number[-1]) + '.nc'\n output_data_path = output_path + output_data\n \n if output_data not in pls:\n \n input_data_path = ''\n for n in file_number:\n input_data_path += output_path + v + '_' + str(n) + '.nc '\n \n \n os.system('ncrcat -v ' \\\n + v + ' ' + input_data_path + ' ' + output_data_path)\n print(output_data_path + ' OK')\n \nprint('DONE') \n \n \n \n ","sub_path":"old_stuff/ncra_ncrcat_ocean_surface.py","file_name":"ncra_ncrcat_ocean_surface.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"372511153","text":"from image_features.FeatureModel import *\nfrom skimage import feature\nimport cv2 as cv\nimport numpy as np\nimport task5 as lsh\nimport h5py\nimport os\n\nCURRENT_DIR = os.path.dirname(__file__)\n\nclass LBP(FeatureModel):\n # Initialize the input path\n def __init__(self, ds_folder_path='../Inputs', image_label=ImageLabel.UNSPECIFIED):\n FeatureModel.__init__(self, ds_folder_path, image_label)\n\n def extract_feature_vector(self, image_id):\n image_path = self.get_path_from_id(image_id)\n return self.image_lbp(image_path)\n\n def calculate_image_lbp(self, image, radius=3):\n num_points = 8 * radius\n cell_size = 100 * 100\n interval = 100\n rows = 1200\n columns = 1600\n n_bins = 20\n count = 0\n lbp_local_max = int(2 ** num_points)\n number_of_cell = int(rows * columns / (cell_size))\n number_of_features = int(number_of_cell * n_bins)\n lbp_img = np.zeros(number_of_features)\n for i in range(0, rows, interval):\n for j in range(0, columns, interval):\n lbp_local = feature.local_binary_pattern(image[i:i + 100, j:j + 100], num_points, radius)\n hist, _ = np.histogram(lbp_local, density=False, bins=n_bins, range=(0, lbp_local_max))\n norm_val = np.sqrt(np.sum(hist ** 2) * 1.0)\n if norm_val != 0:\n hist = hist / norm_val\n # Normalization done above\n lbp_img[count * n_bins: (count + 1) * n_bins] = hist\n count += 1\n return lbp_img\n\n def image_lbp(self, image_path):\n img = cv.imread(image_path, 0)\n return self.calculate_image_lbp(img, radius=2)\n\n def extract_feature_feature_vectors(self):\n feature_matrix = []\n input_images = self.get_data_set_files()\n\n # for i in input_images:\n # feature_matrix.append(self.extract_feature_vector(i.image_id))\n\n # extract from the existing features file\n lsh_index = lsh.LSHIndex()\n hdf5_file = CURRENT_DIR + os.sep + '..' + os.sep + '..' + os.sep + 'Metadata' + os.sep + 'feature_vectors_full_data.hdf5'\n data_lbp = None\n with h5py.File(hdf5_file, 'r') as hf:\n data_lbp = hf['lbp_features'][:]\n\n for i in input_images:\n img_idx = lsh_index.image_id_map[i.image_id]\n feature_vector = data_lbp[img_idx]\n feature_matrix.append(feature_vector)\n\n return feature_matrix\n\n def extract_feature_feature_vectors_list(self, input_images):\n feature_matrix = []\n for i in input_images:\n feature_matrix.append(self.extract_feature_vector(i.image_id))\n return feature_matrix\n\n def find_m_similar_images(self, reduced_data_matrix, reduced_query_img_vector, m, dimensionality_reduction_model):\n distances = []\n for i in range(len(reduced_data_matrix)):\n temp = (self._input_images_[i],\n self.euclidean_distance(list(reduced_data_matrix[i]), list(reduced_query_img_vector[0])))\n distances.append(temp)\n\n counter = 0\n sorted_similar_images = []\n for i in sorted(distances, key=lambda x: x[1]):\n if counter < m:\n # custom definition for similarity score\n # similarity score = (reciprocal of distance) times 1000\n # 0.000001 for LDA similarity score computation\n similarity_score = round((1 / i[1] + 0.000001) * 10, 3)\n # similarity_score = i[1]\n\n image_match = ImageMatch(i[0], similarity_score)\n sorted_similar_images.append(image_match)\n\n print(f'{counter + 1}. Image Id: {i[0].image_id} Similarity score: {similarity_score}')\n counter += 1\n\n return sorted_similar_images","sub_path":"Code/image_features/LBP.py","file_name":"LBP.py","file_ext":"py","file_size_in_byte":3847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"354330637","text":" # -*- coding: utf-8 -*-\n'''\nTest Vincent.charts\n-------------------\n\nTests for Vincent chart types, which also serve as reference grammar.\n\n'''\n\nimport pandas as pd\nimport nose.tools as nt\nfrom vincent.charts import (data_type, Chart, Bar, Scatter, Line, Area,\n StackedArea, StackedBar, GroupedBar)\n\n\ndef chart_runner(chart, scales, axes, marks):\n \"\"\"Iterate through each chart element for check for contents\"\"\"\n\n for i, scale in enumerate(scales):\n nt.assert_dict_equal(chart.scales[i].grammar(), scale)\n\n for i, axis in enumerate(axes):\n nt.assert_dict_equal(chart.axes[i].grammar(), axis)\n\n for i, axis in enumerate(marks):\n nt.assert_dict_equal(chart.marks[i].grammar(), axis)\n\n\ndef test_data_type():\n \"\"\"Test automatic data type importing\"\"\"\n\n puts1 = [10, 20, 30, 40, 50]\n puts2 = {'apples': 10, 'bananas': 20, 'oranges': 30}\n\n gets1 = [{'col': 'data', 'idx': 0, 'val': 10},\n {'col': 'data', 'idx': 1, 'val': 20},\n {'col': 'data', 'idx': 2, 'val': 30},\n {'col': 'data', 'idx': 3, 'val': 40},\n {'col': 'data', 'idx': 4, 'val': 50}]\n gets2 = [{'col': 'data', 'idx': 'apples', 'val': 10},\n {'col': 'data', 'idx': 'oranges', 'val': 30},\n {'col': 'data', 'idx': 'bananas', 'val': 20}]\n\n for ins, outs in zip([puts1, puts2], [gets1, gets2]):\n test = data_type(ins)\n nt.assert_list_equal(test.values, outs)\n\n #From Iters\n puts = {'x': [1, 2, 3], 'y': [10, 20, 30], 'z': [40, 50, 60]}\n gets = [{'col': 'y', 'idx': 1, 'val': 10},\n {'col': 'y', 'idx': 2, 'val': 20},\n {'col': 'y', 'idx': 3, 'val': 30},\n {'col': 'z', 'idx': 1, 'val': 40},\n {'col': 'z', 'idx': 2, 'val': 50},\n {'col': 'z', 'idx': 3, 'val': 60}]\n\n test = data_type(puts, iter_idx='x')\n nt.assert_list_equal(test.values, gets)\n\n #Pandas\n df = pd.DataFrame({'one': [1, 2, 3], 'two': [4, 5, 6]})\n series = pd.Series([1, 2, 3], name='test')\n gets1 = [{'col': 'one', 'idx': 0, 'val': 1},\n {'col': 'two', 'idx': 0, 'val': 4},\n {'col': 'one', 'idx': 1, 'val': 2},\n {'col': 'two', 'idx': 1, 'val': 5},\n {'col': 'one', 'idx': 2, 'val': 3},\n {'col': 'two', 'idx': 2, 'val': 6}]\n gets2 = [{'col': 'test', 'idx': 0, 'val': 1},\n {'col': 'test', 'idx': 1, 'val': 2},\n {'col': 'test', 'idx': 2, 'val': 3}]\n test_df = data_type(df)\n test_series = data_type(series)\n nt.assert_list_equal(test_df.values, gets1)\n nt.assert_list_equal(test_series.values, gets2)\n\n #Bad type\n class BadType(object):\n \"\"\"Bad data type\"\"\"\n pass\n\n test = BadType()\n nt.assert_raises(ValueError, data_type, test)\n\n\nclass TestChart(object):\n \"\"\"Test Chart ABC\"\"\"\n\n def test_init(self):\n chart = Chart([0, 1], width=100, height=100)\n nt.assert_equal(chart.width, 100)\n nt.assert_equal(chart.height, 100)\n padding = {'top': 10, 'left': 50, 'bottom': 50, 'right': 100}\n nt.assert_dict_equal(chart.padding, padding)\n\n #Data loading errors\n nt.assert_raises(ValueError, Chart)\n nt.assert_raises(ValueError, Chart, [])\n\n\nclass TestBar(object):\n \"\"\"Test Bar Chart\"\"\"\n\n def test_init(self):\n bar = Bar([1, 2, 3])\n\n scales = [{u'domain': {u'data': u'table', u'field': u'data.idx'},\n u'name': u'x',\n u'range': u'width',\n u'type': u'ordinal'},\n {u'domain': {u'data': u'table', u'field': u'data.val'},\n u'name': u'y',\n u'nice': True,\n u'range': u'height'}]\n\n axes = [{u'scale': u'x', u'type': u'x'},\n {u'scale': u'y', u'type': u'y'}]\n\n marks = [{u'from': {u'data': u'table'},\n u'properties': {u'enter': {u'width': {u'band': True,\n u'offset': -1,\n u'scale': u'x'},\n u'x': {u'field': u'data.idx', u'scale': u'x'},\n u'y': {u'field': u'data.val', u'scale': u'y'},\n u'y2': {u'scale': u'y', u'value': 0}},\n u'update': {u'fill': {u'value': u'steelblue'}}},\n u'type': u'rect'}]\n\n chart_runner(bar, scales, axes, marks)\n\n\nclass TestScatter(object):\n \"\"\"Test Scatter Chart\"\"\"\n\n def test_init(self):\n\n scatter = Scatter([1, 2, 3])\n\n scales = [{u'domain': {u'data': u'table', u'field': u'data.idx'},\n u'name': u'x',\n u'range': u'width',\n u'type': u'linear'},\n {u'domain': {u'data': u'table', u'field': u'data.val'},\n u'name': u'y',\n u'type': u'linear',\n u'range': u'height',\n u'nice': True},\n {u'domain': {u'data': u'table', u'field': u'data.col'},\n u'name': u'color',\n u'range': u'category20',\n u'type': u'ordinal'}]\n\n axes = [{u'scale': u'x', u'type': u'x'},\n {u'scale': u'y', u'type': u'y'}]\n\n marks = [{u'from': {u'data': u'table',\n u'transform': [{u'keys': [u'data.col'], u'type': u'facet'}]},\n u'marks':\n [{u'properties': {u'enter': {u'fill': {u'field': u'data.col',\n u'scale': u'color'},\n u'size': {u'value': 100},\n u'x': {u'field': u'data.idx', u'scale': u'x'},\n u'y': {u'field': u'data.val', u'scale': u'y'}}},\n u'type': u'symbol'}],\n u'type': u'group'}]\n\n chart_runner(scatter, scales, axes, marks)\n\n\nclass TestLine(object):\n \"\"\"Test Line Chart\"\"\"\n\n def test_init(self):\n line = Line([1, 2, 3])\n\n scales = [{u'domain': {u'data': u'table', u'field': u'data.idx'},\n u'name': u'x',\n u'range': u'width',\n u'type': u'linear'},\n {u'domain': {u'data': u'table', u'field': u'data.val'},\n u'name': u'y',\n u'type': u'linear',\n u'nice': True,\n u'range': u'height'},\n {u'domain': {u'data': u'table', u'field': u'data.col'},\n u'name': u'color',\n u'range': u'category20',\n u'type': u'ordinal'}]\n\n axes = [{u'scale': u'x', u'type': u'x'},\n {u'scale': u'y', u'type': u'y'}]\n\n marks = [{u'from': {u'data': u'table',\n u'transform': [{u'keys': [u'data.col'], u'type': u'facet'}]},\n u'marks':\n [{u'properties': {u'enter': {u'stroke': {u'field': u'data.col',\n u'scale': u'color'},\n u'strokeWidth': {u'value': 2},\n u'x': {u'field': u'data.idx', u'scale': u'x'},\n u'y': {u'field': u'data.val', u'scale': u'y'}}},\n u'type': u'line'}],\n u'type': u'group'}]\n\n chart_runner(line, scales, axes, marks)\n\n\nclass TestArea(object):\n \"\"\"Test Area Chart\"\"\"\n\n def test_init(self):\n area = Area([1, 2, 3])\n\n scales = [{u'domain': {u'data': u'table', u'field': u'data.idx'},\n u'name': u'x',\n u'range': u'width',\n u'type': u'linear'},\n {u'domain': {u'data': u'table', u'field': u'data.val'},\n u'name': u'y',\n u'nice': True,\n u'type': u'linear',\n u'range': u'height'},\n {u'domain': {u'data': u'table', u'field': u'data.col'},\n u'name': u'color',\n u'range': u'category20',\n u'type': u'ordinal'}]\n\n axes = [{u'scale': u'x', u'type': u'x'},\n {u'scale': u'y', u'type': u'y'}]\n\n marks = [{u'from': {u'data': u'table',\n u'transform': [{u'keys': [u'data.col'], u'type': u'facet'}]},\n u'marks':\n [{u'properties': {u'enter': {u'fill': {u'field': u'data.col',\n u'scale': u'color'},\n u'interpolate': {u'value': u'monotone'},\n u'x': {u'field': u'data.idx', u'scale': u'x'},\n u'y': {u'field': u'data.val', u'scale': u'y'},\n u'y2': {u'scale': u'y', u'value': 0}}},\n u'type': u'area'}],\n u'type': u'group'}]\n\n chart_runner(area, scales, axes, marks)\n\n\nclass TestStackedArea(object):\n \"\"\"Test Stacked Area Chart\"\"\"\n\n def test_init(self):\n\n stack = StackedArea({'x': [1, 2, 3], 'y': [4, 5, 6], 'z': [7, 8, 9]},\n iter_idx='x')\n\n scales = [{u'domain': {u'data': u'table', u'field': u'data.idx'},\n u'name': u'x',\n u'range': u'width',\n u'type': u'linear',\n u'zero': False},\n {u'domain': {u'data': u'stats', u'field': u'sum'},\n u'name': u'y',\n u'nice': True,\n u'range': u'height',\n u'type': u'linear'},\n {u'domain': {u'data': u'table', u'field': u'data.col'},\n u'name': u'color',\n u'range': u'category20',\n u'type': u'ordinal'}]\n\n axes = [{u'scale': u'x', u'type': u'x'},\n {u'scale': u'y', u'type': u'y'}]\n\n datas = [{u'name': u'table',\n u'values': [{u'col': u'y', u'idx': 1, u'val': 4},\n {u'col': u'y', u'idx': 2, u'val': 5},\n {u'col': u'y', u'idx': 3, u'val': 6},\n {u'col': u'z', u'idx': 1, u'val': 7},\n {u'col': u'z', u'idx': 2, u'val': 8},\n {u'col': u'z', u'idx': 3, u'val': 9}]},\n {u'name': u'stats',\n u'source': u'table',\n u'transform': [{u'keys': [u'data.idx'], u'type': u'facet'},\n {u'type': u'stats', u'value': u'data.val'}]}]\n\n marks = [{u'from': {u'data': u'table',\n u'transform': [{u'keys': [u'data.col'], u'type': u'facet'},\n {u'height': u'data.val', u'point': u'data.idx', u'type': u'stack'}]},\n u'marks':\n [{u'properties': {u'enter': {u'fill': {u'field': u'data.col',\n u'scale': u'color'},\n u'interpolate': {u'value': u'monotone'},\n u'x': {u'field': u'data.idx', u'scale': u'x'},\n u'y': {u'field': u'y', u'scale': u'y'},\n u'y2': {u'field': u'y2', u'scale': u'y'}}},\n u'type': u'area'}],\n u'type': u'group'}]\n\n chart_runner(stack, scales, axes, marks)\n\n for i, data in enumerate(datas):\n nt.assert_dict_equal(stack.data[i].grammar(), data)\n\n\nclass TestStackedBar(object):\n \"\"\"Test Stacked Bar Chart\"\"\"\n\n def test_init(self):\n\n stack = StackedBar({'x': [1, 2, 3], 'y': [4, 5, 6], 'z': [7, 8, 9]},\n iter_idx='x')\n\n scales = [{u'domain': {u'data': u'table', u'field': u'data.idx'},\n u'name': u'x',\n u'range': u'width',\n u'type': u'ordinal'},\n {u'domain': {u'data': u'stats', u'field': u'sum'},\n u'name': u'y',\n u'nice': True,\n u'range': u'height',\n u'type': u'linear'},\n {u'domain': {u'data': u'table', u'field': u'data.col'},\n u'name': u'color',\n u'range': u'category20',\n u'type': u'ordinal'}]\n\n axes = [{u'scale': u'x', u'type': u'x'},\n {u'scale': u'y', u'type': u'y'}]\n\n datas = [{u'name': u'table',\n u'values': [{u'col': u'y', u'idx': 1, u'val': 4},\n {u'col': u'y', u'idx': 2, u'val': 5},\n {u'col': u'y', u'idx': 3, u'val': 6},\n {u'col': u'z', u'idx': 1, u'val': 7},\n {u'col': u'z', u'idx': 2, u'val': 8},\n {u'col': u'z', u'idx': 3, u'val': 9}]},\n {u'name': u'stats',\n u'source': u'table',\n u'transform': [{u'keys': [u'data.idx'], u'type': u'facet'},\n {u'type': u'stats', u'value': u'data.val'}]}]\n\n marks = [{u'from': {u'data': u'table',\n u'transform': [{u'keys': [u'data.col'], u'type': u'facet'},\n {u'height': u'data.val', u'point': u'data.idx', u'type': u'stack'}]},\n u'marks':\n [{u'properties': {u'enter': {u'fill': {u'field': u'data.col',\n u'scale': u'color'},\n u'width': {u'band': True, u'offset': -1, u'scale': u'x'},\n u'x': {u'field': u'data.idx', u'scale': u'x'},\n u'y': {u'field': u'y', u'scale': u'y'},\n u'y2': {u'field': u'y2', u'scale': u'y'}}},\n u'type': u'rect'}],\n u'type': u'group'}]\n\n chart_runner(stack, scales, axes, marks)\n\n for i, data in enumerate(datas):\n nt.assert_dict_equal(stack.data[i].grammar(), data)\n\n\nclass TestGroupedBar(object):\n \"\"\"Test grouped bar chart\"\"\"\n\n def test_init(self):\n\n farm_1 = {'apples': 10, 'berries': 32, 'squash': 21}\n farm_2 = {'apples': 15, 'berries': 40, 'squash': 17}\n data = [farm_1, farm_2]\n index = ['Farm 1', 'Farm 2']\n df = pd.DataFrame(data, index=index)\n\n group = GroupedBar(df)\n\n scales = [{u'domain': {u'data': u'table', u'field': u'data.idx'},\n u'name': u'x',\n u'padding': 0.2,\n u'range': u'width',\n u'type': u'ordinal'},\n {u'domain': {u'data': u'table', u'field': u'data.val'},\n u'name': u'y',\n u'nice': True,\n u'range': u'height'},\n {u'domain': {u'data': u'table', u'field': u'data.col'},\n u'name': u'color',\n u'range': u'category20',\n u'type': u'ordinal'}]\n\n axes = [{u'scale': u'x', u'type': u'x'},\n {u'scale': u'y', u'type': u'y'}]\n\n datas = [{u'name': u'table',\n u'values':\n [{u'col': u'apples', u'group': 0, u'idx': u'Farm 1', u'val': 10},\n {u'col': u'berries', u'group': 1, u'idx': u'Farm 1', u'val': 32},\n {u'col': u'squash', u'group': 2, u'idx': u'Farm 1', u'val': 21},\n {u'col': u'apples', u'group': 0, u'idx': u'Farm 2', u'val': 15},\n {u'col': u'berries', u'group': 1, u'idx': u'Farm 2', u'val': 40},\n {u'col': u'squash', u'group': 2, u'idx': u'Farm 2', u'val': 17}]}]\n\n marks = [{u'from': {u'data': u'table',\n u'transform': [{u'keys': [u'data.idx'], u'type': u'facet'}]},\n u'marks': [{u'properties': {u'enter': {u'fill': {u'field': u'data.col',\n u'scale': u'color'},\n u'width': {u'band': True, u'offset': -1, u'scale': u'pos'},\n u'x': {u'field': u'data.group', u'scale': u'pos'},\n u'y': {u'field': u'data.val', u'scale': u'y'},\n u'y2': {u'scale': u'y', u'value': 0}}},\n u'type': u'rect'}],\n u'properties': {u'enter': {u'width': {u'band': True, u'scale': u'x'},\n u'x': {u'field': u'key', u'scale': u'x'}}},\n u'scales': [{u'domain': {u'field': u'data.group'},\n u'name': u'pos',\n u'range': u'width',\n u'type': u'ordinal'}],\n u'type': u'group'}]\n\n chart_runner(group, scales, axes, marks)\n\n for i, data in enumerate(datas):\n nt.assert_dict_equal(group.data[i].grammar(), data)\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"tests/test_charts.py","file_name":"test_charts.py","file_ext":"py","file_size_in_byte":16182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"450162284","text":"#####################################################################\n# This module list the drawings according to the inputed key word #\n# change the page nubmer of the drawing requested #\n# preview or edit the drawing #\n#####################################################################\n\nimport kcs_ui\nimport kcs_dex\nimport kcs_util\nimport kcs_draft\nimport KcsObjectCriteria\nfrom KcsObjectCriteria import ObjectCriteria\nfrom wxPython.wx import *\nfrom wxPython.grid import *\n\ndef create(parent):\n\treturn wxFramePreview(parent)\n\n[wxID_WXFRAMEPREVIEW, wxID_WXFRAMEPREVIEWBUTTONCHANGEPAGENO, \nwxID_WXFRAMEPREVIEWBUTTONCLEARLIST, wxID_WXFRAMEPREVIEWBUTTONDWGEDIT, \nwxID_WXFRAMEPREVIEWBUTTONDWGPREVIEW, wxID_WXFRAMEPREVIEWBUTTONEXIT, \nwxID_WXFRAMEPREVIEWBUTTONSAVEDWG, wxID_WXFRAMEPREVIEWBUTTONSEARCHBYBLOCK, \nwxID_WXFRAMEPREVIEWBUTTONSEARCHBYPIECE, wxID_WXFRAMEPREVIEWGAUGE, \nwxID_WXFRAMEPREVIEWLISTCTRLDWGLIST, wxID_WXFRAMEPREVIEWPANEL1, \nwxID_WXFRAMEPREVIEWRADIOBOXCHOOSEDWGTYPE, \nwxID_WXFRAMEPREVIEWSTATICBOXCHANGEPAGE, wxID_WXFRAMEPREVIEWSTATICTEXTKEYIN, \nwxID_WXFRAMEPREVIEWSTATICTEXTNEWPAGE, wxID_WXFRAMEPREVIEWSTATICTEXTSEPARATOR, \nwxID_WXFRAMEPREVIEWTEXTCTRLKEYIN, wxID_WXFRAMEPREVIEWTEXTCTRLNEWPAGE, \nwxID_WXFRAMEPREVIEWTEXTCTRLNEWTOTALPAGE, \nwxID_WXFRAMEPREVIEWTEXTCTRLPAGEPREVIEW, \n] = map(lambda _init_ctrls: wxNewId(), range(21))\n\nclass wxFramePreview(wxFrame):\n\tdef _init_coll_listCtrlDwgList_Columns(self, parent):\n\t\t# generated method, don't edit\n\n\t\tparent.InsertColumn(col=0, format=wxLIST_FORMAT_LEFT,\n\t\t\t heading='Dwg Name', width=-1)\n\t\tparent.InsertColumn(col=1, format=wxLIST_FORMAT_LEFT, heading='Page',\n\t\t\t width=-1)\n\n\tdef _init_ctrls(self, prnt):\n\t\t# generated method, don't edit\n\t\twxFrame.__init__(self, id=wxID_WXFRAMEPREVIEW, name='wxFramePreview',\n\t\t\t parent=prnt, pos=wxPoint(517, 298), size=wxSize(463, 601),\n\t\t\t style=wxDEFAULT_FRAME_STYLE, title='Preview')\n\t\tself.SetClientSize(wxSize(455, 574))\n\n\t\tself.panel1 = wxPanel(id=wxID_WXFRAMEPREVIEWPANEL1, name='panel1',\n\t\t\t parent=self, pos=wxPoint(0, 0), size=wxSize(455, 574),\n\t\t\t style=wxTAB_TRAVERSAL)\n\n\t\tself.radioBoxChooseDwgType = wxRadioBox(choices=['Assembly', 'Cutting',\n\t\t\t 'Nesting'], id=wxID_WXFRAMEPREVIEWRADIOBOXCHOOSEDWGTYPE,\n\t\t\t label='Choose Dwg Type', majorDimension=1,\n\t\t\t name='radioBoxChooseDwgType', parent=self.panel1, point=wxPoint(8,\n\t\t\t 8), size=wxDefaultSize, style=wxRA_SPECIFY_ROWS)\n\n\t\tself.buttonSearchByBlock = wxButton(id=wxID_WXFRAMEPREVIEWBUTTONSEARCHBYBLOCK,\n\t\t\t label='Search', name='buttonSearchByBlock', parent=self.panel1,\n\t\t\t pos=wxPoint(232, 56), size=wxSize(75, 23), style=0)\n\t\tEVT_BUTTON(self.buttonSearchByBlock,\n\t\t\t wxID_WXFRAMEPREVIEWBUTTONSEARCHBYBLOCK,\n\t\t\t self.OnButtonSearchByBlockButton)\n\n\t\tself.buttonSearchByPiece = wxButton(id=wxID_WXFRAMEPREVIEWBUTTONSEARCHBYPIECE,\n\t\t\t label='Search By', name='buttonSearchByPiece', parent=self.panel1,\n\t\t\t pos=wxPoint(328, 56), size=wxSize(75, 23), style=0)\n\t\tEVT_BUTTON(self.buttonSearchByPiece,\n\t\t\t wxID_WXFRAMEPREVIEWBUTTONSEARCHBYPIECE,\n\t\t\t self.OnButtonSearchByPieceButton)\n\n\t\tself.staticTextKeyIn = wxStaticText(id=wxID_WXFRAMEPREVIEWSTATICTEXTKEYIN,\n\t\t\t label='Key In', name='staticTextKeyIn', parent=self.panel1,\n\t\t\t pos=wxPoint(8, 64), size=wxSize(30, 13), style=0)\n\n\t\tself.textCtrlKeyIn = wxTextCtrl(id=wxID_WXFRAMEPREVIEWTEXTCTRLKEYIN,\n\t\t\t name='textCtrlKeyIn', parent=self.panel1, pos=wxPoint(56, 56),\n\t\t\t size=wxSize(160, 21), style=0, value='')\n\n\t\tself.listCtrlDwgList = wxListCtrl(id=wxID_WXFRAMEPREVIEWLISTCTRLDWGLIST,\n\t\t\t name='listCtrlDwgList', parent=self.panel1, pos=wxPoint(16, 96),\n\t\t\t size=wxSize(424, 248), style=wxLC_REPORT | wxLC_ICON)\n\t\tself._init_coll_listCtrlDwgList_Columns(self.listCtrlDwgList)\n\t\tEVT_LIST_ITEM_SELECTED(self.listCtrlDwgList,\n\t\t\t wxID_WXFRAMEPREVIEWLISTCTRLDWGLIST,\n\t\t\t self.OnListCtrlDwgListListItemSelected)\n\n\t\tself.gauge = wxGauge(id=wxID_WXFRAMEPREVIEWGAUGE, name='gauge',\n\t\t\t parent=self.panel1, pos=wxPoint(16, 360), range=100,\n\t\t\t size=wxSize(424, 16), style=wxGA_HORIZONTAL)\n\n\t\tself.buttonClearList = wxButton(id=wxID_WXFRAMEPREVIEWBUTTONCLEARLIST,\n\t\t\t label='Clear List', name='buttonClearList', parent=self.panel1,\n\t\t\t pos=wxPoint(24, 384), size=wxSize(75, 23), style=0)\n\t\tEVT_BUTTON(self.buttonClearList, wxID_WXFRAMEPREVIEWBUTTONCLEARLIST,\n\t\t\t self.OnButtonClearListButton)\n\n\t\tself.buttonDwgPreview = wxButton(id=wxID_WXFRAMEPREVIEWBUTTONDWGPREVIEW,\n\t\t\t label='Preview', name='buttonDwgPreview', parent=self.panel1,\n\t\t\t pos=wxPoint(184, 384), size=wxSize(75, 23), style=0)\n\t\tEVT_BUTTON(self.buttonDwgPreview, wxID_WXFRAMEPREVIEWBUTTONDWGPREVIEW,\n\t\t\t self.OnButtonDwgPreviewButton)\n\n\t\tself.buttonDwgEdit = wxButton(id=wxID_WXFRAMEPREVIEWBUTTONDWGEDIT,\n\t\t\t label='Edit', name='buttonDwgEdit', parent=self.panel1,\n\t\t\t pos=wxPoint(360, 384), size=wxSize(75, 23), style=0)\n\t\tEVT_BUTTON(self.buttonDwgEdit, wxID_WXFRAMEPREVIEWBUTTONDWGEDIT,\n\t\t\t self.OnButtonDwgEditButton)\n\n\t\tself.staticBoxChangePage = wxStaticBox(id=wxID_WXFRAMEPREVIEWSTATICBOXCHANGEPAGE,\n\t\t\t label='Change Page', name='staticBoxChangePage',\n\t\t\t parent=self.panel1, pos=wxPoint(24, 432), size=wxSize(416, 100),\n\t\t\t style=0)\n\n\t\tself.buttonExit = wxButton(id=wxID_WXFRAMEPREVIEWBUTTONEXIT,\n\t\t\t label='Exit', name='buttonExit', parent=self.panel1,\n\t\t\t pos=wxPoint(360, 544), size=wxSize(75, 23), style=0)\n\t\tEVT_BUTTON(self.buttonExit, wxID_WXFRAMEPREVIEWBUTTONEXIT,\n\t\t\t self.OnButtonExitButton)\n\n\t\tself.textCtrlPagePreview = wxTextCtrl(id=wxID_WXFRAMEPREVIEWTEXTCTRLPAGEPREVIEW,\n\t\t\t name='textCtrlPagePreview', parent=self.panel1, pos=wxPoint(48,\n\t\t\t 472), size=wxSize(64, 21), style=0, value='')\n\n\t\tself.textCtrlNewPage = wxTextCtrl(id=wxID_WXFRAMEPREVIEWTEXTCTRLNEWPAGE,\n\t\t\t name='textCtrlNewPage', parent=self.panel1, pos=wxPoint(160, 472),\n\t\t\t size=wxSize(40, 21), style=0, value='')\n\n\t\tself.textCtrlNewTotalPage = wxTextCtrl(id=wxID_WXFRAMEPREVIEWTEXTCTRLNEWTOTALPAGE,\n\t\t\t name='textCtrlNewTotalPage', parent=self.panel1, pos=wxPoint(224,\n\t\t\t 472), size=wxSize(48, 21), style=0, value='')\n\n\t\tself.staticTextNewPage = wxStaticText(id=wxID_WXFRAMEPREVIEWSTATICTEXTNEWPAGE,\n\t\t\t label='New', name='staticTextNewPage', parent=self.panel1,\n\t\t\t pos=wxPoint(128, 472), size=wxSize(22, 13), style=0)\n\n\t\tself.staticTextSeparator = wxStaticText(id=wxID_WXFRAMEPREVIEWSTATICTEXTSEPARATOR,\n\t\t\t label='/', name='staticTextSeparator', parent=self.panel1,\n\t\t\t pos=wxPoint(208, 472), size=wxSize(8, 21), style=0)\n\n\t\tself.buttonChangePageNo = wxButton(id=wxID_WXFRAMEPREVIEWBUTTONCHANGEPAGENO,\n\t\t\t label='Change', name='buttonChangePageNo', parent=self.panel1,\n\t\t\t pos=wxPoint(280, 472), size=wxSize(56, 23), style=0)\n\t\tEVT_BUTTON(self.buttonChangePageNo,\n\t\t\t wxID_WXFRAMEPREVIEWBUTTONCHANGEPAGENO,\n\t\t\t self.OnButtonChangePageNoButton)\n\n\t\tself.buttonSaveDwg = wxButton(id=wxID_WXFRAMEPREVIEWBUTTONSAVEDWG,\n\t\t\t label='Save', name='buttonSaveDwg', parent=self.panel1,\n\t\t\t pos=wxPoint(360, 472), size=wxSize(56, 23), style=0)\n\t\tEVT_BUTTON(self.buttonSaveDwg, wxID_WXFRAMEPREVIEWBUTTONSAVEDWG,\n\t\t\t self.OnButtonSaveDwgButton)\n\n\tdef __init__(self, parent):\n\t\tself._init_ctrls(parent)\n\n################################################################################\n# my own function start #\n################################################################################\n\tdef GetDwgType(self):\n\t\tdwg_type_list = [\"Assembly drawing\",\"General drawing\",\"Hull nesting sketch\"]\n\t\t#dwg_DB_list = [\"SB_ASSPDB\",\"SB_PDB\",\"SB_NPL\"]\n\t\tselection \t = self.radioBoxChooseDwgType.GetSelection()\n\t\tdwg_type \t = dwg_type_list[selection]\n\t\treturn dwg_type\n\n#-------------------------------------------------------------------------------\n\tdef GetDwgDB(self,dwg_type):\n\t\ttry:\n\t\t\tdict \t\t= kcs_draft.dwg_type_list_get() #dict is a dictionary of drawing type list\n\t\t\tdwg_dbNames = map(lambda x : x[0],dict.values())\n\t\t\tdwg_DBs \t= map(lambda x : x[1],dict.values())\n\t\t\tDB_keys \t= dict.keys()\n\t\t\ti = 0\n\t\t\twhile i < len(dwg_DBs):\n\t\t\t\tif dwg_dbNames[i] == dwg_type:\n\t\t\t\t\treturn dwg_DBs[i],DB_keys[i]\n\t\t\t\ti+=1\n\t\t\tif i == len(dwg_DBs):\n\t\t\t\tkcs_ui.message_confirm(\"drawing type do not exist in current project\")\n\t\texcept:\n\t\t\t\tkcs_ui.message_confirm(kcs_draft.error)\n\n#-------------------------------------------------------------------------------\n\tdef GetStmt(self):\n\t\tdwg_type = self.GetDwgType()\n\t\ttext_keyin = self.textCtrlKeyIn.GetValue().upper()\n\t\ttemp = text_keyin\n\t\tif temp == '*' or temp == \"\" :\n\t\t\tstmt = \"DRA('@\"+dwg_type+\"'*).NAM\"\n\t\t\treturn stmt\n\t\t\t\n\t\tif temp[0]=='*':\n\t\t\ttemp=temp[1:len(temp)]\n\t\tif temp[len(temp)-1]=='*':\n\t\t\ttemp=temp[0:len(temp)-1]\n\t\tsplit=temp.split('*')\n\t\tstr=\"\"\n\t\tfor i in split:\n\t\t\tstr += i+\"'*'\"\n\t\tstr=str[0:len(str)-3]\n\t\t\n\t\tprefix = text_keyin[0]\n\t\tpostfix = text_keyin[len(text_keyin)-1]\n\t\tif prefix != '*' and postfix != '*':\n\t\t\tstmt = \"DRA('\"+str+'@'+dwg_type+\"').NAM\"\n\t\telif prefix != '*' and postfix == '*':\n\t\t\tstmt = \"DRA('\"+str+'@'+dwg_type+\"'*).NAM\"\n\t\telif prefix == '*' and postfix != '*':\n\t\t\tstmt = \"DRA(*'\"+str+'@'+dwg_type+\"').NAM\"\n\t\telse:\n\t\t\tstmt = \"DRA(*'\"+str+'@'+dwg_type+\"'*).NAM\"\n\t\treturn stmt\n\n#-------------------------------------------------------------------------------\n\tdef GetDwgNameList(self,stmt_get_dwgname):\n\t\tself.gauge.SetRange(50)\n\t\tdwg_name_list = []\n\t\ttry:\n\t\t\tif kcs_dex.extract(stmt_get_dwgname) == 0 :\n\t\t\t\tdataType = kcs_dex.next_result()\n\t\t\t\tif dataType < 0 :\n\t\t\t\t\tkcs_ui.message_confirm(\"drawngs not found\")\n\t\t\t\t\treturn []\n\t\t\t\tgauge = 0\n\t\t\t\twhile dataType >= 0:\n\t\t\t\t\tif dataType == 3:\n\t\t\t\t\t\tif gauge == 50:\n\t\t\t\t\t\t\tgauge = 0\n\t\t\t\t\t\tgauge += 1\n\t\t\t\t\t\tself.gauge.SetValue(gauge)\n\t\t\t\t\t\tdwg_name_list.append(kcs_dex.get_string())\n\t\t\t\t\t\tdataType = kcs_dex.next_result()\n\t\t\tself.gauge.SetRange(gauge)\n\t\t\tself.gauge.SetValue(gauge)\n\t\t\treturn dwg_name_list\n\t\texcept:\n\t\t\tkcs_ui.message_confirm(kcs_dex.error)\n\n#-------------------------------------------------------------------------------\n\tdef GetColumnText(self,index,col):\n\t\titem = self.listCtrlDwgList.GetItem(index,col)\n\t\treturn item.GetText()\n\n#-------------------------------------------------------------------------------\n\tdef GetTotalNumber(self):\n\t\tdwg_type \t\t = self.GetDwgType()\n\t\tstmt_get_totalNo = \"DRA('\"+self.dwg_name+'@'+dwg_type+\"').TEXT_BY_RULE(8889).ROW(1)\"\n\t\tkcs_dex.extract(stmt_get_totalNo)\n\t\tif kcs_dex.next_result() < 0 :\n\t\t\tdwg_total_no = \" \"\n\t\telse :\n\t\t\tdwg_total_no = kcs_dex.get_string()\n\t\treturn dwg_total_no\n\n#-------------------------------------------------------------------------------\n\tdef GetPageNoList(self,dwg_name_list):\n\t\tself.gauge.SetRange(50)\n\t\tgauge \t = 0\n\t\tdwg_type = self.GetDwgType()\n\t\tdwg_pageNo_list = []\n\t\tfor i in dwg_name_list :\n\t\t\tkcs_dex.extract(\"DRA('\"+i+'@'+dwg_type+\"').TEXT_BY_RULE(8888).ROW(1)\")\n\t\t\tif gauge == 50:\n\t\t\t\tgauge = 0\n\t\t\tgauge += 1\n\t\t\tself.gauge.SetValue(gauge)\n\t\t\tif kcs_dex.next_result() < 0 :\n\t\t\t\tdwg_pageNo_list.append(\" \")\n\t\t\telse :\n\t\t\t\tdwg_pageNo_list.append(kcs_dex.get_string())\n\t\tself.gauge.SetRange(gauge)\n\t\tself.gauge.SetValue(gauge)\n\t\treturn dwg_pageNo_list\n\n#-------------------------------------------------------------------------------\n\tdef SetListCtrl(self,dwg_name_list,dwg_pageNo_list):\n\t\tfor i in range(len(dwg_name_list)):\n\t\t\tself.listCtrlDwgList.InsertStringItem(i,'')\n\t\t\tself.listCtrlDwgList.SetStringItem(i,0,dwg_name_list[i])\n\t\t\tself.listCtrlDwgList.SetStringItem(i,1,dwg_pageNo_list[i])\n\n#-------------------------------------------------------------------------------\n\tdef OpenCurrentDwg(self,mode):\n\t\tif kcs_draft.dwg_current():\n\t\t\tkcs_draft.dwg_close()\n\t\tdwg_type = self.GetDwgType()\n\t\tDB,DBKey = self.GetDwgDB(dwg_type)\n\t\ttry:\n\t\t\tkcs_draft.dwg_open(self.dwg_name,DB,mode)\n\t\texcept:\n\t\t\tkcs_ui.message_confirm(kcs_draft.error)\n\n################################################################################\n# my own functions end #\n################################################################################\n\n################################################################################\n# Event functions start #\n################################################################################\n\n\tdef OnButtonSearchByBlockButton(self, event):\n\t\tself.listCtrlDwgList.DeleteAllItems()\n\t\t# stmt_get_dwgname = self.GetDwgNameStmt()\n\t\tstmt_get_dwgname = self.GetStmt()\n\t\tdwg_name_list \t = self.GetDwgNameList(stmt_get_dwgname)\n\t\tdwg_PangeNo_list = self.GetPageNoList(dwg_name_list)\n\t\tself.SetListCtrl(dwg_name_list,dwg_PangeNo_list)\n\n#-------------------------------------------------------------------------------\n\tdef OnButtonSearchByPieceButton(self, event):\n\t\tself.listCtrlDwgList.DeleteAllItems()\n\t\tstmt_piece_list \t= self.GetStmt()\n\t\tdwg_piece_list\t\t= self.GetDwgNameList(stmt_piece_list)\n\t\tdwg_piece_page_list = self.GetPageNoList(dwg_piece_list)\n\t\tself.SetListCtrl(dwg_piece_list,dwg_piece_page_list)\n\n#-------------------------------------------------------------------------------\n\tdef OnListCtrlDwgListListItemSelected(self, event):\n\t\tcurrent_item = event.m_itemIndex\n\t\tself.dwg_name = self.GetColumnText(current_item,0)\n\t\tdwg_page \t = self.GetColumnText(current_item,1)\n\t\tself.textCtrlPagePreview.SetValue(dwg_page)\n\t\tself.textCtrlNewPage.SetValue(dwg_page)\n\t\tdwg_total_No = self.GetTotalNumber()\n\t\tself.textCtrlNewTotalPage.SetValue(dwg_total_No)\n\n#-------------------------------------------------------------------------------\n\tdef OnButtonClearListButton(self, event):\n\t\tself.listCtrlDwgList.DeleteAllItems()\n\n#-------------------------------------------------------------------------------\n\tdef OnButtonDwgPreviewButton(self, event):\n\t\tself.OpenCurrentDwg(kcs_draft.kcsOPENMODE_READONLY)\n\n#-------------------------------------------------------------------------------\n\tdef OnButtonDwgEditButton(self, event):\n\t\tself.OpenCurrentDwg(kcs_draft.kcsOPENMODE_READWRITE)\n\t\tif kcs_draft.dwg_current():\n\t\t\tself.Destroy()\n\t\telse:\n\t\t\tevent.skip()\n\n#-------------------------------------------------------------------------------\n\tdef OnButtonExitButton(self, event):\n\t\tself.Destroy()\n\n#-------------------------------------------------------------------------------\n\tdef OnButtonChangePageNoButton(self, event):\n\t\tself.OpenCurrentDwg(kcs_draft.kcsOPENMODE_READWRITE)\n\t\tpage_No \t= self.textCtrlPagePreview.GetValue()\n\t\tnew_page_No = self.textCtrlNewPage.GetValue()\n\t\tif new_page_No != \"\" and page_No != new_page_No:\n\t\t\ttry:\n\t\t\t\tkcs_draft.rule_text_new(new_page_No,8888)\n\t\t\texcept:\n\t\t\t\tkcs_ui.message_confirm(kcs_draft.error)\n\t\tnew_total_page \t = self.textCtrlNewTotalPage.GetValue()\n\t\tprevious_total_No = self.GetTotalNumber()\n\t\tif new_total_page != \"\" and previous_total_No != new_total_page :\n\t\t\ttry:\n\t\t\t\tkcs_draft.rule_text_new(new_total_page,8889)\n\t\t\texcept:\n\t\t\t\tkcs_ui.message_confirm(kcs_draft.error)\n\n#-------------------------------------------------------------------------------\n\tdef OnButtonSaveDwgButton(self, event):\n\t\ttry:\n\t\t\tkcs_draft.dwg_save()\n\t\texcept:\n\t\t\tkcs_ui.message_confirm(kcs_draft.error)\n\n################################################################################\n# Event functions end #\n################################################################################\n\n################################################################################\n# main function start #\n################################################################################\n \nclass PreviewApp(wxApp):\n\tdef OnInit(self):\n\t\twxInitAllImageHandlers()\n\t\tself.main = create(None)\n\t\tself.main.Show()\n\t\tself.SetTopWindow(self.main)\n\t\treturn True\n\ndef main():\n\tapplication = PreviewApp(0)\n\tapplication.MainLoop()\n\nif __name__ == '__main__':\n\tmain()\n################################################################################\n# main function ends #\n################################################################################","sub_path":"src/python/tribonM3/PreviewFrame.PM.17.57.py","file_name":"PreviewFrame.PM.17.57.py","file_ext":"py","file_size_in_byte":16070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"197284105","text":"# coding: utf-8\n###################################################################\n# Copyright (c) 2016-2020 European Synchrotron Radiation Facility #\n# #\n# Author: Marius Retegan #\n# #\n# This work is licensed under the terms of the MIT license. #\n# For further information, see https://github.com/mretegan/crispy #\n###################################################################\n\"\"\"The modules provides a class to deal with the configuration.\"\"\"\n\nimport logging\nimport os\nimport sys\n\nfrom PyQt5.QtCore import QSettings, QStandardPaths\n\nfrom crispy import __version__ as version, resourceAbsolutePath\n\nlogger = logging.getLogger(__name__)\n\n\nclass Config:\n @property\n def name(self):\n return \"Crispy\" if sys.platform == \"win32\" else \"crispy\"\n\n @property\n def path(self):\n return os.path.split(self.settings.fileName())[0]\n\n @property\n def settings(self):\n return QSettings(\n QSettings.IniFormat, QSettings.UserScope, self.name, \"settings-new\"\n )\n\n def read(self):\n return self.settings\n\n def loadDefaults(self):\n settings = self.read()\n\n settings.beginGroup(\"Quanty\")\n settings.setValue(\"Path\", self.findQuanty())\n settings.setValue(\"Verbosity\", \"0x0000\")\n settings.setValue(\"DenseBorder\", \"2000\")\n settings.setValue(\"RemoveFiles\", True)\n settings.endGroup()\n\n settings.setValue(\"CheckForUpdates\", True)\n settings.setValue(\"CurrentPath\", os.path.expanduser(\"~\"))\n settings.setValue(\"Version\", version)\n\n settings.sync()\n\n def removeOldFiles(self):\n \"\"\"Function that removes the settings from previous versions.\"\"\"\n root = QStandardPaths.standardLocations(QStandardPaths.GenericConfigLocation)[0]\n\n path = os.path.join(root, self.name)\n\n if version < \"0.7.0\":\n try:\n os.remove(os.path.join(path, \"settings.json\"))\n os.rmdir(path)\n logger.debug(\"Removed old configuration file.\")\n except (IOError, OSError):\n pass\n\n @staticmethod\n def findQuanty():\n if sys.platform == \"win32\":\n executable = \"Quanty.exe\"\n else:\n executable = \"Quanty\"\n\n envPath = QStandardPaths.findExecutable(executable)\n localPath = resourceAbsolutePath(os.path.join(\"quanty\", \"bin\"))\n localPath = QStandardPaths.findExecutable(executable, [localPath])\n\n # Check if Quanty is in the paths defined in the $PATH.\n if envPath:\n path = envPath\n # Check if Quanty is bundled with Crispy.\n elif localPath:\n path = localPath\n else:\n path = None\n\n return path\n","sub_path":"crispy/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"486304894","text":"import abc\nimport random\nfrom collections import deque, namedtuple\nfrom typing import Any, Collection, Optional\n\nimport numpy as np\nimport torch\nfrom dataclasses import dataclass\nfrom torch import optim\nfrom torch.nn import functional as f\n\nfrom epsilon_policies import EpsilonGreedyPolicy\nfrom model import DQNModel\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nexperience = namedtuple(\"Experience\", field_names=[\"state\", \"action\", \"reward\", \"next_state\", \"done\"]) #\n\n\n@dataclass\nclass DRLAgent(abc.ABC):\n \"\"\"\n Abstract deep reinforcement learning agent.\n \"\"\"\n state_size: int # size of each state in the state space\n action_size: int # size of the action space\n lr: float # learning rate\n epsilon_greedy_policy: EpsilonGreedyPolicy\n seed: Optional[int] # seed\n buffer_size: int = int(1e5) # experience memory buffer size\n batch_size: int = 64 # experience memory batch size\n update_every: int = 4 # how often the target network is updated\n gamma: float = 0.99 # discount factor\n tau: float = 1e-3 # step-size for soft updating the target network\n \n @abc.abstractmethod\n def step(self, state: Collection[float], action: int, reward: float, next_state: Collection[float],\n done: bool) -> None:\n \"\"\"\n The agent registers a step it took in the environment.\n\n :param state: current state\n :param action: action taken\n :param reward: reward received\n :param next_state: state that resulted from the action\n :param done: if the resulting state was terminal\n \"\"\"\n \n @abc.abstractmethod\n def learn(self, experiences: Collection[experience]) -> None:\n \"\"\"\n The agent learns from previous experiences.\n :param experiences: a minibatch of previous experiences with size=batch_size\n \"\"\"\n \n @abc.abstractmethod\n def act(self, state: Collection[float], train: bool = True) -> int:\n \"\"\"\n The agent acts following a epsilon-greedy policy.\n :param train: if training mode is active, if so the agent will follow the epsilon-greedy policy, otherwise it\n will follow the greedy policy\n :param state: current state\n :return: action selected\n \"\"\"\n \n def soft_update(self) -> None:\n \"\"\"\n Soft-updates the target network with the recently-updated parameters of the local network, with self.tau as\n step-size.\n \"\"\"\n\n\nclass DQNetAgent(DRLAgent):\n \"\"\"\n Deep Q-Network agent.\n \"\"\"\n \n def __init__(self, **data: Any):\n super(DQNetAgent, self).__init__(**data)\n np.random.seed(self.seed)\n \n # Initializes the Local and the Target QNetworks.\n self.q_local = DQNModel(self.state_size, self.action_size, self.seed).to(device)\n self.q_target = DQNModel(self.state_size, self.action_size, self.seed).to(device)\n self.optimizer = optim.Adam(self.q_local.parameters(), lr=self.lr)\n \n # Initializes the experience replay memory\n self.memory = ReplayBuffer(buffer_size=self.buffer_size, batch_size=self.batch_size, seed=self.seed)\n \n # Sets the initial time step to 0, this is used for updating the target network every update_every steps\n self.time_step = 0\n \n def load(self, path: str) -> None:\n \"\"\"\n Load previously trained model.\n :param path: model path\n \"\"\"\n self.q_local.load_state_dict(torch.load(path))\n \n def step(self, state: Collection[float], action: int, reward: float, next_state: Collection[float], done: bool) -> \\\n None:\n # Store experience in memory\n self.memory.add(state, action, reward, next_state, done)\n \n # Learn every update_every time steps\n self.time_step = (self.time_step + 1) % self.update_every\n if self.time_step == 0:\n # Check if there are enough samples in memory, if so, get a sample and learn from it\n if len(self.memory) > self.batch_size:\n experiences = self.memory.sample()\n self.learn(experiences)\n \n def learn(self, experiences: Collection[experience]) -> None:\n \n # Get the informed from the experiences sample.\n states, actions, rewards, next_states, dones = experiences\n \n # Max action value for each episode in the sample\n target_values = self.q_target(next_states).cpu().max(1)[0].unsqueeze(1)\n \n # Calculate the target action-value for taking each action from each origin state in the sample. If the\n # episode is terminal, the action-value is the reward\n target_values = target_values.to(device)\n target_estimate = rewards + self.gamma * target_values * (1 - dones)\n \n # Get the estimates for the local network and gather the action-value for each action taken in the sample.\n local_estimate = self.q_local(states).gather(1, actions)\n \n # Calculate the loss and applies gradient descent\n loss = f.mse_loss(local_estimate, target_estimate)\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n \n # Update the target network\n self.soft_update()\n \n def act(self, state: Collection[float], train: bool = True) -> int:\n epsilon = self.epsilon_greedy_policy.step(self.time_step)\n state = torch.from_numpy(state).float().unsqueeze(0).to(device)\n \n # Get estimate action values from local network\n self.q_local.eval()\n with torch.no_grad():\n action_values = self.q_local(state)\n self.q_local.train()\n \n # Epsilon-greedy action selection\n if train:\n if np.random.random() > epsilon:\n return np.argmax(action_values.cpu().data.numpy())\n else:\n return np.random.choice(np.arange(self.action_size))\n else:\n return np.argmax(action_values.cpu().data.numpy())\n \n def soft_update(self) -> None:\n for target_p, local_p in zip(self.q_target.parameters(), self.q_local.parameters()):\n target_p.data.copy_(self.tau * local_p.data + (1.0 - self.tau) * target_p.data)\n\n\nclass ReplayBuffer:\n \"\"\"\n Buffer for stores experiences and sampling them when requested.\n \"\"\"\n \n def __init__(self, batch_size: int, buffer_size: int, seed: int):\n \"\"\"\n ReplayBuffer constructor\n :param batch_size: number of experiences in a minibatch\n :param buffer_size: max len of memory\n :param seed: random seed\n \"\"\"\n super(ReplayBuffer, self).__init__()\n random.seed(seed)\n self.batch_size = batch_size\n self.memory = deque(maxlen=buffer_size)\n \n def add(self, state: Collection[float], action: int, reward: float, next_state: Collection[float], done: bool) -> \\\n None:\n \"\"\"\n Add a new experience to memory.\n :param state: current state\n :param action: action taken\n :param reward: reward received\n :param next_state: resulting state after action\n :param done: if the resulting state is terminal\n \"\"\"\n exp = experience(state, action, reward, next_state, done)\n self.memory.append(exp)\n \n def sample(self) -> Collection[experience]:\n \"\"\"\n Randomly sample a batch of experiences from memory.\n :return: a minibatch of experiences\n \"\"\"\n samples = random.sample(self.memory, k=self.batch_size)\n samples = np.array(samples, dtype=np.object)\n \n states = torch.from_numpy(np.vstack(samples[:, 0])).float().to(device)\n actions = torch.from_numpy(np.vstack(samples[:, 1])).long().to(device)\n rewards = torch.from_numpy(np.vstack(samples[:, 2])).float().to(device)\n next_states = torch.from_numpy(np.vstack(samples[:, 3])).float().to(device)\n dones = torch.from_numpy(np.vstack(samples[:, 4]).astype(np.uint8)).float().to(\n device)\n return states, actions, rewards, next_states, dones\n \n def __len__(self) -> int:\n \"\"\"Return the current size of internal memory\"\"\"\n return len(self.memory)\n","sub_path":"src/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":8251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"651540388","text":"from django.utils import timezone\nfrom webzmap import settings\nimport os\nimport sys\nimport subprocess\nimport time\nimport datetime\n\n\nclass ZmapStatus(object):\n def __init__(self):\n self.read_time = None\n self.time_elapsed = 0\n self.time_remaining = 0\n self.percent_complete = 0\n self.active_send_threads = 0\n self.sent_total = 0\n self.hit_rate = 0\n self.sent_last_one_sec = 0\n self.sent_avg_per_sec = 0\n self.recv_success_total = 0\n self.recv_success_last_one_sec = 0\n self.recv_success_avg_per_sec = 0\n self.recv_total = 0\n self.recv_total_last_one_sec = 0\n self.recv_total_avg_per_sec = 0\n self.pcap_drop_total = 0\n self.drop_last_one_sec = 0\n self.drop_avg_per_sec = 0\n self.sendto_fail_total = 0\n self.sendto_fail_last_one_sec = 0\n self.sendto_fail_avg_per_sec = 0\n\n\nclass ShellExecuteError(BaseException):\n def __init__(self, error_msg):\n super(ShellExecuteError, self).__init__(error_msg)\n\n\ndef create_parent_dir(path):\n parent = os.path.dirname(path)\n if not os.path.exists(parent):\n os.makedirs(parent)\n\n\ndef get_last_line(path):\n cmd = \"tail -n 1 %s\" % path\n p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)\n return_code = p.wait()\n if return_code == 0:\n return p.stdout.read().strip()\n else:\n raise ShellExecuteError(p.stderr.read())\n\n\ndef get_current_status(status_path):\n \"\"\"\n real-time,\n time-elapsed,\n time-remaining,\n percent-complete,\n hit-rate,\n active-send-threads,\n sent-total,\n sent-last-one-sec,\n sent-avg-per-sec,\n recv-success-total,\n recv-success-last-one-sec,\n recv-success-avg-per-sec,\n recv-total,\n recv-total-last-one-sec,\n recv-total-avg-per-sec,\n pcap-drop-total,\n drop-last-one-sec,\n drop-avg-per-sec,\n sendto-fail-total,\n sendto-fail-last-one-sec,\n sendto-fail-avg-per-sec\n :param status_path:\n :return:\n \"\"\"\n try:\n line = get_last_line(status_path)\n except ShellExecuteError:\n return None\n if line.startswith(\"real-time\"):\n return None\n status = ZmapStatus()\n items = line.split(\",\")\n t = time.strptime(items[0], \"%Y-%m-%d %X\")\n y, m, d, h, M, s = t[0:6]\n status.read_time = datetime.datetime(y, m, d, h, M, s, tzinfo=timezone.LocalTimezone())\n status.time_elapsed = int(items[1])\n status.time_remaining = int(items[2])\n status.percent_complete = float(items[3])\n status.hit_rate = float(items[4])\n status.active_send_threads = int(items[5])\n status.sent_total = long(items[6])\n status.sent_last_one_sec = int(items[7])\n status.sent_avg_per_sec = int(items[8])\n status.recv_success_total = long(items[9])\n status.recv_success_last_one_sec = int(items[10])\n status.recv_success_avg_per_sec = int(items[11])\n status.recv_total = long(items[12])\n status.recv_total_last_one_sec = int(items[13])\n status.recv_total_avg_per_sec = int(items[14])\n status.pcap_drop_total = long(items[15])\n status.drop_last_one_sec = int(items[16])\n status.drop_avg_per_sec = int(items[17])\n status.sendto_fail_total = long(items[18])\n status.sendto_fail_last_one_sec = int(items[19])\n status.sendto_fail_avg_per_sec = int(items[20])\n return status\n\n\nclass Zmap(object):\n def __init__(self, execute_bin='zmap', verbosity=3, cwd=None, logger=None):\n self.execute_bin = execute_bin\n self.verbosity = verbosity\n self.cwd = cwd\n self.logger = logger\n\n def run_job(self, job):\n pass\n\n def scan(self, job, port, subnets=None, output_path=None, log_path=None, bandwidth=2, white_list=None, black_list=None,\n verbosity=None, status_updates_path=None, quiet=False, stdout=None, stderr=None):\n if verbosity:\n self.verbosity = verbosity\n cmd = \"%s -p %s\" % (self.execute_bin, port)\n # if output_path:\n # output_path = os.path.join(self.cwd, output_path)\n # create_parent_dir(output_path)\n # cmd += ' -o %s' % output_path\n if bandwidth:\n # cmd += \" -B %sM\" % bandwidth\n cmd += \" -r %s\" % bandwidth\n if white_list:\n white_list = os.path.join(self.cwd, white_list)\n create_parent_dir(white_list)\n cmd += \" -w %s\" % white_list\n if black_list:\n black_list = os.path.join(self.cwd, black_list)\n create_parent_dir(black_list)\n cmd += \" -b %s\" % black_list\n if status_updates_path:\n status_updates_path = os.path.join(self.cwd, status_updates_path)\n create_parent_dir(status_updates_path)\n cmd += \" -u %s\" % status_updates_path\n if log_path:\n log_path = os.path.join(self.cwd, log_path)\n create_parent_dir(log_path)\n cmd += \" -l %s\" % log_path\n cmd += ' -v %s' % self.verbosity\n if subnets:\n cmd += ' ' + subnets\n if quiet:\n cmd += ' -q'\n if self.logger:\n self.logger.info(\"cmd is \" + cmd)\n cmd = filter(lambda x: x.strip() != '', cmd.split(\" \"))\n r, w = os.pipe()\n zmap_pid = subprocess.Popen(cmd, stdout=w, stderr=sys.stderr)\n service = get_service(port)\n zgrab_arg = [settings.zgrab2_path, service]\n zgrab_pid = subprocess.Popen(zgrab_arg, stdin=r, stderr=sys.stderr)\n self.logger.info(\"cmd is fuck\")\n return zmap_pid, zgrab_pid\n\n\ndef get_service(port):\n port_to_service = {\n 102: \"siemens\",\n 502: \"modbus\",\n 789: \"crimson\",\n 1911: \"fox\",\n 1962: \"pcworx\",\n 2404: \"iec104\",\n 9600: \"omron\",\n 20000: \"dnp3\",\n 20547: \"proconos\",\n 44818: \"ethip\",\n 47808: \"bacnet\",\n }\n return port_to_service[port]\n\n\nif __name__ == '__main__':\n import signal\n zmap = Zmap(logger=None)\n p, q = zmap.scan(\n job=\"ss\",\n subnets='118.25.94.0/24',\n port=80,\n stderr=None,\n stdout=None,\n quiet=False,\n )\n import time\n p_exit_code = p.poll()\n q_exit_code = q.poll()\n while p_exit_code is None:\n print(p.poll())\n if p.poll() == 0:\n q.send_signal(signal.SIGKILL)\n break\n time.sleep(2)\n\n","sub_path":"tools/zmap.py","file_name":"zmap.py","file_ext":"py","file_size_in_byte":6394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"644026677","text":"# -*- coding: utf-8 -*-\r\nimport codecs\r\n\r\nclass Morpheme:\r\n def __init__(self,surface,base,pos,pos1):\r\n self.surface = surface\r\n self.base = base\r\n self.pos = pos\r\n self.pos1 = pos1\r\n\r\nclass Phrase:\r\n def __init__(self,morpheme_surfaces,morpheme_bases,morphemes_poses,modifier_index,phrase_index):\r\n self.morpheme_surfaces = morpheme_surfaces\r\n self.morpheme_bases = morpheme_bases\r\n self.morpheme_poses = morphemes_poses\r\n self.modifier_index = modifier_index\r\n self.phrase_index = phrase_index\r\n\r\nclass Sentence:\r\n def __init__(self, phrases):\r\n self.phrases = phrases\r\n\r\ndef init(sentence):\n sentence = Sentence([])\r\n\r\ndef decisionOutput(phrases):\r\n output_candidate_phrases = []\r\n output_candidate_phrases_modifier_indexs = []\r\n for phrase in phrases:\r\n for output_candidate_phrase in output_candidate_phrases:\r\n modifier_index = int(output_candidate_phrase.split(\"\\t\")[0])\r\n modifiee_index = phrase.phrase_index\r\n if modifier_index == modifiee_index:\r\n if u\"動詞\" in phrase.morpheme_poses:\r\n noun_particle = output_candidate_phrase.split(\"\\t\")[1]\r\n verb_index = phrase.morpheme_poses.index(u\"動詞\")\r\n verb = phrase.morpheme_bases[verb_index]\r\n verb_noun_particle = verb + ' ' + noun_particle\r\n print(verb_noun_particle)\r\n output_candidate_phrases.remove(output_candidate_phrase)\r\n output_candidate_phrases_modifier_indexs.remove(str(modifier_index))\r\n break\r\n if u\"名詞\" in phrase.morpheme_poses and u\"助詞\" in phrase.morpheme_poses:\r\n noun_index = phrase.morpheme_poses.index(u\"名詞\")\r\n noun = phrase.morpheme_surfaces[noun_index]\r\n particle_index = phrase.morpheme_poses.index(u\"助詞\")\r\n particle = phrase.morpheme_surfaces[particle_index]\r\n if phrase.modifier_index not in output_candidate_phrases_modifier_indexs:\r\n output_candidate_phrases_modifier_indexs.append(phrase.modifier_index)\r\n output_candidate_phrases.append(phrase.modifier_index + '\\t' + noun + ' ' + particle)\r\n else:\r\n index = output_candidate_phrases_modifier_indexs.index(phrase.modifier_index)\r\n output_candidate_phrases[index] += (' ' + noun + ' ' + particle)\r\n\r\n\r\ndef main():\r\n input_file = codecs.open(\"doc0000000000.knp.txt\", 'r', \"utf-8\")\r\n phrase = Phrase([], [], [], -1, -1)\r\n sentence = Sentence([])\r\n phrase_index = 0\r\n# 全体的に変数名見直す\r\n for line in input_file.readlines():\r\n\r\n if \"EOS\\n\" == line:\r\n if len(phrase.morpheme_surfaces) != 0:\r\n sentence.phrases.append(phrase)\r\n decisionOutput(sentence.phrases)\r\n sentence = Sentence([])\r\n phrase_index = 0\r\n continue\r\n else:\r\n line_split = line.split(\" \")\r\n identifiers = []\r\n identifiers.append(line_split[0])\r\n identifiers.append(line_split[2][0])\r\n if '*' == identifiers[0] and '<' == identifiers[1]:\r\n continue\r\n if '#' == identifiers[0] and 'U' == identifiers[1]:\r\n continue\r\n elif '+' == identifiers[0] and '<' == identifiers[1]:\r\n if len(phrase.morpheme_surfaces) != 0:\r\n sentence.phrases.append(phrase)\r\n #↑1句終わりとしての処理、↓1句はじめとしての処理\r\n modifier_index = line_split[1][:-1]\r\n phrase = Phrase([], [], [], modifier_index, phrase_index)\r\n phrase_index += 1\r\n else:\r\n surface = line_split[0]\r\n base = line_split[2]\r\n pos = line_split[3]\r\n phrase.morpheme_surfaces.append(surface)\r\n phrase.morpheme_bases.append(base)\r\n phrase.morpheme_poses.append(pos)\r\n\r\n\r\n input_file.close()\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"knp_edit.py","file_name":"knp_edit.py","file_ext":"py","file_size_in_byte":4092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"176624511","text":"from django.test import TestCase\nimport datetime\nfrom django.test import TestCase\nfrom django.utils import timezone\n\nfrom .models import Question, Choice\n\n\nclass QuestionModelTest(TestCase):\n def test_was_published_recently_with_future_question(self):\n time = timezone.now() + datetime.timedelta(days=30)\n future_question = Question(pub_date=time)\n self.assertIs(future_question.was_published_recently(), False)\n\n\ndef create_question(question_text, days):\n time = timezone.now() + datetime.datetime(day == days)\n return Question.objects.create(question_text=question_text, pub_date=time)\n\n\nclass QuestionIndexViewTests(TestCase):\n def test_no_question(self):\n r = self.client.get(reverse('polls:index'))\n self.assertEqual(r.status_code, 200)\n self.assertContains(r, \"No polls are avaliable\")\n self.assertQuerysetEqual(r.context['latest_question_list'], [])\n\n def test_past_question(self):\n create_question('Past question', 30)\n r = self.client.get(reverse('polls:index'))\n self.assertQuerysetEqual(\n r.context['latest_question_list'],\n {':Past question'}\n )\n \n","sub_path":"src/mysite/polls/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"329243914","text":"# -*- coding: utf-8 -*-\n\nfrom unittest import TestCase\n\nimport numpy as np\n\nfrom sklearn.svm.classes import SVC\nfrom sklearn.datasets import samples_generator\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import f_regression\nfrom sklearn.pipeline import Pipeline\n\nfrom tests.estimator.classifier.Classifier import Classifier\nfrom tests.language.JavaScript import JavaScript\n\n\nclass SVCJSTest(JavaScript, Classifier, TestCase):\n\n def setUp(self):\n super(SVCJSTest, self).setUp()\n self.estimator = SVC(C=1., kernel='rbf',\n gamma=0.001, random_state=0)\n\n def tearDown(self):\n super(SVCJSTest, self).tearDown()\n\n def test_linear_kernel(self):\n self.estimator = SVC(C=1., kernel='linear',\n gamma=0.001, random_state=0)\n self.load_iris_data()\n self._port_estimator()\n amin = np.amin(self.X, axis=0)\n amax = np.amax(self.X, axis=0)\n preds, ground_truth = [], []\n for _ in range(self.TEST_N_RANDOM_FEATURE_SETS):\n x = np.random.uniform(amin, amax, self.n_features)\n preds.append(self.pred_in_custom(x))\n ground_truth.append(self.pred_in_py(x))\n self._clear_estimator()\n # noinspection PyUnresolvedReferences\n self.assertListEqual(preds, ground_truth)\n\n def test_sigmoid_kernel(self):\n self.estimator = SVC(C=1., kernel='sigmoid',\n gamma=0.001, random_state=0)\n self.load_iris_data()\n self._port_estimator()\n amin = np.amin(self.X, axis=0)\n amax = np.amax(self.X, axis=0)\n preds, ground_truth = [], []\n for _ in range(self.TEST_N_RANDOM_FEATURE_SETS):\n x = np.random.uniform(amin, amax, self.n_features)\n preds.append(self.pred_in_custom(x))\n ground_truth.append(self.pred_in_py(x))\n self._clear_estimator()\n # noinspection PyUnresolvedReferences\n self.assertListEqual(preds, ground_truth)\n\n def test_auto_gamma(self):\n self.estimator = SVC(C=1., gamma='auto', random_state=0)\n self.load_iris_data()\n self._port_estimator()\n amin = np.amin(self.X, axis=0)\n amax = np.amax(self.X, axis=0)\n preds, ground_truth = [], []\n for _ in range(self.TEST_N_RANDOM_FEATURE_SETS):\n x = np.random.uniform(amin, amax, self.n_features)\n preds.append(self.pred_in_custom(x))\n ground_truth.append(self.pred_in_py(x))\n self._clear_estimator()\n # noinspection PyUnresolvedReferences\n self.assertListEqual(preds, ground_truth)\n\n def test_pipeline_estimator(self):\n self.X, self.y = samples_generator.make_classification(\n n_informative=5, n_redundant=0, random_state=42)\n anova_filter = SelectKBest(f_regression, k=5)\n self.estimator = Pipeline([('anova', anova_filter), ('svc', SVC(kernel='linear'))])\n self.estimator.set_params(anova__k=10, svc__C=.1)\n try:\n self._port_estimator()\n except Exception as e:\n self.fail('Unexpected exception raised: {}'.format(e.message))\n finally:\n self._clear_estimator()\n","sub_path":"tests/estimator/classifier/SVC/SVCJSTest.py","file_name":"SVCJSTest.py","file_ext":"py","file_size_in_byte":3237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"200063455","text":"from typing import Sequence, Tuple\n\ndef prereq(courses: Sequence[int], categories: Sequence[Tuple[int, Sequence[int]]]) -> bool:\n taken_in_category = [0] * len(categories)\n for course in courses:\n for ndx, category in enumerate(categories):\n if course in category[1]:\n taken_in_category[ndx] += 1\n for ndx, category in enumerate(categories):\n if taken_in_category[ndx] < category[0]:\n return False\n return True\n\ndef test_1():\n assert prereq([123, 9876, 2222], [(1, [8888, 2222]), (2, [9876, 2222, 7654])]) == True\n\n\ndef test_2():\n assert prereq([123, 9876, 2222], [(2, [8888, 2222]), (2, [9876, 2222, 7654])]) == False\n\n\nif __name__ == '__main__':\n while True:\n line = input()\n if line == '0':\n break\n num_courses, num_categories = map(int, line.split())\n courses = list(map(int, input().split()))\n categories = []\n for c in range(num_categories):\n info = list(map(int, input().split()))\n categories.append((info[1], info[2:]))\n print(['no','yes'][prereq(courses, categories)])\n\n# from 514.1 rank 683 (team 284.4 rank 132)","sub_path":"python/1_8/prerequisites.py","file_name":"prerequisites.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"399605346","text":"#November 6th, 2018 Sebastian \n# I have not given or received any unauthorized assistance on this assignment.” \nimport random\nimport math\nclass ellipse(object):\n 'Class that holds ellipse information'\n \n def __init__(self,Major,Minor):\n 'Set up the primary numbers to calc the ellipse, major and minor axis '\n self.Major = Major # major axis radius \n self.Minor = Minor #minor axis radius \n \n def setFocli(self,Major,Minor,C1):\n 'Figure out what the Folci points are in the ellipse'\n self.focli = round(math.sqrt(Major**2 - Minor**2),2) #formula to obtian focli points in ellipse \n self.F1 = self.focli + C1 # set equal to folci \n self.F2 = self.focli * -1 + C1 # give neg to get opposite side of axis \n \n return (self.F1, self.F2)\n\n def setMajor_Minor_Axis(self,Major,Minor,C1,C2):\n 'Set up the bounds of the ellipse '\n # self.fMajor = Major * 2 # double the major radius to get full major axis\n # self.fMinor = Minor * 2 # doulbe the minor radius to get full minor axis \n self.V1 = Major + C1# upper bound of Major axis \n self.V2 = Major * -1 - C1 # Lower bound of major axis\n self.V3 = Minor + C2 # Upper bound of minor axis \n self.V4 = Minor * -1 + C2 #Lower bound of minor axis \n self.vertList = [self.V1,self.V2,self.V3,self.V4]\n\n return (self.vertList)\n\n def setCenter(self,ellipseOne):\n 'Set Center point of the ellipse'\n self.C1 = int(random.randint(-10,10)) #set center one \n self.C2 = int(random.randint(-10,10)) #set center two \n return (self.C1,self.C2) #return values into ellipse class \n\n def Unit_setCenter(self,ellipseOne,X,Y):\n 'Set up for unit test, to manual set center '\n print(\" Set_Center FN : set up for unit test, to manual set center \") \n self.C1 = X\n self.C2 = Y\n print(\"Center is \" + str(self.C1) + \" \" + str(self.C2))\n return (self.C1,self.C2) #return values into ellipse class \n\n def get(self):\n return (self.focli)\n\n\ndef labMenu(): #set up menu selection greet user\n 'Menu Selection screen' #docstring\n print(\"Hello there! Plese follow the below instructions. \")\n print('Enter 1 for area and circumfrence of ellipse 1. ')\n print('Enter 2 for area and circumfrence of ellipse 2. ')\n print('Enter 3 for overlap of ellipses ')\n print('Enter 4 for unit testing ')\n print('Enter 5 to exit.')\n\ndef Major_Minor():\n 'Set up Major and Minor Axis'\n final = False\n while not final:\n axisA = int(random.randint(3,15)) #random number gen\n axisB = int(random.randint(3,15)) # random number gen \n if axisA == axisB: #make sure ellipse is an ellipse not a circle so points cant equal \n axisA = int(random.randint(3,15))\n axisB = int(random.randint(3,15))\n if axisA > axisB:\n Major = axisA #set axis A as the major axis \n Minor = axisB #set Axis B as the minor axis \n final = True\n\n return Major,Minor\n\n\n\n\n\n\ndef circumference(Major,Minor):\n ' Unit test Calculate the circumference of the ellipse'\n print(\"Unit testCalculate the circumference of the ellipse\")\n\n # formula for circumference of a circle using major and minor axis \n circumference = math.pi * ( 3*(Major+Minor) - math.sqrt( (3*Major + Minor) * (Major + 3*Minor) ) )\n print(\"Circumference is \" + str(circumference))\n return round(circumference,2)\n\ndef area(Major,Minor):\n 'Calculate the area of the ellipse'\n print(\"Calculate the are of the ellipse Unit test\")\n\n area = math.pi * Major * Minor\n print(\"Area is \" + str(area))\n return round(area,2)\n\ndef pointCheck(ellipseObject):\n 'Function used to check points on ellipse, if its in bounds '\n #print(ellipseObject)\n focal1 = [ellipseObject.F1,ellipseObject.C2] # set focal point one on axis \n focal2 = [ellipseObject.F2,ellipseObject.C2] #set focal point 2 on axis \n final = False\n while not final:\n x = random.randint(ellipseObject.V2,ellipseObject.V1) #set up random point \n y = random.randint(ellipseObject.V2,ellipseObject.V1) #set up random point \n point = [x,y] #set cord \n d1 = ((point[0] - (focal1[0]))**2) + ((point[1] - (focal1[1]))**2)\n d2 = ((point[0] - (focal2[0]))**2) + ((point[1] - (focal2[1]))**2)\n\n d1 = math.sqrt(d1)\n d2 = math.sqrt(d2)\n\n dist = d1 + d2 # get distance of points add together \n if d1 + d2 == ellipseObject.Major * 2: #make sure distance of point(x,y) is same equal to sum of major axis distance \n print(\"point is good \")\n final = True \n\n\ndef checkpoint(ellipseObject,point):\n 'Function used to check if point falls into ellipse'\n E1 = 0 # set to 0 \n focal1 = [ellipseObject.F1,ellipseObject.C2] # set focal point one on axis \n focal2 = [ellipseObject.F2,ellipseObject.C2] #set focal point 2 on axis \n\n #point = [x,y] #set cord \n d1 = ((point[0] - (focal1[0]))**2) + ((point[1] - (focal1[1]))**2)\n d2 = ((point[0] - (focal2[0]))**2) + ((point[1] - (focal2[1]))**2)\n\n d1 = math.sqrt(d1)\n d2 = math.sqrt(d2)\n\n dist = d1 + d2 # get distance of points add together \n if dist <= ellipseObject.Major * 2: #make sure distance of point(x,y) is same equal to sum of major axis distance \n E1 = 1 #give value of 1 if its a match \n return E1\n\n\n\ndef boxSetUp(ellipseOne,ellipseTwo):\n 'Set up bounds of box for ellipses'\n boxMaxX = max(ellipseOne.V1,ellipseTwo.V1) # get max x vert ellipse 1 or 2 \n boxMinX= min(ellipseOne.V2,ellipseTwo.V2) # get min x vert of ellipse 1 or 2\n\n boxMaxY = max(ellipseOne.V3,ellipseTwo.V3) # get max vert of y axis \n boxMinY = min(ellipseOne.V4,ellipseTwo.V4) # get min vert of y axis \n\n xBound = [boxMaxX + 0,boxMinX - 0]\n yBound = [boxMaxY + 0, boxMinY - 0] \n\n boxArea = (abs(xBound[0]) + abs(xBound[1])) * (abs(yBound[0] + abs(yBound[1]))) #get area of the box \n\n return xBound, yBound, boxArea\n\n\ndef OverlapFn(ellipseOne,ellipseTwo,xBound, yBound, boxArea):\n 'Calculate the overlap between the two ellipses'\n n = 0 # set to 0\n hit = 0 # set to 0 for amount of times point falls within \n full = False # set while condtion to false, once it hits 10000 then its true \n\n while not full:\n point = [int(random.randint(xBound[1],xBound[0])),int(random.randint(yBound[1],yBound[0]))] # make random points within bounds of box \n #print (point)\n E1 = checkpoint(ellipseOne,point) #check and see if point falls into ellipse 1 \n E2 = checkpoint(ellipseTwo,point) #check and see if point falls into ellipse 2\n\n if E1 == 1 and E2 == 1: #point must fall into both ellipse to be true \n hit += 1 # count how many times point falls between both ellipse \n\n n += 1 # add to counter \n if n == 100000:\n full = True # once all points have been hit, make while true \n OverLapArea = (hit/boxArea) / 2 #Calculate the overlap between the ellipses hits over the box area \n\n return round(OverLapArea,2)\n#(random.randint(xBound[1],xBound[0]))\n\ndone = False\nwhile not done:\n labMenu()\n choice = int(input('Please make an entry: '))\n\n if choice == 1:\n # set up ellipse 1 \n Major, Minor = Major_Minor() # Get the major radius and minor radius axis of Ellipse \n ellipseOne = ellipse(Major,Minor) #set bounds of Major radius and Minor Axis radius \n ellipseOne.setCenter(ellipseOne) #get center point / location of ellipse \n focal = ellipseOne.setFocli(ellipseOne.Major,ellipseOne.Minor,ellipseOne.C1) #get main focal points\n ellipseOne.setMajor_Minor_Axis(ellipseOne.Major,ellipseOne.Minor,ellipseOne.C1,ellipseOne.C2) # get upper/lower bounds of axis\n areaCalc = area(ellipseOne.Major,ellipseOne.Minor) #calc the area of the ellipse \n circumferenceCalc = circumference(ellipseOne.Major,ellipseOne.Minor) # get circumference of the ellipse \n print(\"The circumference of the ellipse 1 is \"+ str(circumferenceCalc))\n print(\"The area of the ellipse 1 is \" +str(areaCalc))\n\n elif choice == 2:\n #Ellipse 2 setup\n Major, Minor = Major_Minor() # Get the major radius and minor radius axis of Ellipse \n ellipseTwo = ellipse(Major,Minor) #set bounds of Major radius and Minor Axis radius \n ellipseTwo.setCenter(ellipseTwo) #get center point / location of ellipse \n focal = ellipseTwo.setFocli(ellipseTwo.Major,ellipseTwo.Minor,ellipseTwo.C1) #get main focal points\n ellipseTwo.setMajor_Minor_Axis(ellipseTwo.Major,ellipseTwo.Minor,ellipseTwo.C1,ellipseTwo.C2) # get upper/lower bounds of axis\n areaCalc = area(ellipseTwo.Major,ellipseTwo.Minor) #calc the area of the ellipse \n circumferenceCalc = circumference(ellipseTwo.Major,ellipseTwo.Minor) # get circumference of the ellipse \n print(\"The circumference of the ellipse 2 is \"+ str(circumferenceCalc))\n print(\"The area of the ellipse 2 is \" +str(areaCalc))\n\n elif choice == 3:\n #Get ellipse 1 \n Major, Minor = Major_Minor() # Get the major radius and minor radius axis of Ellipse \n ellipseOne = ellipse(Major,Minor) #set bounds of Major radius and Minor Axis radius \n ellipseOne.setCenter(ellipseOne) #get center point / location of ellipse \n focal = ellipseOne.setFocli(ellipseOne.Major,ellipseOne.Minor,ellipseOne.C1) #get main focal points\n ellipseOne.setMajor_Minor_Axis(ellipseOne.Major,ellipseOne.Minor,ellipseOne.C1,ellipseOne.C2) # get upper/lower bounds of axis\n areaCalc = area(ellipseOne.Major,ellipseOne.Minor) #calc the area of the ellipse \n circumferenceCalc = circumference(ellipseOne.Major,ellipseOne.Minor) # get circumference of the ellipse \n print(\"The circumference of the ellipse 1 is \"+ str(circumferenceCalc))\n print(\"The area of the ellipse 1 is \" +str(areaCalc))\n\n # Get ellipse 2 \n Major, Minor = Major_Minor() # Get the major radius and minor radius axis of Ellipse \n ellipseTwo = ellipse(Major,Minor) #set bounds of Major radius and Minor Axis radius \n ellipseTwo.setCenter(ellipseTwo) #get center point / location of ellipse \n focal = ellipseTwo.setFocli(ellipseTwo.Major,ellipseTwo.Minor,ellipseTwo.C1) #get main focal points\n ellipseTwo.setMajor_Minor_Axis(ellipseTwo.Major,ellipseTwo.Minor,ellipseTwo.C1,ellipseTwo.C2) # get upper/lower bounds of axis\n areaCalc = area(ellipseTwo.Major,ellipseTwo.Minor) #calc the area of the ellipse \n circumferenceCalc = circumference(ellipseTwo.Major,ellipseTwo.Minor) # get circumference of the ellipse \n print(\"The circumference of the ellipse 2 is \"+ str(circumferenceCalc))\n print(\"The area of the ellipse 2 is \" +str(areaCalc))\n\n # set up overlap function \n xBound, yBound, boxArea = boxSetUp(ellipseOne,ellipseTwo) #grab the bounds of the box around ellipse / area as well\n\n OverLapArea = OverlapFn(ellipseOne,ellipseTwo,xBound, yBound, boxArea) #overlap function to calc overlap \n print(\"The Overlap of the two ellipses is \"+ str(OverLapArea))\n \n elif choice == 4:\n print(\"Unit test of Ellipse\")\n \n #set up small ellipse 1\n ellipseOne = ellipse(3,1) #set bounds of Major radius and Minor Axis radius unit test \n print(\"The major axis is 3 and minor axis is 1\")\n ellipseOne.Unit_setCenter(ellipseOne,0,0) #set center to 0 Unit test \n focal = ellipseOne.setFocli(ellipseOne.Major,ellipseOne.Minor,ellipseOne.C1) #get main focal points\n ellipseOne.setMajor_Minor_Axis(ellipseOne.Major,ellipseOne.Minor,ellipseOne.C1,ellipseOne.C2) # get upper/lower bounds of axis\n areaCalc = area(ellipseOne.Major,ellipseOne.Minor) #calc the area of the ellipse \n circumferenceCalc = circumference(ellipseOne.Major,ellipseOne.Minor) \n print(\"The circumference of the ellipse 1 is \"+ str(circumferenceCalc)) # print our circum of test ellipse \n print(\"The area of the ellipse 1 is \" +str(areaCalc)) #print out area of test ellipse 1 \n\n #Set up large Ellipse 2\n ellipseTwo = ellipse(9,5) #set bounds of Major radius and Minor Axis radius unit test \n print(\"The major axis is 9 and minor axis is 5\")\n ellipseTwo.Unit_setCenter(ellipseTwo,0,0) #set center to 0 Unit test \n focal = ellipseTwo.setFocli(ellipseTwo.Major,ellipseTwo.Minor,ellipseTwo.C1) #get main focal points\n ellipseTwo.setMajor_Minor_Axis(ellipseTwo.Major,ellipseTwo.Minor,ellipseTwo.C1,ellipseTwo.C2) # get upper/lower bounds of axis\n areaCalc = area(ellipseTwo.Major,ellipseTwo.Minor) #calc the area of the ellipse \n circumferenceCalc = circumference(ellipseTwo.Major,ellipseTwo.Minor) \n print(\"The circumference of the ellipse 2 is \"+ str(circumferenceCalc)) # print our circum of test ellipse 2\n print(\"The area of the ellipse 2 is \" +str(areaCalc)) #print out area of test ellipse 2\n\n\n #Set up ellipse 3 off centered \n ellipseThree = ellipse(3,1) #set bounds of Major radius and Minor Axis radius unit test \n print(\"The major axis is 3 and minor axis is 1\")\n ellipseThree.Unit_setCenter(ellipseThree,5,5) #set center to 5,5Unit test no overlap should occur\n focal = ellipseThree.setFocli(ellipseThree.Major,ellipseThree.Minor,ellipseThree.C1) #get main focal points\n ellipseThree.setMajor_Minor_Axis(ellipseThree.Major,ellipseThree.Minor,ellipseThree.C1,ellipseThree.C2) # get upper/lower bounds of axis\n areaCalc = area(ellipseThree.Major,ellipseThree.Minor) #calc the area of the ellipse \n circumferenceCalc = circumference(ellipseThree.Major,ellipseThree.Minor) \n\n print(\"The circumference of the ellipse 3 is \"+ str(circumferenceCalc)) # print our circum of test ellipse 3\n print(\"The area of the ellipse 3 is \" +str(areaCalc)) #print out area of test ellipse 3 \n\n #Set up large ellpise 4 to overlap with ellipse 2 \n ellipseFour = ellipse(11,9) #set bounds of Major radius and Minor Axis radius unit test \n print(\"The major axis is 11 and minor axis is 9\")\n ellipseFour.Unit_setCenter(ellipseFour,0,0) #set center to 0,0 Unit test \n focal = ellipseFour.setFocli(ellipseFour.Major,ellipseFour.Minor,ellipseFour.C1) #get main focal points\n ellipseFour.setMajor_Minor_Axis(ellipseFour.Major,ellipseFour.Minor,ellipseFour.C1,ellipseFour.C2) # get upper/lower bounds of axis\n areaCalc = area(ellipseFour.Major,ellipseFour.Minor) #calc the area of the ellipse \n circumferenceCalc = circumference(ellipseFour.Major,ellipseFour.Minor) \n\n print(\"The circumference of the ellipse 4 is \"+ str(circumferenceCalc)) # print our circum of test ellipse 4\n print(\"The area of the ellipse 4 is \" +str(areaCalc)) #print out area of test ellipse 4 \n \n print(\"Test Ellipse 1 and 2 overlap area Ellipse one should be within ellipse 2 \")\n #Set up Ellipse 1 and 2, see if the area of overlap = ellipse 1 \n xBound, yBound, boxArea = boxSetUp(ellipseOne,ellipseTwo) #grab the bounds of the box around ellipse / area as well\n\n OverLapArea = OverlapFn(ellipseOne,ellipseTwo,xBound, yBound, boxArea) #overlap function to calc overlap \n print(\"The Overlap of the two ellipses is \"+ str(OverLapArea))\n\n print(\"Test Ellipse 2 and 1 overlap area, see if points are similar \")\n OverLapArea = OverlapFn(ellipseTwo,ellipseOne,xBound, yBound, boxArea)\n print(\"The Overlap of the two ellipses is \"+ str(OverLapArea))\n\n print(\"test Ellipse 1 and 3, make sure that overlap area is 0, due to center being off \")\n xBound, yBound, boxArea = boxSetUp(ellipseOne,ellipseThree)\n OverLapArea = OverlapFn(ellipseOne,ellipseThree,xBound, yBound, boxArea)\n print(\"The Overlap of the two ellipses is \"+ str(OverLapArea))\n\n print(\"test Ellipse 2 and 4, check large overlap area \")\n xBound, yBound, boxArea = boxSetUp(ellipseTwo,ellipseFour)\n OverLapArea = OverlapFn(ellipseTwo,ellipseFour,xBound, yBound, boxArea)\n print(\"The Overlap of the two ellipses is \"+ str(OverLapArea))\n\n else:\n done = True \n\n","sub_path":"Assignment 4/A4_P4_SZ.py","file_name":"A4_P4_SZ.py","file_ext":"py","file_size_in_byte":16296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"167485654","text":"import uasyncio as asyncio\n\nasync def schedule(cbk, t, *args, **kwargs):\n await asyncio.sleep(t)\n cbk(*args, **kwargs)\n\ndef callback(x, y):\n print('x={} y={}'.format(x, y))\n\nasync def bar():\n asyncio.create_task(schedule(callback, 3, 42, 100))\n for count in range(6):\n print(count)\n await asyncio.sleep(1) # Pause 1s\n\nasyncio.run(bar())","sub_path":"Experimental_exercise/uasyncio_test/2.2.2 Running a callback function.py","file_name":"2.2.2 Running a callback function.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"386610329","text":"#!/usr/bin/env python3\n\n# Functions can be made available through a module by adding\n# the following code to another file.\n#\n# from wordcount import numchars, numlines, numwords\n\ndef numchars(filename='', fileobj=None):\n if not filename and not fileobj:\n raise Exception('No parameters')\n\n f = fileobj\n iopened = False\n nchars = 0\n if not f:\n if filename != '':\n f = open(filename, 'r')\n iopened = True\n else:\n raise FileNotFoundError('No filename given')\n \n f.seek(0)\n nchars = len(f.read())\n\n if iopened:\n f.close()\n\n return nchars\n\ndef numlines(filename='', fileobj=None):\n f = fileobj\n iopened = False\n nlines = 0\n if not f:\n if filename != '':\n f = open(filename, 'r')\n iopened = True\n else:\n raise FileNotFoundError('No filename given')\n \n f.seek(0)\n nlines = len(f.readlines())\n\n if iopened:\n f.close()\n\n return nlines\n\ndef numwords(filename='', fileobj=None):\n f = fileobj\n iopened = False\n nwords = 0\n if not f:\n if filename != '':\n f = open(filename, 'r')\n iopened = True\n else:\n raise FileNotFoundError('No filename given')\n \n f.seek(0)\n nwords = len(f.read().split())\n\n if iopened:\n f.close()\n\n return nwords\n\nif __name__ == '__main__':\n '''\n print(numwords(filename='test1.txt'))\n\n againf = open('test1.txt', 'r')\n print(numwords(fileobj=againf))\n againf.close()\n\n # FileNotFoundError\n print(numwords())\n\n print(numlines(filename='test1.txt'))\n\n againf = open('test1.txt', 'r')\n print(numlines(fileobj=againf))\n againf.close()\n\n # FileNotFoundError\n print(numlines())\n '''\n\n from sys import argv\n from pathlib import Path\n progname = Path(argv[0]).name\n\n if len(argv) < 2:\n print('Usage: %s ' % progname)\n exit(2)\n\n filenames = argv[1:]\n for filename in filenames:\n print('%5d %5d %5d %s' % (\n numchars(filename=filename),\n numwords(filename=filename),\n numlines(filename=filename),\n filename))\n\n","sub_path":"wordcount.py","file_name":"wordcount.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"422756900","text":"def get_elo_team(team,team_elo):\n import distance\n output_elo = 0\n \n # Fixed assign\n team_names_panda_fixed = [\"AZ\",\"Astana\",\"Asteras\",\"Rubin\",\"Sion\",\"Celtic\",\"Shakhtar Donetsk\",\"Mönchengladbach\",\"Paris\",\"Krasnodar\",\"Club Brugge\",\"Lokomotiv Moskva\",\"Qarabağ\",\"St-Étienne\",\"Sporting CP\",\"Qäbälä\",\"Plzeň\",\"Liberec\",\"Gent\",\"Athletic\"]\n team_names_elo_fixed = [\"Alkmaar\",\"FK Astana\",\"Asteras Tripolis\",\"Rubin Kazan\",\"Sion\",\"Celtic\",\"Shakhtar\",\"Gladbach\",\"Paris SG\",\"FC Krasnodar\",\"Brugge\",\"Lok Moskva\",\"Karabakh Agdam\",\"Saint-Etienne\",\"Sporting\",\"Gabala\",\"Viktoria Plzen\",\"Slovan Liberec\",\"Gent\",\"Bilbao\"]\n for k in range(len(team_names_panda_fixed)):\n if team == team_names_panda_fixed[k]:\n for j in range(len(team_elo)):\n if team_elo[j][0] == team_names_elo_fixed[k]:\n output_elo = team_elo[j][1]\n \n # Rest\n if output_elo == 0:\n for j in range(len(team_elo)):\n if distance.levenshtein(team,team_elo[j][0]) == 0:\n output_elo = team_elo[j][1]\n break\n elif distance.levenshtein(team,team_elo[j][0]) == 1:\n output_elo = team_elo[j][1]\n break\n elif distance.levenshtein(team,team_elo[j][0]) == 2:\n output_elo = team_elo[j][1]\n break\n\n return float(output_elo)","sub_path":"app_voetbalelo/uefa_leagues/get_elo_team.py","file_name":"get_elo_team.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"588156648","text":"from background_task import background\nfrom django.utils import timezone\nfrom passport_app.models import *\n\nimport psycopg2\nfrom psycopg2 import sql\nfrom psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT # <-- ADD THIS LINE\n\n# @background(schedule=1)\ndef init_classifier():\n print(\"start init classifier\")\n #classificator\n params = [\n {\n 'name':'social',\n 'point':'1.1',\n 'name_ru': \"Социальная инфраструктура\",\n 'descr': ''\n },\n\n {\n 'name': 'transport',\n 'point': '1.2',\n 'name_ru': \"Транспортная доступность\",\n 'descr': ''\n },\n {\n 'name': 'place_info',\n 'point': '1.3',\n 'name_ru': \"Характеристики местоположения\",\n 'descr': ''\n },\n {\n 'name': 'rights',\n 'point': '1.4',\n 'name_ru': \"Права и обременения\",\n 'descr': ''\n },\n {\n 'name': 'architecture',\n 'point': '1.5',\n 'name_ru': \"Архитектура и конструкции\",\n 'descr': ''\n },\n {\n 'name': 'engsys',\n 'point': '1.6',\n 'name_ru': \"Инженерные системы\",\n 'descr': ''\n },\n {\n 'name': 'base',\n 'point': '1.0',\n 'name_ru': \"Основные\",\n 'descr': ''\n },\n ]\n\n for item in params:\n classificator = Classifier(**item)\n classificator.save()\n print(\"finish init classifier\")\n\n# @background(schedule=timezone.now())\ndef init_type_of_value():\n #class TypeOfValue(models.Model):\n #name = models.CharField(max_length=255)\n print(\"start init type of value\")\n params = [\n {\n 'name': 'integer',\n 'name_ru': 'целое число'\n },\n\n {\n 'name': 'float',\n 'name_ru': 'дробное число'\n },\n {\n 'name': 'text',\n 'name_ru': 'текст'\n },\n {\n 'name': 'date',\n 'name_ru': 'дата'\n },\n {\n 'name': 'datetime',\n 'name_ru': 'дата и время'\n },\n ]\n\n for item in params:\n type_of_val = TypeOfValue(**item)\n type_of_val.save()\n print(\"finish init type of value\")\n\n\n# @background(schedule=timezone.now())\ndef init_units():\n print(\"start init unit\")\n #name = models.CharField(max_length=255)\n\n params = [\n\n ]\n\n for item in params:\n unit = Unit(**item)\n unit.save()\n print(\"finish init unit\")\n\n\n# @background(schedule=timezone.now())\ndef init_addreses():\n print(\"start init country\")\n # address\n country = Country(**{'name': 'Россия'})\n country.save()\n print(\"finish init classifier\")\n\n# @background(schedule=timezone.now())\ndef init_social_fields():\n print(\"start init fields\")\n #social\n # name = models.CharField(max_length=255)\n # title = models.CharField(max_length=255)\n # title_rus = models.CharField(max_length=255)\n # unit = models.ForeignKey(Unit, on_delete=models.CASCADE)\n # classifier = models.ForeignKey(Сlassifier, on_delete=models.CASCADE)\n params = [\n {\n 'name':'college',\n 'title':'college',\n 'title_rus': \"Высшее учебное заведение\",\n },\n\n {\n 'name': 'school',\n 'title': 'school',\n 'title_rus': \"Общеобразовательная Школа учебное заведение\",\n },\n {\n 'name': 'kindergarten',\n 'title': 'kindergarten',\n 'title_rus': \"Детский сад\",\n },\n {\n 'name': 'atheneum',\n 'title': 'library',\n 'title_rus': \"Читальный зал Билиблиотека Книги\",\n },\n\n {\n 'name': 'shop',\n 'title': 'shop',\n 'title_rus': \"Магазин\",\n },\n {\n 'name': 'domestic_service',\n 'title': 'domestic service',\n 'title_rus': \"Бытовые услуги\",\n },\n {\n 'name': 'rest_space',\n 'title': 'rest space',\n 'title_rus': \"Городской парк\",\n },\n {\n 'name': 'sport_complex',\n 'title': 'sport_complex',\n 'title_rus': \"Спортинвый комплекс\",\n },\n {\n 'name': 'sport_ground',\n 'title': 'sport ground',\n 'title_rus': \"Спортивная площадка\",\n },\n {\n 'name': 'playground',\n 'title': 'playground',\n 'title_rus': \"Детская площадка\",\n },\n {\n 'name': 'polyclinic',\n 'title': 'polyclinic',\n 'title_rus': \"Поликлиника больница\",\n },\n {\n 'name': 'mall',\n 'title': 'mall',\n 'title_rus': \"Торговый центр\",\n },\n\n {\n 'name': 'pharmacy',\n 'title': 'pharmacy',\n 'title_rus': \"Аптека\",\n },\n {\n 'name': 'cafe',\n 'title': 'cafe',\n 'title_rus': \"Пункт Общественного питания\",\n },\n {\n 'name': 'bank',\n 'title': 'bank',\n 'title_rus': \"Банк\"\n },\n {\n 'name': 'water_place',\n 'title': 'water object',\n 'title_rus': \"Водный объект\",\n },\n {\n 'name': 'theatre',\n 'title': 'theatre',\n 'title_rus': \"Театр\",\n },\n {\n 'name': 'religion_object',\n 'title': 'religion_object',\n 'title_rus': \"Религиозный объект\",\n },\n {\n 'name': 'ambulance',\n 'title': 'ambulance',\n 'title_rus': \"Подстанция скорой помощи\",\n },\n\n ]\n\n\n\n classificator = Classifier.objects.get(name='social')\n for item in params:\n field = Field(**item)\n field.classifier = classificator\n field.save()\n\n print(\"finish init fields\")\n\n# @background(schedule=timezone.now())\ndef init_transport_fields():\n print(\"start init fields\")\n #social\n # name = models.CharField(max_length=255)\n # title = models.CharField(max_length=255)\n # title_rus = models.CharField(max_length=255)\n # unit = models.ForeignKey(Unit, on_delete=models.CASCADE)\n # classifier = models.ForeignKey(Сlassifier, on_delete=models.CASCADE)\n params = [\n {\n 'name':'metro_stations',\n 'title':'metro stations',\n 'title_rus': \"Станция метро\",\n },\n {\n 'name': 'light_subway_stations',\n 'title': 'light subway stations',\n 'title_rus': \"станция МЦК\",\n },\n {\n 'name': 'stations_of_electric_trains',\n 'title': 'stations_of_electric_trains',\n 'title_rus': \"Станция электропоездов\",\n },\n {\n 'name': 'public_transport_stops',\n 'title': 'public_transport_stops',\n 'title_rus': \"Остановка общественного транспорта автобусы\",\n },\n {\n 'name': 'distance_from_the_center',\n 'title': 'distance_from_the_center',\n 'title_rus': \"Администрация города\",\n },\n {\n 'name': 'parking_spaces_for_paid_and_intercepting_parking_lots',\n 'title': 'parking_spaces_for_paid_and_intercepting_parking_lots',\n 'title_rus': \"Машиноместа платных и перехватывающих парковок\",\n },\n {\n 'name': 'transport_highways',\n 'title': 'transport_highways',\n 'title_rus': \"Транспортные магистрали\",\n },\n\n\n ]\n\n\n\n classificator = Classifier.objects.get(name='transport')\n for item in params:\n field = Field(**item)\n field.classifier = classificator\n field.save()\n\n print(\"finish init fields\")\n\n\n# @background(schedule=timezone.now())\ndef init_place_info_fields():\n print(\"start init fields\")\n #social\n # name = models.CharField(max_length=255)\n # title = models.CharField(max_length=255)\n # title_rus = models.CharField(max_length=255)\n # unit = models.ForeignKey(Unit, on_delete=models.CASCADE)\n # classifier = models.ForeignKey(Сlassifier, on_delete=models.CASCADE)\n params = [\n {\n 'name':'location',\n 'title':'location',\n 'title_rus': \"Местоположение\",\n },\n {\n 'name': 'area',\n 'title': 'area',\n 'title_rus': \"Район\",\n },\n {\n 'name': 'geology',\n 'title': 'geology',\n 'title_rus': \"Геология\",\n },\n {\n 'name': 'snap_to_the_town_plan',\n 'title': 'snap_to_the_town_plan',\n 'title_rus': \"Привязка к градостроительному плану\",\n },\n {\n 'name': 'cadastral_engineer',\n 'title': 'cadastral_engineer',\n 'title_rus': \"Кадастровый инженер\",\n },\n {\n 'name': 'cadastral_number_of_the_block',\n 'title': 'cadastral_number_of_the_block',\n 'title_rus': \"Кадастровый номер квартала\",\n },\n {\n 'name': 'data_of_the_cadastral_passport_of_the_land_plot',\n 'title': 'data_of_the_cadastral_passport_of_the_land_plot',\n 'title_rus': \"Данные кадастрового паспорта земельного участка\",\n },\n {\n 'name': 'land_category',\n 'title': 'land_category',\n 'title_rus': \"Категория земель\",\n },\n {\n 'name': 'kind_of_permitted_use',\n 'title': 'kind_of_permitted_use',\n 'title_rus': \"Вид разрешённого использования\",\n },\n {\n 'name': 'the_accuracy_of_the_boundaries_of_the_land',\n 'title': 'the_accuracy_of_the_boundaries_of_the_land',\n 'title_rus': \"Точность границ земельного участка\",\n },\n {\n 'name': 'the_area_of_the_land_plot',\n 'title': 'the_area_of_the_land_plot',\n 'title_rus': \"Площадь земельного участка, входящего в состав общего имущества в многоквартирном доме\",\n },\n {\n 'name': 'area_of_parking_within_the_boundaries_of_the_land_plot',\n 'title': 'area_of_parking_within_the_boundaries_of_the_land_plot',\n 'title_rus': \"Площадь парковки в границах земельного участка\",\n },\n {\n 'name': 'date_of_change_of_information_in_gkn',\n 'title': 'date_of_change_of_information_in_gkn',\n 'title_rus': \"Дата изменения сведений в ГКН\",\n },\n {\n 'name': 'date_of_unloading_of_information_in_gkn',\n 'title': 'date_of_unloading_of_information_in_gkn',\n 'title_rus': \"Дата выгрузки сведений из ГКН\",\n },\n {\n 'name': 'place_info_playground',\n 'title': 'place_info_playground',\n 'title_rus': \"Детская площадка\",\n },\n {\n 'name': 'place_info_sportground',\n 'title': 'place_info_sportground',\n 'title_rus': \"Спортивная площадка\",\n },\n {\n 'name': 'other_elements_of_improvement',\n 'title': 'other_elements_of_improvement',\n 'title_rus': \"Иные элементы благоустройства\",\n },\n {\n 'name': 'place_info_improvement',\n 'title': 'place_info_improvement',\n 'title_rus': \"Благоустройство\",\n },\n ]\n\n\n\n classificator = Classifier.objects.get(name='place_info')\n for item in params:\n field = Field(**item)\n field.classifier = classificator\n field.save()\n\n print(\"finish init fields\")\n\n\n\n# @background(schedule=timezone.now())\ndef init_rights_fields():\n print(\"start init fields\")\n #social\n # name = models.CharField(max_length=255)\n # title = models.CharField(max_length=255)\n # title_rus = models.CharField(max_length=255)\n # unit = models.ForeignKey(Unit, on_delete=models.CASCADE)\n # classifier = models.ForeignKey(Сlassifier, on_delete=models.CASCADE)\n params = [\n {\n 'name':'special_conditions_for_the_use_of_land',\n 'title':'special_conditions_for_the_use_of_land',\n 'title_rus': \"Особые условия использования земельных участков\",\n },\n {\n 'name': 'special_conditions_for_environmental_protection',\n 'title': 'special_conditions_for_environmental_protection',\n 'title_rus': \"Особые условия охраны окружающей среды\",\n },\n {\n 'name': 'information_on_the_inclusion_of_a_property_in_the_register_of_cultural_heritage_sites',\n 'title': 'information_on_the_inclusion_of_a_property_in_the_register_of_cultural_heritage_sites',\n 'title_rus': \"Сведения о включении объекта недвижимости в реестр объектов культурного наследия\",\n },\n {\n 'name': 'other_special_conditions_of_use',\n 'title': 'other_special_conditions_of_use',\n 'title_rus': \"Иные особые условия использования\",\n },\n {\n 'name': 'name_of_the_managing_organization',\n 'title': 'name_of_the_managing_organization',\n 'title_rus': \"Наименование управляющей организации\",\n },\n {\n 'name': 'location_address',\n 'title': 'location_address',\n 'title_rus': \"Адрес местоположения\",\n },\n {\n 'name': 'rights_head_of_organization',\n 'title': 'rights_head_of_organization',\n 'title_rus': \"Глава организации\",\n },\n {\n 'name': 'contact_number',\n 'title': 'contact_phone',\n 'title_rus': \"Контактный телефон\",\n },\n {\n 'name': 'email',\n 'title': 'email',\n 'title_rus': \"Почта\",\n },\n {\n 'name': 'official_website_of_the_company',\n 'title': 'site',\n 'title_rus': \"Официальный сайт компании\",\n },\n {\n 'name': 'management_start_date',\n 'title': 'management_start_date',\n 'title_rus': \"Дата начала управления\",\n },\n {\n 'name': 'management_document',\n 'title': 'management_document',\n 'title_rus': \"Основание управления\",\n },\n {\n 'name': 'date_and_number_document',\n 'title': 'date_and_number_document',\n 'title_rus': \"Дата и номер документа\",\n },\n {\n 'name': 'date_of_contract',\n 'title': 'date_of_contract',\n 'title_rus': \"Дата заключения договора\",\n },\n {\n 'name': 'rate',\n 'title': 'rate',\n 'title_rus': \"Тариф\",\n },\n {\n 'name': 'information_disclosure',\n 'title': 'information_disclosure',\n 'title_rus': \"Раскрытие информации\",\n },\n {\n 'name': 'overhaul_schedule',\n 'title': 'overhaul_schedule',\n 'title_rus': \"График капитального ремонта\",\n },\n {\n 'name': 'method_of_formation_of_the_capital_repair_fund',\n 'title': 'method_of_formation_of_the_capital_repair_fund',\n 'title_rus': \"Способ формирования фонда капитального ремонта\",\n },\n {\n 'name': 'inn_account_owner',\n 'title': 'inn_account_owner',\n 'title_rus': \"ИНН владельца специального счета\",\n },\n {\n 'name': 'amount_of_the_contribution_for_capital_repairs',\n 'title': 'amount_of_the_contribution_for_capital_repairs',\n 'title_rus': \"Размер взноса на капитальный ремонт\",\n },\n {\n 'name': 'date_number_protocol',\n 'title': 'date_number_protocol',\n 'title_rus': \"Дата и номер протокола собраний владельцев\",\n },\n {\n 'name': 'extra_info',\n 'title': 'extra_info',\n 'title_rus': \"Дополнительная информация\",\n },\n {\n 'name': 'collected_means_of_owners_of_all',\n 'title': 'collected_means_of_owners_of_all',\n 'title_rus': \"Собрано средств собственников всего\",\n },\n {\n 'name': 'current_debt_of_owners_on_contributions',\n 'title': 'current_debt_of_owners_on_contributions',\n 'title_rus': \"Текущая задолженность собственников по взносам\",\n },\n {\n 'name': 'spent_on_work',\n 'title': 'spent_on_work',\n 'title_rus': \"Израсходовано на работы\",\n },\n {\n 'name': 'including_spent_subsidies',\n 'title': 'including_spent_subsidies',\n 'title_rus': \"В т.ч. израсходовано субсидий\",\n },\n {\n 'name': 'balance_of_funds_for_overhauling',\n 'title': 'balance_of_funds_for_overhauling',\n 'title_rus': \"Остаток средств на проведение капремонта\",\n },\n {\n 'name': 'planned_works',\n 'title': 'planned_works',\n 'title_rus': \"Запланировано работ\",\n },\n {\n 'name': 'completed_work',\n 'title': 'completed_work',\n 'title_rus': \"Выполнено работ\",\n },\n {\n 'name': 'year_of_nearest_work',\n 'title': 'year_of_nearest_work',\n 'title_rus': \"Год ближайшей работы\",\n },\n {\n 'name': 'management_report',\n 'title': 'management_report',\n 'title_rus': \"Отчёт по управлению\",\n },\n {\n 'name': 'management_reports_archive',\n 'title': 'management_reports_archive',\n 'title_rus': \"Архив отчетов по управлению\",\n },\n {\n 'name': 'debts_of_owners_before_the_criminal_code',\n 'title': 'debts_of_owners_before_the_criminal_code',\n 'title_rus': \"Задолженность собственников перед УК\",\n },\n\n ]\n\n\n\n classificator = Classifier.objects.get(name='rights')\n for item in params:\n field = Field(**item)\n field.classifier = classificator\n field.save()\n\n print(\"finish init fields\")\n\n\n# @background(schedule=timezone.now())\ndef init_architecture_fields():\n print(\"start init fields\")\n #social\n # name = models.CharField(max_length=255)\n # title = models.CharField(max_length=255)\n # title_rus = models.CharField(max_length=255)\n # unit = models.ForeignKey(Unit, on_delete=models.CASCADE)\n # classifier = models.ForeignKey(Сlassifier, on_delete=models.CASCADE)\n params = [\n {\n 'name':'cadastral_number_of_the_building',\n 'title':'cadastral_number_of_the_building',\n 'title_rus': \"Кадастровый номер здания\",\n },\n {\n 'name': 'cadastral_value_of_the_building',\n 'title': 'cadastral_value_of_the_building',\n 'title_rus': \"Кадастровая стоимость здания\",\n },\n {\n 'name': 'date_of_cadastral_registration',\n 'title': 'date_of_cadastral_registration',\n 'title_rus': \"Дата постановки на кадастровый учёт\",\n },\n {\n 'name': 'architecture_date_of_change_of_information_in_gkn',\n 'title': 'date_of_unloading_of_information_in_gkn',\n 'title_rus': \"Дата изменения сведений в ГКН\",\n },\n {\n 'name': 'architecture_date_of_unloading_of_information_in_gkn',\n 'title': 'date_of_unloading_of_information_in_gkn',\n 'title_rus': \"Дата выгрузки сведений из ГКН\",\n },\n {\n 'name': 'year_of_construction',\n 'title': 'year_of_construction',\n 'title_rus': \"Год постройки\",\n },\n {\n 'name': 'year_of_commissioning',\n 'title': 'metro stations',\n 'title_rus': \"Год ввода в эксплуатацию\",\n },\n {\n 'name': 'total_area',\n 'title': '',\n 'title_rus': \"Общая площадь\",\n },\n {\n 'name': 'total_area_of_living_quarters',\n 'title': '',\n 'title_rus': \"Общая площадь жилых помещений\",\n },\n {\n 'name': 'total_area_of_non_residential_premises',\n 'title': '',\n 'title_rus': \"Общая площадь нежилых помещений\",\n },\n {\n 'name': 'total_area_of_premises_included_in_the_total_property',\n 'title': '',\n 'title_rus': \"Общая площадь помещений, входящих в состав общего имущества\",\n },\n {\n 'name': 'number_of_storeys',\n 'title': '',\n 'title_rus': \"Этажность\",\n },\n {\n 'name': 'number_of_residential_premises',\n 'title': '',\n 'title_rus': \"Количество жилых помещений\",\n },\n {\n 'name': 'number_of_unresidential_premises',\n 'title': '',\n 'title_rus': \"Количество нежилых помещений\",\n },\n {\n 'name': 'underground_floors',\n 'title': '',\n 'title_rus': \"Подземных этажей\",\n },\n {\n 'name': 'functional_purpose_of_the_capital_construction_object',\n 'title': '',\n 'title_rus': \"Функциональное назначение объекта капитального строительства\",\n },\n {\n 'name': 'series_building_type',\n 'title': '',\n 'title_rus': \"Серия, тип постройки здания\",\n },\n {\n 'name': 'type_of_house',\n 'title': '',\n 'title_rus': \"Тип дома\",\n },\n {\n 'name': 'the_house_is_recognized_as_an_emergency',\n 'title': '',\n 'title_rus': \"Дом признан аварийным\",\n },\n {\n 'name': 'type_of_foundation',\n 'title': '',\n 'title_rus': \"Тип фундамента\",\n },\n {\n 'name': 'floor_type',\n 'title': '',\n 'title_rus': \"Тип перекрытий\",\n },\n {\n 'name': 'material_of_bearing_walls',\n 'title': '',\n 'title_rus': \"Материал несущих стен\",\n },\n {\n 'name': 'basement',\n 'title': '',\n 'title_rus': \"Подвал\",\n },\n {\n 'name': 'basement_area',\n 'title': '',\n 'title_rus': \"Площадь подвала\",\n },\n {\n 'name': 'number_of_entrances',\n 'title': '',\n 'title_rus': \"Количество подъездов\",\n },\n {\n 'name': 'facade_type',\n 'title': '',\n 'title_rus': \"Тип фасада\",\n },\n {\n 'name': 'roof_type',\n 'title': '',\n 'title_rus': \"Тип крыши\",\n },\n {\n 'name': 'roofing_type',\n 'title': '',\n 'title_rus': \"Тип кровли\",\n },\n {\n 'name': 'garbage_chute',\n 'title': '',\n 'title_rus': \"Мусоропровод\",\n },\n {\n 'name': 'type_of_garbage_chute',\n 'title': '',\n 'title_rus': \"Тип мусоропровода\",\n },\n {\n 'name': 'number_of_garbage_chutes',\n 'title': '',\n 'title_rus': \"Количество мусоропроводов\",\n },\n {\n 'name': 'object_wear',\n 'title': '',\n 'title_rus': \"Износ объекта\",\n },\n {\n 'name': 'conformity_of_the_building_with_ecological_gost_r_54964-2012',\n 'title': '',\n 'title_rus': \"Соответствие здания экологическому ГОСТ Р 54964-2012\",\n },\n {\n 'name': 'inclusiveness',\n 'title': '',\n 'title_rus': \"Инклюзивность\",\n },\n\n\n ]\n\n\n\n classificator = Classifier.objects.get(name='architecture')\n for item in params:\n field = Field(**item)\n field.classifier = classificator\n field.save()\n\n print(\"finish init fields\")\n\n\n# @background(schedule=timezone.now())\ndef init_engsys_fields():\n print(\"start init fields\")\n #social\n # name = models.CharField(max_length=255)\n # title = models.CharField(max_length=255)\n # title_rus = models.CharField(max_length=255)\n # unit = models.ForeignKey(Unit, on_delete=models.CASCADE)\n # classifier = models.ForeignKey(Сlassifier, on_delete=models.CASCADE)\n params = [\n {\n 'name':'external_networks',\n 'title':'',\n 'title_rus': \"Внешние сети\",\n },\n {\n 'name': 'project_documentation',\n 'title': '',\n 'title_rus': \"Проектная документация\",\n },\n {\n 'name': 'technical_documentation',\n 'title': '',\n 'title_rus': \"Техническая документация\",\n },\n {\n 'name': 'energy_efficiency_class',\n 'title': '',\n 'title_rus': \"Класс энергетической эффективности\",\n },\n {\n 'name': 'power_supply_system',\n 'title': '',\n 'title_rus': \"Система электроснабжения\",\n },\n {\n 'name': 'type_of_power_supply_system',\n 'title': '',\n 'title_rus': \"Тип системы электроснабжения\",\n },\n {\n 'name': 'number_of_entries_in_the_house',\n 'title': '',\n 'title_rus': \"Количество вводов в дом\",\n },\n {\n 'name': 'the_fact_of_providing_the_supply_system_service',\n 'title': '',\n 'title_rus': \"Факт предоставления услуги\",\n },\n {\n 'name': 'supply_system_rate',\n 'title': '',\n 'title_rus': \"Тариф\",\n },\n {\n 'name': 'unit_of_supply_system_measurement',\n 'title': '',\n 'title_rus': \"Единица измерения\",\n },\n {\n 'name': 'the_person_who_supplies_the_communal_supply_system_resource',\n 'title': '',\n 'title_rus': \"Лицо, осуществляющее поставку коммунального ресурса\",\n },\n {\n 'name': 'date_of_installation_of_the_supply_meter',\n 'title': '',\n 'title_rus': \"Дата установки прибора учёта\",\n },\n {\n 'name': 'type_of_supply_meter',\n 'title': '',\n 'title_rus': \"Тип прибора учёта\",\n },\n {\n 'name': 'date_of_verification_replacement_of_the_supply_meter',\n 'title': '',\n 'title_rus': \"Дата поверки / замены прибора учёта\",\n },\n {\n 'name': 'heat_supply_system',\n 'title': '',\n 'title_rus': \"Система теплоснабжения\",\n },\n {\n 'name': 'type_of_heat_supply_system',\n 'title': '',\n 'title_rus': \"Тип системы теплоснабжения\",\n },\n {\n 'name': 'the_fact_of_providing_the_heat_supply_service',\n 'title': '',\n 'title_rus': \"Факт предоставления услуги\",\n },\n {\n 'name': 'unit_of_heat_supply_measurement',\n 'title': '',\n 'title_rus': \"Единица измерения\",\n },\n {\n 'name': 'the_person_who_supplies_the_communal_heat_supply_resource',\n 'title': '',\n 'title_rus': \"Лицо, осуществляющее поставку коммунального ресурса\",\n },\n {\n 'name': 'date_of_installation_of_the_heat_supply_meter',\n 'title': '',\n 'title_rus': \"Дата установки прибора учёта\",\n },\n {\n 'name': 'type_of_heat_supply_meter',\n 'title': '',\n 'title_rus': \"Тип прибора учёта\",\n },\n {\n 'name': 'date_of_verification_replacement_of_the_heat_supply_meter',\n 'title': '',\n 'title_rus': \"Дата поверки / замены прибора учёта\",\n },\n {\n 'name': 'hot_water_system',\n 'title': '',\n 'title_rus': \"Система горячего водоснабжения\",\n },\n {\n 'name': 'type_of_hot_water_system',\n 'title': '',\n 'title_rus': \"Тип системы горячего водоснабжения\",\n },\n {\n 'name': 'the_fact_of_providing_the_hot_water_service',\n 'title': '',\n 'title_rus': \"Факт предоставления услуги\",\n },\n {\n 'name': 'hot_water_rate',\n 'title': '',\n 'title_rus': \"Тариф\",\n },\n {\n 'name': 'unit_of_hot_water_measurement',\n 'title': '',\n 'title_rus': \"Единица измерения\",\n },\n {\n 'name': 'the_person_who_supplies_the_communal_hot_water_resource',\n 'title': '',\n 'title_rus': \"Лицо, осуществляющее поставку коммунального ресурса\",\n },\n {\n 'name': 'date_of_installation_of_the_hot_water_meter',\n 'title': '',\n 'title_rus': \"Дата установки прибора учёта\",\n },\n {\n 'name': 'type_of_hot_water_meter',\n 'title': '',\n 'title_rus': \"Тип прибора учёта\",\n },\n {\n 'name': 'date_of_verification_replacement_of_the_hot_water_meter',\n 'title': '',\n 'title_rus': \"Дата поверки / замены прибора учёта\",\n },\n {\n 'name': 'cold_water_system',\n 'title': '',\n 'title_rus': \"Система холодного водоснабженияs\",\n },\n {\n 'name': 'type_of_cold_water_supply_system',\n 'title': '',\n 'title_rus': \"Тип системы холодного водоснабжения\",\n },\n {\n 'name': 'the_fact_of_providing_the_cold_water_service',\n 'title': '',\n 'title_rus': \"Факт предоставления услуги\",\n },\n {\n 'name': 'unit_of_cold_water_measurement',\n 'title': '',\n 'title_rus': \"Единица измерения\",\n },\n {\n 'name': 'the_person_who_supplies_the_communal_cold_water_resource',\n 'title': '',\n 'title_rus': \"Лицо, осуществляющее поставку коммунального ресурса\",\n },\n {\n 'name': 'date_of_verification_replacement_of_the_cold_water_metermeter',\n 'title': '',\n 'title_rus': \"Дата поверки / замены прибора учёта\",\n },\n {\n 'name': 'type_of_cold_water_meter',\n 'title': '',\n 'title_rus': \"Тип прибора учёта\",\n },\n {\n 'name': 'water_disposal_system',\n 'title': '',\n 'title_rus': \"Система водоотведения\",\n },\n {\n 'name': 'type_of_sewerage_system',\n 'title': '',\n 'title_rus': \"Тип системы водоотведения\",\n },\n {\n 'name': 'the_fact_of_providing_the_disposal_service',\n 'title': '',\n 'title_rus': \"Факт предоставления услуги\",\n },\n {\n 'name': 'disposal_rate',\n 'title': '',\n 'title_rus': \"Тариф\",\n },\n {\n 'name': 'unit_of_disposal_measurement',\n 'title': '',\n 'title_rus': \"Единица измерения\",\n },\n {\n 'name': 'the_person_who_supplies_the_communal_disposal_resource',\n 'title': '',\n 'title_rus': \"Лицо, осуществляющее поставку коммунального ресурса\",\n },\n {\n 'name': 'date_of_installation_of_the_disposal_meter',\n 'title': '',\n 'title_rus': \"Дата установки прибора учёта\",\n },\n {\n 'name': 'type_of_disposal_meter',\n 'title': '',\n 'title_rus': \"Тип прибора учёта\",\n },\n {\n 'name': 'date_of_verification_replacement_of_the_disposal_meter',\n 'title': '',\n 'title_rus': \"Дата поверки / замены прибора учёта\",\n },\n {\n 'name': 'volume_of_cesspools',\n 'title': '',\n 'title_rus': \"Объем выгребных ям\",\n },\n {\n 'name': 'gutter_system',\n 'title': '',\n 'title_rus': \"Система водостоков\",\n },\n {\n 'name': 'gutter_system_type',\n 'title': '',\n 'title_rus': \"Тип системы водостоков\",\n },\n {\n 'name': 'gas_supply_system',\n 'title': '',\n 'title_rus': \"Система газоснабжения\",\n },\n {\n 'name': 'type_of_gas_supply_system',\n 'title': '',\n 'title_rus': \"Тип системы газоснабжения\",\n },\n {\n 'name': 'the_fact_of_providing_the_gas_service',\n 'title': '',\n 'title_rus': \"Факт предоставления услуги\",\n },\n {\n 'name': 'gas_supply_system_rate',\n 'title': '',\n 'title_rus': \"Тариф\",\n },\n {\n 'name': 'unit_of_gas_measurement',\n 'title': '',\n 'title_rus': \"Единица измерения\",\n },\n {\n 'name': 'the_person_who_supplies_the_communal_gas_resource',\n 'title': '',\n 'title_rus': \"Лицо, осуществляющее поставку коммунального ресурса\",\n },\n {\n 'name': 'date_of_installation_of_the_gas_meter',\n 'title': '',\n 'title_rus': \"Дата установки прибора учёта\",\n },\n {\n 'name': 'type_of_gas_meter',\n 'title': '',\n 'title_rus': \"Тип прибора учёта\",\n },\n {\n 'name': 'date_of_verification_replacement_of_the_gas_meter',\n 'title': '',\n 'title_rus': \"Дата поверки / замены прибора учёта\",\n },\n {\n 'name': 'ventilation_system',\n 'title': '',\n 'title_rus': \"Система вентиляции\",\n },\n {\n 'name': 'type_of_ventilation_system',\n 'title': '',\n 'title_rus': \"Тип системы вентиляции\",\n },\n {\n 'name': 'air_conditioning_system',\n 'title': '',\n 'title_rus': \"Система кондиционирования\",\n },\n {\n 'name': 'weak_system',\n 'title': '',\n 'title_rus': \"Слаботочная система\",\n },\n {\n 'name': 'lifting_equipment',\n 'title': '',\n 'title_rus': \"Подъёмное оборудование\",\n },\n {\n 'name': 'type_of_lift',\n 'title': '',\n 'title_rus': \"Тип лифта\",\n },\n {\n 'name': 'number_of_elevators',\n 'title': '',\n 'title_rus': \"Количество лифтов\",\n },\n {\n 'name': 'year_of_commissioning_of_the_lift_system',\n 'title': '',\n 'title_rus': \"Год ввода в эксплуатацию лифтовой системы\",\n },\n {\n 'name': 'integrated_security_system',\n 'title': '',\n 'title_rus': \"Система комплексной безопасности\",\n },\n {\n 'name': 'video_surveillance',\n 'title': '',\n 'title_rus': \"Видеонаблюдение\",\n },\n {\n 'name': 'fencing',\n 'title': '',\n 'title_rus': \"Ограждение\",\n },\n {\n 'name': 'barrier',\n 'title': '',\n 'title_rus': \"Шлагбаум\",\n },\n {\n 'name': 'integrated_fire_protection_system',\n 'title': '',\n 'title_rus': \"Система комплексной противопожарной защиты\",\n },\n {\n 'name': 'fire_extinguishing_system',\n 'title': '',\n 'title_rus': \"система пожаротушения\",\n },\n {\n 'name': 'type_fire_extinguishing_system',\n 'title': '',\n 'title_rus': \"Тип системы пожаротушения\",\n },\n {\n 'name': 'distance_to_fire_station',\n 'title': '',\n 'title_rus': \"Расстояние до пожарной части\",\n },\n\n ]\n\n\n\n classificator = Classifier.objects.get(name='engsys')\n for item in params:\n field = Field(**item)\n field.classifier = classificator\n field.save()\n\n print(\"finish init fields\")\n\n# @background(schedule=timezone.now())\ndef create_config():\n print (\"create config\")\n try:\n count = SearchConfig.objects.count()\n if count == 0:\n search_config = SearchConfig()\n search_config.save()\n except Exception as e:\n print(str(e))\n pass\n\ndef move_data_to_category():\n #разделы\n\n razdel = Category()\n razdel.name = \"razdel\"\n razdel.point = \"1.0\"\n razdel.comment = \"\"\n razdel.name_ru = \"Раздел\"\n razdel.save()\n\n root_category = Category()\n root_category.name = \"category\"\n root_category.point = \"1.0\"\n root_category.comment = \"\"\n root_category.name_ru = \"Категория\"\n root_category.save()\n\n classifiers = Classifier.objects.all()\n\n for classifier in classifiers:\n try:\n category = Category()\n category.name = classifier.name\n category.point = classifier.point\n category.comment = classifier.descr\n category.name_ru = classifier.name_ru\n category.save()\n category.parent_categories.add(razdel)\n category.save()\n \n razdel.categories.add(category)\n razdel.save()\n except Exception as e:\n print(str(e))\n pass\n\n fields = Field.objects.all()\n\n for item in fields:\n try:\n category = Category()\n category.name = item.name \n category.name_ru = item.title_rus \n category.save()\n if item.classifier:\n classifier_item = Category.objects.filter(name__exact = item.classifier.name)\n if classifier_item: \n print ( \"classifier_item %i\" % classifier_item.count()) \n print ( classifier_item ) \n category.parent_categories.add(classifier_item[0])\n classifier_item[0].categories.add(category)\n classifier_item[0].save()\n else:\n print (\"not found classifier %s\" % item.classifier.name )\n category.save()\n \n # parserparameter = ParserParameter()\n # parserparameter.name = item.name \n \n # # parameter.name_ru = item.title_rus \n # # parameter.unit = item.unit \n\n # parserparameter.save()\n # # category.parameters.add(parameter)\n # category.save()\n\n # field_data = DataField.objects.filter(field = item)\n # for field_data_item in field_data:\n # print (\"try save data parametter\")\n # data_parameter = ParserParameterData()\n # data_parameter.value = field_data_item.value \n # data_parameter.real_estate = field_data_item.real_estate\n # data_parameter.parser_parameter = parserparameter \n # data_parameter.save()\n # print (\"save data parametter\")\n\n except Exception as e:\n print(str(e))\n pass\n\n typeofrealestates = TypeOfRealEstate.objects.all()\n\n for item in typeofrealestates:\n try:\n category = Category()\n category.name = item.name\n category.name_ru = item.title_rus \n category.save()\n category.parent_categories.add(root_category)\n category.save()\n root_category.categories.add(category)\n root_category.save()\n except Exception as e:\n print(str(e))\n pass\n\n subtypeofrealestates = SubtypeOfRealEstate.objects.all()\n\n for item in subtypeofrealestates:\n try:\n category = Category()\n category.name = item.name\n category.name_ru = item.title_rus\n category.save()\n if item.type:\n type_categories = Category.objects.filter(name__exact = item.type.name)\n if type_categories:\n print ( \"type_categories %i \" % type_categories.count())\n print ( type_categories )\n category.parent_categories.add(type_categories[0])\n type_categories[0].categories.add(category)\n type_categories[0].save()\n else:\n print (\"not found type %s\" % item.type.name )\n\n category.save()\n except Exception as e:\n print(str(e))\n pass\n\n subsubtypeofrealestates = SubsubtypeOfRealEstate.objects.all()\n\n for item in subsubtypeofrealestates:\n try:\n category = Category()\n category.name = item.name\n category.name_ru = item.title_rus\n category.save()\n if item.subtype: \n subtype_categories = Category.objects.filter(name = item.subtype.name)\n if subtype_categories:\n print ( \"subtype_categories %i \" % subtype_categories.count())\n print ( subtype_categories )\n category.parent_categories.add(subtype_categories[0])\n subtype_categories[0].categories.add(category) \n subtype_categories[0].save() \n else:\n print (\"not found subtype %s\" % item.subtype.name )\n category.save()\n except Exception as e:\n print(str(e))\n pass\n \n\n subsubsubtypeofrealestates = SubsubsubtypeOfRealEstate.objects.all()\n\n for item in subsubsubtypeofrealestates:\n try:\n category = Category()\n category.name = item.name\n category.name_ru = item.title_rus\n category.save()\n if item.subsubtype:\n subsubtype_categories = Category.objects.filter(name = item.subsubtype.name)\n if subsubtype_categories:\n print ( \"subsubtype_categories %i \" % subsubtype_categories.count())\n print ( subsubtype_categories )\n category.parent_categories.add(subsubtype_categories[0])\n subsubtype_categories[0].categories.add(category) \n subsubtype_categories[0].save() \n else:\n print (\"not found subsubtype %s\" % item.subsubtype.name )\n category.save()\n except Exception as e:\n print(str(e))\n pass\n \n\ndef create_parser_types():\n print(\"create parser types...\")\n parser_type = ParserType()\n parser_type.name = \"google_map\"\n parser_type.name_ru = \"google map\"\n parser_type.save()\n\n\n parser_type = ParserType()\n parser_type.name = \"yandex_map\"\n parser_type.name_ru = \"yandex map\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"yandex_transport\"\n parser_type.name_ru = \"yandex transport\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"wiki_routes\"\n parser_type.name_ru = \"wiki routes\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"rosreestr.ru\"\n parser_type.name_ru = \"rosreestr.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"reformagkh.ru\"\n parser_type.name_ru = \"reformagkh.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"dom.gosuslugi.ru\"\n parser_type.name_ru = \"dom.gosuslugi.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"greenpatrol.ru\"\n parser_type.name_ru = \"greenpatrol.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"ecofactor.ru\"\n parser_type.name_ru = \"ecofactor.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"kartasvalok.ru\"\n parser_type.name_ru = \"kartasvalok.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"fssprus.ru\"\n parser_type.name_ru = \"fssprus.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"egrul.nalog.ru\"\n parser_type.name_ru = \"egrul.nalog.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"sudrf.ru\"\n parser_type.name_ru = \"sudrf.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"notariat.ru\"\n parser_type.name_ru = \"notariat.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"genproc.gov.ru\"\n parser_type.name_ru = \"genproc.gov.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"мвд.рф\"\n parser_type.name_ru = \"мвд.рф\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"mchs.gov.ru\"\n parser_type.name_ru = \"mchs.gov.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"rosinv.ru/o-predpriyatii\"\n parser_type.name_ru = \"rosinv.ru/o-predpriyatii\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"bti-moscow.ru\"\n parser_type.name_ru = \"bti-moscow.ru\"\n parser_type.save()\n\n parser_type = ParserType()\n parser_type.name = \"mobti.ru\"\n parser_type.name_ru = \"mobti.ru\"\n parser_type.save()\n\n print(\"finished\")\n\ndef create_parser_parameters():\n print(\"create parser parameters...\")\n fields = Field.objects.all()\n for item in fields:\n try:\n \n parserparameter = ParserParameter()\n parserparameter.name = item.name \n \n parserparameter.name_ru = item.title_rus\n parserparameter.parser_type = ParserType.objects.get(id = item.parser_type+1)\n parserparameter.save()\n\n field_data = DataField.objects.filter(field = item)\n for field_data_item in field_data:\n print (\"try save data parametter\")\n data_parameter = ParserParameterData()\n data_parameter.value = field_data_item.value\n data_parameter.real_estate = field_data_item.real_estate\n data_parameter.parser_parameter = parserparameter\n data_parameter.save()\n print (\"save data parameter\")\n\n except Exception as e:\n print(str(e))\n pass\n print(\"finished\")\n\ndef create_formula():\n print(\"create empty formulas\")\n categories = Category.objects.all()\n for category in categories:\n try: \n print (\"try save data category formula\") \n category_formula = FormulaCategory() \n category_formula.category = category\n category_formula.value = \"FV_%i\" % (category.id,)\n category_formula.rate = \"FR_%i\" % (category.id,)\n category_formula.formula = \"FF_%i\" % (category.id,)\n category_formula.save()\n print (\"save data category formula\")\n print (category.parameters)\n if category.parameters.exists():\n for parameter in category.parameters.all():\n print (\"try save data parametter formula\")\n parameter_formula = FormulaParameterCategory()\n parameter_formula.category = category\n parameter_formula.parameter = parameter\n parameter_formula.value_label = \"PV_%i_%i\" % (parameter.id,category.id,)\n parameter_formula.rate_label = \"PR_%i_%i\" % (parameter.id,category.id,)\n parameter_formula.formula_label = \"PF_%i_%i\" % (parameter.id,category.id,)\n parameter_formula.value = \"PV_%i_%i\" % (parameter.id,category.id,)\n parameter_formula.rate = \"PR_%i_%i\" % (parameter.id,category.id,) \n parameter_formula.save()\n print (\"save data parametter formula\")\n\n except Exception as e:\n print(str(e))\n break\n print(\"finished\")\n\ndef create_default_search_form():\n # if not SearchForm.objects.get(name = 'default'):\n search_form = SearchForm()\n search_form.name = 'default'\n search_form.name_ru = 'Стандартный'\n search_form.user = User.objects.get(id = 1)\n search_form.save()\n search_form.categories.set(Category.objects.all())\n \n search_form.save()\n\n\n\ndef init_db():\n con = psycopg2.connect(dbname='postgres',\n user='postgres', host='',\n password='postgres')\n\n con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) # <-- ADD THIS LINE\n\n cur = con.cursor()\n\n # Use the psycopg2.sql module instead of string concatenation \n # in order to avoid sql injection attacs.\n cur.execute(sql.SQL(\"CREATE DATABASE {}\").format(\n sql.Identifier('db_passport'))\n )\n\ndef create_yandex_parameter():\n parser_type = ParserType.objects.filter(name = \"google_map\").first()\n parser_type_yandex = ParserType.objects.filter(name = \"yandex_map\").first()\n parser_parameters = ParserParameter.objects.filter(parser_type = parser_type)\n print(\"create_yandex_parameter\")\n #print(parser_type.name)\n #print(parser_type_yandex.name)\n\n for item in parser_parameters:\n parserparameter = ParserParameter()\n parserparameter.name = item.name +\"yandex\" \n parserparameter.name_ru = item.name_ru \n parserparameter.parser_type = parser_type_yandex\n parserparameter.parser_parameter_type = item.parser_parameter_type\n parserparameter.save()\n\ndef tasks():\n print(\"tasks\")\n # init_classifier()\n # init_addreses()\n # init_units()\n #\n # init_type_of_value()\n # init_social_fields()\n # init_transport_fields()\n # init_place_info_fields()\n # init_architecture_fields()\n # init_rights_fields()\n #\n # init_engsys_fields()\n # create_config()\n # move_data_to_category()\n # create_parser_types()\n # create_parser_parameters()\n # create_formula()\n # init_db()\n create_default_search_form()\n # create_yandex_parameter()\n # #create_gkh_parameter()\n\n print(\"finish tasks\")\n\n\n","sub_path":"passport_app/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":54851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"330202560","text":"import os\r\nimport time\r\n\r\nfrom openstack import connection\r\n\r\n\r\n\r\n# Please put the endpoints which are not the native OpenStack services.\r\n_endpoints = {\r\n 'OS_DMS_ENDPOINT_OVERRIDE': 'https://dms.eu-de.otc.t-systems.com:443/v1.0/%(project_id)s/',\r\n 'OS_LOAD_BALANCER_ENDPOINT_OVERRIDE': 'https://elb.eu-de.otc.t-systems.com:443/v1.0/%(project_id)s',\r\n 'OS_RDS_ENDPOINT_OVERRIDE': 'https://rds.eu-de.otc.t-systems.com:443/v1.0/%(project_id)s',\r\n 'OS_SMN_ENDPOINT_OVERRIDE': 'https://smn.eu-de.otc.t-systems.com:443/v1.0/%(project_id)s'\r\n}\r\n\r\n_auth = {\r\n 'auth_url': \"https://iam.eu-de.otc.t-systems.com:443/v3\",\r\n 'project_id': 'YOUR-PROJECT-ID',\r\n 'user_domain_id': 'YOUR-DOMAIN-ID',\r\n 'username': 'YOUR-USER-NAME',\r\n 'password': 'YOUR-PASSWORD'\r\n}\r\n\r\n\r\ndef create_queue(conn, queue_name):\r\n queue_obj = None\r\n queues = conn.dms.queues()\r\n for each in queues:\r\n if 0 != cmp(each.name, queue_name):\r\n pass\r\n else:\r\n queue_obj = each\r\n break\r\n\r\n # create a new one\r\n if queue_obj is None:\r\n queue_param = {\r\n 'name': queue_name,\r\n 'description': 'This is a dms demo queue.'\r\n }\r\n queue_obj = conn.dms.create_queue(**queue_param)\r\n else:\r\n pass\r\n\r\n # for debug\r\n #print(queue_obj)\r\n return queue_obj\r\n\r\n\r\ndef create_groups(conn, queue):\r\n print(\"create groups on queue %s\", queue)\r\n groups_new = [\"dms-group-01\"]\r\n\r\n # check if the new groups are already exist.\r\n groups = conn.dms.groups(queue)\r\n groups_exist = [grp.name for grp in groups]\r\n groups_add = list(set(groups_new) - set(groups_exist))\r\n if 0 < len(groups_add):\r\n grps_params = {\"groups\": [{\"name\": i} for i in groups_add ]}\r\n print(conn.dms.create_groups(queue, **grps_params))\r\n else:\r\n pass\r\n\r\n\r\ndef delete_groups(conn, queue):\r\n print(\"delete all groups on queue %s\", queue)\r\n for g in conn.dms.groups(queue):\r\n print(g)\r\n conn.dms.delete_group(queue, g)\r\n\r\n\r\ndef produce_message(conn, queue):\r\n print(\"send message on a queue %s\", queue)\r\n msg_dict = {\r\n \"messages\": [\r\n {\r\n \"body\": \"TEST11\",\r\n \"attributes\":\r\n {\r\n \"attribute1\": \"value1\",\r\n \"attribute2\": \"value2\"\r\n }\r\n }\r\n ]\r\n }\r\n\r\n msgs = conn.dms.send_messages(queue, **msg_dict)\r\n #print(\"send messages %s\" % msgs)\r\n\r\n\r\ndef consume_message(conn, queue):\r\n grps = conn.dms.groups(queue)\r\n\r\n for grp in grps:\r\n print(\"=========consumed message by group %s start...\" % grp.name)\r\n csm_msgs = conn.dms.consume_message(queue, grp.id)\r\n for cm in csm_msgs:\r\n print(\"*****ack consumed message %s\" % cm)\r\n print(conn.dms.ack_consumed_message(cm))\r\n print(\"=========consumed message by group %s end.\" % grp.name)\r\n\r\n\r\ndef consume_message_with_tags(conn, qui, gid):\r\n \"\"\"Consume message by tag list in queue and group\"\"\"\r\n #qid = '673f8fca-9aa1-4974-8fc5-b0eb1c5f9724'\r\n #gid = 'g-a826e437-2e67-46c7-b220-63836b5bb463'\r\n params = {\r\n 'max_msgs': 10,\r\n 'time_wait': 30,\r\n 'tags': ['tag1', 'tag2'],\r\n 'tag_type': 'or'\r\n }\r\n\r\n for c in conn.dms.consume_message(qui, gid, **params):\r\n print(c)\r\n\r\n\r\ndef get_quotas(conn):\r\n for q in conn.dms.quotas():\r\n print(q)\r\n\r\n\r\ndef main():\r\n # set the endpoints\r\n for edp_key in _endpoints:\r\n #print(edp_key, _endpoints[edp_key])\r\n os.environ.setdefault(edp_key, _endpoints[edp_key])\r\n\r\n # connect to OTC\r\n conn = connection.Connection(**_auth)\r\n\r\n queue_name = 'dms-demo-queue'\r\n queue_obj = create_queue(conn, queue_name)\r\n create_groups(conn, queue_obj)\r\n\r\n produce_message(conn, queue_obj)\r\n consume_message(conn, queue_obj)\r\n\r\n get_quotas(conn)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n\r\n\r\n","sub_path":"example-dms.py","file_name":"example-dms.py","file_ext":"py","file_size_in_byte":3990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"52822411","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\n\nimport radical.utils as ru\nimport radical.pilot as rp\n\n\n# This script has to run as a task within an pilot allocation, and is\n# a demonstration of a task overlay within the RCT framework.\n# It will:\n#\n# - create a master which bootstraps a specific communication layer\n# - insert n workers into the pilot (again as a task)\n# - perform RPC handshake with those workers\n# - send RPC requests to the workers\n# - terminate the worker\n#\n# The worker itself is an external program which is not covered in this code.\n\n\n# ------------------------------------------------------------------------------\n#\nclass MyMaster(rp.task_overlay.Master):\n '''\n This class provides the communication setup for the task overlay: it will\n set up the request / response communication queues and provide the endpoint\n information to be forwarded to the workers.\n '''\n\n # --------------------------------------------------------------------------\n #\n def __init__(self, cfg):\n\n # initialize the task overlay base class. That base class will ensure\n # proper communication channels to the pilot agent.\n rp.task_overlay.Master.__init__(self, cfg=cfg)\n\n\n # --------------------------------------------------------------------------\n #\n def create_work_items(self):\n\n self._prof.prof('create_start')\n\n world_size = self._cfg.n_masters\n rank = self._cfg.rank\n print('=== 2 : ', self._cfg.rank)\n\n # create an initial list of work items to be distributed to the workers.\n # Work items MUST be serializable dictionaries.\n idx = rank\n total = int(eval(self._cfg.workload.total))\n while idx < total:\n\n uid = 'request.%06d' % idx\n print('=== uid:', uid)\n item = {'uid' : uid,\n 'mode': 'call',\n 'data': {'method': 'hello',\n 'kwargs': {'count': idx,\n 'uid' : uid}}}\n self.request(item)\n idx += world_size\n\n self._prof.prof('create_stop')\n\n\n # --------------------------------------------------------------------------\n #\n def result_cb(self, requests):\n\n # result callbacks can return new work items\n new_requests = list()\n for r in requests:\n sys.stdout.write('result_cb %s: %s [%s]\\n' % (r.uid, r.state, r.result))\n sys.stdout.flush()\n\n # count = r.work['data']['kwargs']['count']\n # if count < 10:\n # new_requests.append({'mode': 'call',\n # 'data': {'method': 'hello',\n # 'kwargs': {'count': count + 100}}})\n\n return new_requests\n\n\n# ------------------------------------------------------------------------------\n#\nif __name__ == '__main__':\n\n # This master script runs as a task within a pilot allocation. The purpose\n # of this master is to (a) spawn a set or workers within the same\n # allocation, (b) to distribute work items (`hello` function calls) to those\n # workers, and (c) to collect the responses again.\n cfg_fname = str(sys.argv[1])\n cfg = ru.Config(cfg=ru.read_json(cfg_fname))\n cfg.rank = int(sys.argv[2])\n print('=== 1 : ', cfg.rank)\n\n n_nodes = cfg.nodes\n cpn = cfg.cpn\n gpn = cfg.gpn\n descr = cfg.worker_descr\n worker = os.path.basename(cfg.worker)\n pwd = os.getcwd()\n\n # add data staging to worker: link input_dir, impress_dir, and oe_license\n descr['arguments'] = [os.path.basename(worker)]\n descr['input_staging'] = [\n {'source': '%s/%s' % (pwd, worker),\n 'target': worker,\n 'action': rp.COPY,\n 'flags' : rp.DEFAULT_FLAGS,\n 'uid' : 'sd.0'},\n {'source': '%s/%s' % (pwd, cfg_fname),\n 'target': cfg_fname,\n 'action': rp.COPY,\n 'flags' : rp.DEFAULT_FLAGS,\n 'uid' : 'sd.1'},\n ]\n\n # one node is used by master. Alternatively (and probably better), we could\n # reduce one of the worker sizes by one core. But it somewhat depends on\n # the worker type and application workload to judge if that makes sense, so\n # we leave it for now.\n print('workers: ', (n_nodes / cfg.n_masters) - 1)\n n_workers = int((n_nodes / cfg.n_masters) - 1)\n\n # create a master class instance - this will establish communication to the\n # pilot agent\n master = MyMaster(cfg)\n\n # insert `n` worker tasks into the agent. The agent will schedule (place)\n # those workers and execute them. Insert one smaller worker (see above)\n # NOTE: this assumes a certain worker size / layout\n master.submit(descr=descr, count=n_workers, cores=cpn, gpus=gpn)\n master.submit(descr=descr, count=1, cores=cpn - 1, gpus=gpn)\n\n # wait until `m` of those workers are up\n # This is optional, work requests can be submitted before and will wait in\n # a work queue.\n # master.wait(count=nworkers)\n\n master.run()\n\n # simply terminate\n # FIXME: clean up workers\n\n\n# ------------------------------------------------------------------------------\n\n","sub_path":"examples/misc/task_overlay_master.py","file_name":"task_overlay_master.py","file_ext":"py","file_size_in_byte":5515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"82069621","text":"# -*- coding:UTF-8 -*-\nimport cv2\nfrom PIL import Image\nimport os\nimport shutil\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport math\nimport glob\n\nindex = 0\n\n\ndef show(img):\n global index\n index += 1\n if len(img.shape) == 3:\n image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n plt.title(index)\n plt.imshow(image)\n plt.show()\n if len(img.shape) == 2:\n plt.title(index)\n plt.imshow(img, cmap=plt.gray())\n plt.show()\n\n\ndef find_image_cbox(img):\n img = img.copy()\n img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 4)\n img = cv2.bitwise_not(img)\n cropped_box = find_image_bbox(img)\n return cropped_box\n\n\ndef find_image_bbox(img):\n height = img.shape[0]\n width = img.shape[1]\n v_sum = np.sum(img, axis=0)\n h_sum = np.sum(img, axis=1)\n left = 0\n right = width - 1\n top = 0\n low = height - 1\n # 从左往右扫描,遇到非零像素点就以此为字体的左边界\n for i in range(width):\n if v_sum[i] > 0:\n left = i\n break\n # 从右往左扫描,遇到非零像素点就以此为字体的右边界\n for i in range(width - 1, -1, -1):\n if v_sum[i] > 0:\n right = i\n break\n # 从上往下扫描,遇到非零像素点就以此为字体的上边界\n for i in range(height):\n if h_sum[i] > 0:\n top = i\n break\n # 从下往上扫描,遇到非零像素点就以此为字体的下边界\n for i in range(height - 1, -1, -1):\n if h_sum[i] > 0:\n low = i\n break\n return left, top, right, low\n\n\ndef same_scale(cv2_img, max_width, max_height):\n cur_height, cur_width = cv2_img.shape[:2]\n ratio_w = float(max_width) / float(cur_width)\n ratio_h = float(max_height) / float(cur_height)\n ratio = min(ratio_w, ratio_h)\n\n new_size = (min(int(cur_width * ratio), max_width),\n min(int(cur_height * ratio), max_height))\n\n new_size = (max(new_size[0], 1),\n max(new_size[1], 1),)\n resized_img = cv2.resize(cv2_img, new_size)\n return resized_img\n\n\ndef same_scale2(cv2_img, max_size):\n cur_height, cur_width = cv2_img.shape[:2]\n ratio_h = float(max_size) / float(cur_height)\n new_width = int(cur_width*ratio_h)\n if new_width == 0:\n new_width = 1\n resized_img = cv2.resize(cv2_img, (new_width, max_size))\n return resized_img\n\n\ndef img_crop2(img):\n img = img.copy()\n left, upper, right, lower = find_image_bbox(img)\n img = img[upper: lower + 1, left: right + 1]\n return img\n\n\n\nTARGET_SIZE = 48\n\n\nclass OcrSpliter(object):\n def __init__(self):\n self.num = 0\n\n def DegreeTrans(self,theda):\n return theda / np.pi * 180\n\n def getNewSize(self,img, angle):\n q_height, q_width = img.shape[0], img.shape[1]\n angle = angle * math.pi / 180.0\n s = math.fabs(math.sin(angle))\n c = math.fabs(math.cos(angle))\n width = int((q_height * s + q_width * c) / 4) * 4\n height = int((q_height * c + q_width * s) / 4) * 4\n return width, height\n\n def rotate(self, img, rotate):\n img = img.copy()\n b, g, r = img[5, 5]\n height, width = img.shape[0], img.shape[1]\n if rotate != 0:\n M = cv2.getRotationMatrix2D(((width - 1) / 2.0, (height - 1) / 2.0), rotate, 1.0)\n new_width, new_height = self.getNewSize(img, rotate)\n img = cv2.warpAffine(img, M, (new_width, new_height), borderValue=(int(b), int(g), int(r)))\n return img\n\n def get_x_y(self, x, y, angle):\n angle = angle * math.pi / 180.0\n x1 = x + math.sqrt(x ** 2 + y ** 2) * math.sin(angle)\n y1 = y\n return [x1, y1]\n\n def line_detection(self, image):\n src = image.copy()\n img_r = src.copy()\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n # show(gray)\n edges = cv2.Canny(gray, 50, 150, apertureSize=3)\n # show(edges)\n lines = cv2.HoughLines(edges, 1, np.pi / 180, 160)\n if lines is not None:\n sum = 0\n for line in lines:\n rho, theta = line[0]\n sum += theta\n # show(image)\n avg = sum / len(lines)\n angle = self.DegreeTrans(avg) - 90\n # print(angle)\n img_r = self.rotate(src, angle)\n # show(img_r)\n padding = 30\n img = np.ones([img_r.shape[0], img_r.shape[1] + padding * 2, 3], dtype=np.uint8) * 255\n img[:, padding:padding+img_r.shape[1]] = img_r\n # show(img)\n height, width = img.shape[0], img.shape[1]\n p1 = [0, 0]\n p2 = [int((width - 1)/2), int((height-1)/2)]\n p3 = [0, height - 1]\n matSrc = np.float32([p1,p2,p3]) # 需要注意的是 行列 和 坐标 是不一致的\n img_src = img\n\n def get_count(angle):\n matDst = np.float32(\n [self.get_x_y(p1[0], p1[1], angle), p2,\n self.get_x_y(p3[0], p3[1], -angle)])\n matAffine = cv2.getAffineTransform(matSrc, matDst) # mat 1 src 2 dst 形成组合矩阵\n img = cv2.warpAffine(img_src, matAffine, (img_src.shape[1], img_src.shape[0]), borderValue=(255, 255, 255))\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (4, 4))\n img = cv2.erode(img, kernel)\n # show(img)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # show(img)\n ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_OTSU)\n # show(img)\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (4, 4))\n img = cv2.erode(img, kernel)\n # show(img)\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))\n img = cv2.dilate(img, kernel)\n # show(img)\n img = cv2.bitwise_not(img)\n # show(img)\n img, _ = img_crop2(img)\n h, w = img.shape[0], img.shape[1]\n count = 0\n for i in range(w):\n for j in range(h):\n if img[j, i] == 255:\n count += 1\n break\n if count == 0:\n count = 10000\n return count\n\n flag = True\n left = -10\n right = 10\n now = 0\n left_count = get_count(left)\n now_count = get_count(now)\n right_count = get_count(right)\n if left_count > now_count and right_count > now_count:\n flag = False\n\n if flag:\n left = -30\n right = 30\n now = 0\n while left <= right-1:\n left_count = get_count(left)\n now_count = get_count(now)\n right_count = get_count(right)\n if left_count < now_count and right_count < now_count:\n if abs(left_count - now_count) > abs(right_count - now_count):\n right = now\n now = (left + right) / 2\n else:\n left = now\n now = (left + right) / 2\n elif left_count < now_count:\n right = now\n now = (left + right) / 2\n elif right_count < now_count:\n left = now\n now = (left + right) / 2\n else:\n left += 2\n right -= 2\n\n rigth_angle = now\n print('rigth_angle:', rigth_angle)\n\n if rigth_angle == 0:\n return img_r\n else:\n matDst = np.float32(\n [self.get_x_y(p1[0], p1[1], rigth_angle), p2,\n self.get_x_y(p3[0], p3[1], -rigth_angle)])\n matAffine = cv2.getAffineTransform(matSrc, matDst) # mat 1 src 2 dst 形成组合矩阵\n img = cv2.warpAffine(img_src, matAffine, (img_src.shape[1], img_src.shape[0]), borderValue=(255, 255, 255))\n return img\n\n # def ocr_split(self, path):\n # src = cv2.imread(path)\n # src = same_scale(src,200,30)\n # # show(src)\n # # pure_name = os.path.basename(path).split('.')[0]\n # # dir_name = os.path.join('images', pure_name)\n # # shutil.rmtree(dir_name, ignore_errors=True)\n # # os.mkdir(dir_name)\n # img = src.copy()\n # img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_OTSU)\n # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))\n # img = cv2.erode(img, kernel)\n # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))\n # img = cv2.dilate(img, kernel)\n # img = cv2.bitwise_not(img)\n # img = img_padding(img)\n # # show(img)\n # img = img_crop2(img)\n # img = same_scale(img, 200, 30)\n # _, img = cv2.threshold(img, 127,255, cv2.THRESH_BINARY)\n # img = img_padding(img)\n # # show(img)\n # # src = src[top:bottom + 1, left:right + 1]\n # # src = same_scale(src, 400, 60)\n # # show(src)\n # return img\n\n def ocr_split(self, path, img_src=None):\n if img_src is not None:\n src = img_src.copy()\n else:\n src = cv2.imread(path)\n src = same_scale(src, 200, 30)\n # show(src)\n # pure_name = os.path.basename(path).split('.')[0]\n # dir_name = os.path.join('images', pure_name)\n # shutil.rmtree(dir_name, ignore_errors=True)\n # os.mkdir(dir_name)\n # img = src.copy()\n # img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n img = src[:, :, 2]\n # show(img)\n ret, img = cv2.threshold(img, 127, 255, cv2.THRESH_OTSU)\n # show(img)\n # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))\n # img = cv2.dilate(img, kernel)\n # kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))\n # img = cv2.erode(img, kernel)\n img = cv2.bitwise_not(img)\n img = img_padding(img)\n # show(img)\n img = img_crop2(img)\n img = same_scale(img, 200, 30)\n _, img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)\n img = img_padding(img)\n # show(img)\n # src = src[top:bottom + 1, left:right + 1]\n # src = same_scale(src, 400, 60)\n # show(src)\n return img\n\n\n\n\ndef img_padding(img):\n TARGET_HEIGHT = 30\n TARGET_WIDTH = 200\n left = TARGET_WIDTH - img.shape[1] - 1\n top = TARGET_HEIGHT - img.shape[0] - 1\n if left < 0 and top < 0:\n return img\n final_img = np.zeros((TARGET_HEIGHT, TARGET_WIDTH), dtype=np.uint8)\n # if left<=0:\n # start_x=0\n # else:\n # start_x = int(left / 2)\n start_x = 0\n if top<=0:\n start_y=0\n else:\n start_y = int(top / 2)\n img_h, img_w = img.shape[0], img.shape[1]\n final_img[start_y:start_y + img_h, start_x:start_x + img_w] = img\n return final_img\n\n\n\n\n# spliter = OcrSpliter()\n#\n#\n# path = 'IMG_20181120_145731_21.jpg'\n# spliter.ocr_split(path)\n\n\n# paths = glob.glob('images/*.*g')\n# print(len(paths))\n# for i, path in enumerate(paths):\n# spliter.ocr_split(path)\n","sub_path":"slim/ocr_price_utils.py","file_name":"ocr_price_utils.py","file_ext":"py","file_size_in_byte":11261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"343315026","text":"# -*- coding: utf-8 -*-\nfrom django import forms\nfrom django.contrib import admin\nfrom tinymce.widgets import TinyMCE\n\nfrom bumerang.apps.news.models import NewsCategory, NewsItem\n\n\nclass NewsCategoryAdmin(admin.ModelAdmin):\n prepopulated_fields = {\"slug\": (\"title\",)}\n\n\nclass NewsItemForm(forms.ModelForm):\n class Meta:\n model = NewsItem\n widgets = {\n 'text': TinyMCE(attrs={'cols': 80, 'rows': 30}),\n 'preview_text': TinyMCE(attrs={'cols': 80, 'rows': 30})\n }\n\n\nclass NewsItemAdmin(admin.ModelAdmin):\n form = NewsItemForm\n prepopulated_fields = {\"slug\": (\"title\",)}\n\n\nadmin.site.register(NewsCategory, NewsCategoryAdmin)\nadmin.site.register(NewsItem, NewsItemAdmin)\n","sub_path":"bumerang/apps/news/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"232818694","text":"from turtle import Screen, Turtle\nfrom random import randint\n\ns = Screen()\ns.setup(560,560)\ns.title(\"A drunken turtle collecting ...\")\n\ns.tracer(False)\nwriter = Turtle(visible=False)\nwriter.penup()\nwriter.goto(0, -275)\n\ncoins = []\nfor i in range(-4,5):\n for j in range(-4, 5):\n if i == j == 0:\n continue\n c = Turtle(shape=\"circle\")\n c.color(\"\", \"orange\")\n c.shapesize(0.5)\n c.goto(40*i, 40*j)\n coins.append(c)\ns.tracer(True)\n\nDRUNKENNESS = 45 \nt = Turtle(shape=\"turtle\")\nt.color(\"black\",\"\")\npoints = 0\nwhile abs(t.xcor()) < 200 and abs(t.ycor()) < 200:\n t.forward(5)\n t.right(randint(-DRUNKENNESS, DRUNKENNESS))\n found = None\n for c in coins:\n if t.distance(c) < 10:\n found = c\n break\n if found:\n found.hideturtle()\n coins.remove(found)\n t.shapesize(1+points/5., outline=1+points)\n points += 1\n\nwriter.write(\"{0} points\".format(points),\n align=\"center\", font=('Arial', 24, 'bold'))","sub_path":"visoes_1/programas/tartaruga_1/rqndom_walk.py","file_name":"rqndom_walk.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"586253369","text":"# coding=utf-8\n# Copyright 2017 The Tensor2Tensor Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Collect trajectories from interactions of agent with environment.\"\"\"\n\nimport tensorflow as tf\n\n\ndef define_collect(policy_factory, batch_env, config):\n \"\"\"Collect trajectories.\"\"\"\n memory_shape = [config.epoch_length] + [batch_env.observ.shape.as_list()[0]]\n memories_shapes_and_types = [\n # observation\n (memory_shape + [batch_env.observ.shape.as_list()[1]], tf.float32),\n (memory_shape, tf.float32), # reward\n (memory_shape, tf.bool), # done\n (memory_shape + batch_env.action_shape, tf.float32), # action\n (memory_shape, tf.float32), # pdf\n (memory_shape, tf.float32), # value function\n ]\n memory = [tf.Variable(tf.zeros(shape, dtype), trainable=False)\n for (shape, dtype) in memories_shapes_and_types]\n cumulative_rewards = tf.Variable(\n tf.zeros(config.num_agents, tf.float32), trainable=False)\n\n should_reset_var = tf.Variable(True, trainable=False)\n reset_op = tf.cond(should_reset_var,\n lambda: batch_env.reset(tf.range(config.num_agents)),\n lambda: 0.0)\n with tf.control_dependencies([reset_op]):\n reset_once_op = tf.assign(should_reset_var, False)\n\n with tf.control_dependencies([reset_once_op]):\n\n def step(index, scores_sum, scores_num):\n \"\"\"Single step.\"\"\"\n # Note - the only way to ensure making a copy of tensor is to run simple\n # operation. We are waiting for tf.copy:\n # https://github.com/tensorflow/tensorflow/issues/11186\n obs_copy = batch_env.observ + 0\n actor_critic = policy_factory(tf.expand_dims(obs_copy, 0))\n policy = actor_critic.policy\n action = policy.sample()\n postprocessed_action = actor_critic.action_postprocessing(action)\n simulate_output = batch_env.simulate(postprocessed_action[0, ...])\n pdf = policy.prob(action)[0]\n with tf.control_dependencies(simulate_output):\n reward, done = simulate_output\n done = tf.reshape(done, (config.num_agents,))\n to_save = [obs_copy, reward, done, action[0, ...], pdf,\n actor_critic.value[0]]\n save_ops = [tf.scatter_update(memory_slot, index, value)\n for memory_slot, value in zip(memory, to_save)]\n cumulate_rewards_op = cumulative_rewards.assign_add(reward)\n agent_indices_to_reset = tf.where(done)[:, 0]\n with tf.control_dependencies([cumulate_rewards_op]):\n scores_sum_delta = tf.reduce_sum(\n tf.gather(cumulative_rewards, agent_indices_to_reset))\n scores_num_delta = tf.count_nonzero(done, dtype=tf.int32)\n with tf.control_dependencies(save_ops + [scores_sum_delta,\n scores_num_delta]):\n reset_env_op = batch_env.reset(agent_indices_to_reset)\n reset_cumulative_rewards_op = tf.scatter_update(\n cumulative_rewards, agent_indices_to_reset,\n tf.zeros(tf.shape(agent_indices_to_reset)))\n with tf.control_dependencies([reset_env_op,\n reset_cumulative_rewards_op]):\n return [index + 1, scores_sum + scores_sum_delta,\n scores_num + scores_num_delta]\n\n init = [tf.constant(0), tf.constant(0.0), tf.constant(0)]\n index, scores_sum, scores_num = tf.while_loop(\n lambda c, _1, _2: c < config.epoch_length,\n step,\n init,\n parallel_iterations=1,\n back_prop=False)\n mean_score = tf.cond(tf.greater(scores_num, 0),\n lambda: scores_sum / tf.cast(scores_num, tf.float32),\n lambda: 0.)\n printing = tf.Print(0, [mean_score, scores_sum, scores_num], \"mean_score: \")\n with tf.control_dependencies([printing]):\n return tf.identity(index), memory\n","sub_path":"tensor2tensor/rl/collect.py","file_name":"collect.py","file_ext":"py","file_size_in_byte":4350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"145862291","text":"import pgzrun # 导入游戏库\nimport random # 导入随机库\n\nWIDTH = 350 # 设置窗口的宽度\nHEIGHT = 600 # 设置窗口的高度\n\nbackground = Actor('background') # 导入背景图片\nbird = Actor('bird') # 导入小鸟图片\nbird.x = 50 # 设置小鸟的x坐标\nbird.y = HEIGHT/2 # 设置小鸟的y坐标\nbar_up = Actor('bar_up') # 导入障碍物上半部分图片\nbar_up.x = 300 # 设置障碍物上半部分的x坐标\nbar_up.y = 0 # 设置障碍物上半部分的y坐标\nbar_down = Actor('bar_down') # 导入障碍物下半部分图片\nbar_down.x = 300 # 设置障碍物下半部分的x坐标\nbar_down.y = 600 # 设置障碍物下半部分的y坐标\n\n\ndef draw(): # 绘制模块,每帧重复执行\n background.draw() # 绘制背景\n bar_up.draw() # 绘制障碍物上半部分\n bar_down.draw() # 绘制障碍物下半部分\n bird.draw() # 绘制小鸟\n\n\ndef update(): # 更新模块,每帧重复操作\n bird.y = bird.y + 2 # 小鸟y坐标增加,即缓慢下落\n bar_up.x = bar_up.x - 2 # 障碍物上半部分缓慢向左移动\n bar_down.x = bar_down.x - 2 # 障碍物下半部分缓慢向左移动\n # 当障碍物移动到最左边时,让其在最右边重新出现\n if bar_up.x < 0:\n bar_up.x = WIDTH\n bar_down.x = WIDTH\n bar_up.y = random.randint(-200, 200) # 障碍物上半部分上下随机出现\n bar_down.y = 600 + bar_up.y # 上、下部分的障碍物中间空隙高度固定\n\ndef on_mouse_down(): # 当鼠标点击时运行\n bird.y = bird.y - 100 # 小鸟y坐标减少,即上升一段距离\n\npgzrun.go() # 开始执行游戏","sub_path":"PygameZero/python游戏趣味编程代码/第5章/5-4-4.py","file_name":"5-4-4.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"556018383","text":"import sqlite3\n\nvalues = ((\"Jean-Baptiste Zorg\", \"Human\", 122), (\"Korben Dallas\", \"Meat Popssicle\", 100), (\"Ak'not\", \"Mangalore\", -5))\n\nwith sqlite3.connect(\":memory:&db\") as conn:\n c = conn.cursor()\n c.execute(\"DROP TABLE IF EXISTS Roster\")\n c.execute(\"CREATE TABLE Roster(Name TEXT, Species TEXT, IQ INT)\")\n c.executemany(\"INSERT INTO Roster VALUES(?, ?, ?)\", values) #This inserts all the data in the list to the database\n c.execute(\"UPDATE Roster SET Species = ? WHERE Name = ? AND IQ = ?\", (\"Human\", \"Korben Dallas\", 100)) \n c.execute(\"SELECT Name, IQ FROM Roster WHERE Species is 'Human'\")\n for row in c.fetchall():\n print(row)\n","sub_path":"RAMdd.py","file_name":"RAMdd.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"337666845","text":"#!/usr/bin/env python3\n\nimport os\nSCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))\nFILENAME = '{}/../input.txt'.format(SCRIPT_PATH)\n\n\ndef get_file(name=FILENAME):\n with open(name) as input_file:\n return input_file.read()\n\n\ndef next_index(after, removed):\n n = after + 1\n while n in removed:\n n += 1\n return n\n\n\ndef prev_index(before, removed):\n prev = before - 1\n while prev in removed:\n prev -= 1\n if prev < 0:\n prev = next_index(prev, removed)\n return prev\n\n\noriginal_puzzle = get_file()\n\navailable_units = set()\nfor unit in original_puzzle.lower():\n available_units.add(unit)\n\nsmallest_size = len(original_puzzle)\nfor unit in available_units:\n puzzle = original_puzzle\n lower_puzzle = puzzle.lower()\n removed_elements = set()\n\n unit_upper = unit.upper()\n for index, p in enumerate(puzzle):\n if p in (unit, unit_upper):\n removed_elements.add(index)\n\n cur_index = next_index(-1, removed_elements)\n\n while cur_index < len(puzzle) - 1:\n compare_index = next_index(cur_index, removed_elements)\n if compare_index >= len(puzzle):\n break\n\n if lower_puzzle[cur_index] == lower_puzzle[compare_index] and puzzle[cur_index] != puzzle[compare_index]:\n removed_elements.add(cur_index)\n removed_elements.add(compare_index)\n cur_index = prev_index(cur_index, removed_elements)\n continue\n\n cur_index = next_index(cur_index, removed_elements)\n\n puzzle_size = len(puzzle) - len(removed_elements)\n if puzzle_size < smallest_size:\n smallest_size = puzzle_size\n\nprint('The shortest polymer you can produce is:', smallest_size)\n","sub_path":"2018/day_05/python/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"368466031","text":"from socket import *\n#创建tcp套接字\ns=socket()\ns.bind(('0.0.0.0',10000))\ns.listen(5)\nwhile True:\n c,addr=s.accept()\n print('connect from',addr)\n\n data=c.recv(4096)\n print('*****************')\n print(data)#浏览器发来的http请求\n print('*****************')\n\n #组织响应内容\n data='''HTTP/1.1 200 ok\n Content-Encoding: gzip\n Content-Type: text/html\n\n
Welcome to tedu
\n '''\n c.send(data.encode())\n c.close()\n\ns.close()","sub_path":"网络/pythonNet/day2/http.py","file_name":"http.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"237464075","text":"from PyQt4.Qsci import QsciLexerCPP,QsciStyle,QsciScintilla, QsciLexerJavaScript\nfrom PyQt4.QtCore import QString\nfrom PyQt4.QtGui import QFont, QColor\nfrom globals import config\n\nclass Squirrel(QsciLexerJavaScript):\n words1 = [\n 'base','break','case','catch','class','clone',\n 'continue','const','default','delete','else','enum',\n 'extends','for','foreach','function',' if',' in',\n 'local','null','resume','return','switch','this',\n 'throw','try','typeof','while','yield','constructor',\n 'instanceof','true','false','static'\n ]\n \n words2 = [\n 'init', 'dest', 'onLoad', 'onDispose', 'onGainedFocus','onMotionEvent',\n 'onLostFocus','onUpdate','onFps','onKeyEvent','onSensorEvent',\n 'onControlEvent','onDrawFrame','onError','onLowMemory','onNetCallBack'\n ]\n\n words3 = [\n 'rawdelete', 'rawin', 'array', 'seterrorhandler', 'setdebughook',\n 'enabledebuginfo', 'getroottable', 'setroottable', 'getconsttable',\n 'setconsttable', 'assert', 'print', 'compilestring', 'collectgarbage',\n 'type', 'getstackinfos', 'newthread', 'tofloat', 'tostring',\n 'tointeger', 'tochar', 'weakref', 'slice', 'find', 'tolower',\n 'toupper', 'len', 'rawget', 'rawset', 'clear', 'append', 'push',\n 'extend', 'pop', 'top', 'insert', 'remove', 'resize', 'sort',\n 'reverse', 'call', 'pcall', 'acall', 'pacall', 'bindenv', 'instance',\n 'getattributes', 'getclass', 'getstatus', 'ref'\n ]\n \n def __init__(self,parent):\n QsciLexerJavaScript.__init__(self, parent)\n self.parent = parent\n self.plainFont = QFont()\n self.plainFont.setFamily(config.fontName())\n self.plainFont.setFixedPitch(True)\n self.plainFont.setPointSize(config.fontSize())\n self.boldFont = QFont(self.plainFont)\n self.boldFont.setBold(True)\n self.setFoldCompact(True)\n \n def setColors(self, editStyle):\n self.base = QColor(editStyle[\"base\"]) #This is the font color\n self.back = QColor(editStyle[\"back\"]) #This is the bg color\n self.comment = QColor(editStyle[\"comment\"])\n self.number = QColor(editStyle[\"number\"])\n self.keyword = QColor(editStyle[\"keyword\"])\n self.string = QColor(editStyle[\"string\"])\n self.operator = QColor(editStyle[\"operator\"])\n self.styles = [\n #index description color paper font eol \n QsciStyle(0, QString(\"base\"), self.base, self.back, self.plainFont, True),\n QsciStyle(1, QString(\"comment\"), self.comment, self.back, self.plainFont, True),\n QsciStyle(4, QString(\"number\"), self.number, self.back, self.plainFont, True),\n QsciStyle(5, QString(\"Keyword\"), self.keyword, self.back, self.boldFont, True),\n QsciStyle(6, QString(\"String\"), self.string,self.back, self.plainFont, True),\n QsciStyle(10, QString(\"Operator\"), self.operator, self.back, self.plainFont, False) \n ]\n \n def language(self):\n return 'Squirrel'\n \n def foldCompact(self):\n return self._foldcompact\n\n def setFoldCompact(self, enable):\n self._foldcompact = bool(enable)\n\n def description(self, ix):\n for i in self.styles:\n if i.style() == ix:\n return i.description()\n return QString(\"\")\n \n def defaultColor(self, ix):\n for i in self.styles:\n if i.style() == ix:\n return i.color()\n return QsciLexerCPP.defaultColor(self, ix)\n\n def defaultFont(self, ix):\n for i in self.styles:\n if i.style() == ix:\n return i.font()\n return QsciLexerCPP.defaultFont(self, ix)\n\n def defaultPaper(self, ix):\n for i in self.styles:\n if i.style() == ix:\n return i.paper()\n return QsciLexerCPP.defaultPaper(self, ix)\n\n def defaultEolFill(self, ix):\n for i in self.styles:\n if i.style() == ix:\n return i.eolFill()\n return QsciLexerCPP.defaultEolFill(self, ix)\n \n'''\n def styleText(self, start, end):\n editor = self.editor()\n if editor is None:\n return\n SCI = editor.SendScintilla\n GETFOLDLEVEL = QsciScintilla.SCI_GETFOLDLEVEL\n SETFOLDLEVEL = QsciScintilla.SCI_SETFOLDLEVEL\n HEADERFLAG = QsciScintilla.SC_FOLDLEVELHEADERFLAG\n LEVELBASE = QsciScintilla.SC_FOLDLEVELBASE\n NUMBERMASK = QsciScintilla.SC_FOLDLEVELNUMBERMASK\n WHITEFLAG = QsciScintilla.SC_FOLDLEVELWHITEFLAG\n INDIC_SET = QsciScintilla.SCI_INDICSETSTYLE\n INDIC_SETCURRENT = QsciScintilla.SCI_SETINDICATORCURRENT\n INDIC_FILL = QsciScintilla.SCI_INDICATORFILLRANGE\n INDIC_CLEAR = QsciScintilla.SCI_INDICATORCLEARRANGE\n INDIC_START = QsciScintilla.SCI_INDICATORSTART\n INDIC_END = QsciScintilla.SCI_INDICATOREND\n \n # using indicator 7 with Boxed style\n SCI(INDIC_SET, 7 ,QsciScintilla.INDIC_BOX)\n SCI(INDIC_SETCURRENT, 7)\n \n set_style = self.setStyling\n source = ''\n if end > editor.length():\n end = editor.length()\n if end > start:\n source = bytearray(end - start)\n SCI(QsciScintilla.SCI_GETTEXTRANGE, start, end, source)\n if not source:\n return \n #compact = self.foldCompact()\n index = SCI(QsciScintilla.SCI_LINEFROMPOSITION, start)\n self.startStyling(start, 0x1f)\n lineno = -1\n source = source.splitlines(True)\n for line in source:\n lineno += 1 \n length = len(line)\n if length == 0: #lol gg this had to be Zero\n return \n if line.startswith('#'):\n newState = self.styles[1]\n else:\n pos = SCI(QsciScintilla.SCI_GETLINEENDPOSITION, index) - length + 1\n i = 0\n while i < length:\n wordLength = 1\n self.startStyling(i + pos, 0x1f)\n newState = self.styles[0]\n for word in self.words2:\n if line[i:].startswith(word):\n newState = self.styles[4]\n wordLength = len(word)\n \n if chr(line[i]) in '0123456789':\n newState = self.styles[4]\n 'startpos=3, length=3, use current indicator'\n #SCI(INDIC_FILL,pos+line[i],1)\n else:\n if line[i:].startswith('\"'):\n newState = self.styles[1]\n pos2 = line.find('\"',i+1)\n size = pos2 - i\n if(size != 0 and pos2 != -1 ):\n wordLength = size\n #print \"line: \",lineno, \"pos: \",pos1, pos2\n elif line[i:].startswith(\"'\"):\n newState = self.styles[1]\n pos2 = line.find(\"'\",i+1)\n size = pos2 - i\n if(size != 0 and pos2 != -1 ):\n wordLength = size\n #print \"line: \",lineno, \"pos: \",pos1, pos2\n \n elif line[i:].startswith(\"class\"):\n newState = self.styles[5]\n wordLength = 5\n elif line[i:].startswith('function'):\n newState = self.styles[5]\n wordLength = 8\n elif line[i:].startswith('enum'):\n newState = self.styles[5]\n wordLength = 4\n elif line[i:].startswith(' if'):\n newState = self.styles[4]\n wordLength = 3\n elif line[i:].startswith('#'): \n # get end of line position and set word length to that\n newState = self.styles[4]\n pos = SCI(QsciScintilla.SCI_GETLINEENDPOSITION, lineno)\n wordLength = pos\n #print \"#end\", pos\n #elif line[i:].startswith(','):\n # newState = self.styles[1]\n # wordLength = 1\n i += wordLength\n set_style(wordLength, newState)\n if newState: \n set_style(length, newState)\n pos = SCI(QsciScintilla.SCI_GETLINEENDPOSITION, index)\n index += 1\n'''","sub_path":"editor/squirrel.py","file_name":"squirrel.py","file_ext":"py","file_size_in_byte":8842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"403739562","text":"#!/usr/bin/env python3\n#-*- coding: UTF 8 -*-\n\nimport os\nimport sqlite3\nfrom objs.bot import ExportBot\n\ndatabase = 'miptnews.db'\n\nif not os.path.isfile(database):\n db = sqlite3.connect(database)\n c = db.cursor()\n c.execute('CREATE TABLE miptnews (id INTEGER PRIMARY KEY, text VARCHAR(200), link VARCHAR(100), date UNIX_TIME, publish UNIX_TIME, chat_id INTEGER, message_id INTEGER)')\n\nbot = ExportBot()\nbot.detect()\nbot.public_posts()\n","sub_path":"miptnews.py","file_name":"miptnews.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"529893265","text":"\"\"\"Helper methods for tests of custom Gym environments.\n\nThis is used in our test suite in `tests/test_envs.py`. It is also used in sister\nprojects such as `imitation`, and may be useful in other codebases.\n\"\"\"\n\nimport re\nfrom typing import (\n Any,\n Callable,\n Iterable,\n Iterator,\n List,\n Mapping,\n Optional,\n Sequence,\n Tuple,\n)\n\nimport gym\nfrom gym.envs.mujoco import mujoco_env\nimport numpy as np\n\nStep = Tuple[Any, Optional[float], bool, Mapping[str, Any]]\nRollout = Sequence[Step]\n\"\"\"A sequence of 4-tuples (obs, rew, done, info) as returned by `get_rollout`.\"\"\"\n\n\ndef make_env_fixture(\n skip_fn: Callable[[str], None],\n) -> Callable[[str], Iterator[gym.Env]]:\n \"\"\"Creates a fixture function, calling `skip_fn` when dependencies are missing.\n\n For example, in `pytest`, one would use::\n\n env = pytest.fixture(make_env_fixture(skip_fn=pytest.skip))\n\n Then any method with an `env` parameter will receive the created environment, with\n the `env_name` parameter automatically passed to the fixture.\n\n In `unittest`, one would use::\n\n def skip_fn(msg):\n raise unittest.SkipTest(msg)\n\n make_env = contextlib.contextmanager(make_env_fixture(skip_fn=skip_fn))\n\n And then call `with make_env(env_name) as env:` to create environments.\n\n Args:\n skip_fn: the function called when a dependency is missing to skip the test.\n\n Returns:\n A method to create Gym environments given their name.\n \"\"\"\n\n def f(env_name: str) -> Iterator[gym.Env]:\n \"\"\"Create environment `env_name`.\n\n Args:\n env_name: The name of the environment in the Gym registry.\n\n Yields:\n The created environment.\n\n Raises:\n gym.error.DependencyNotInstalled: if a dependency is missing\n other than MuJoCo (for MuJoCo, the test is instead skipped).\n \"\"\"\n env = None\n try:\n env = gym.make(env_name)\n yield env\n except gym.error.DependencyNotInstalled as e: # pragma: no cover\n if e.args[0].find(\"mujoco_py\") != -1:\n skip_fn(\"Requires `mujoco_py`, which isn't installed.\")\n else:\n raise\n finally:\n if env is not None:\n env.close()\n\n return f\n\n\ndef matches_list(env_name: str, patterns: Iterable[str]) -> bool:\n \"\"\"Returns True if `env_name` matches any of the patterns in `patterns`.\"\"\"\n return any(re.match(env_pattern, env_name) for env_pattern in patterns)\n\n\ndef get_rollout(env: gym.Env, actions: Iterable[Any]) -> Rollout:\n \"\"\"Performs sequence of actions `actions` in `env`.\n\n Args:\n env: the environment to rollout in.\n actions: the actions to perform.\n\n Returns:\n A sequence of 4-tuples (obs, rew, done, info).\n \"\"\"\n ret: List[Step] = [(env.reset(), None, False, {})]\n for act in actions:\n ret.append(env.step(act))\n return ret\n\n\ndef assert_equal_rollout(rollout_a: Rollout, rollout_b: Rollout) -> None:\n \"\"\"Checks rollouts for equality.\n\n Raises:\n AssertionError if they are not equal.\n \"\"\"\n for step_a, step_b in zip(rollout_a, rollout_b):\n ob_a, rew_a, done_a, info_a = step_a\n ob_b, rew_b, done_b, info_b = step_b\n np.testing.assert_equal(ob_a, ob_b)\n assert rew_a == rew_b\n assert done_a == done_b\n np.testing.assert_equal(info_a, info_b)\n\n\ndef has_same_observations(rollout_a: Rollout, rollout_b: Rollout) -> bool:\n \"\"\"True if `rollout_a` and `rollout_b` have the same observations.\"\"\"\n obs_list_a = [step[0] for step in rollout_a]\n obs_list_b = [step[0] for step in rollout_b]\n return all(np.all(obs_a == obs_b) for obs_a, obs_b in zip(obs_list_a, obs_list_b))\n\n\ndef test_seed(env: gym.Env, env_name: str, deterministic_envs: Iterable[str]) -> None:\n \"\"\"Tests environment seeding.\n\n If non-deterministic, different seeds should produce different transitions.\n If deterministic, should be invariant to seed.\n\n Raises:\n AssertionError if test fails.\n \"\"\"\n env.action_space.seed(0)\n actions = [env.action_space.sample() for _ in range(10)]\n\n # With the same seed, should always get the same result\n seeds = env.seed(42)\n assert isinstance(seeds, list)\n assert len(seeds) > 0\n rollout_a = get_rollout(env, actions)\n\n env.seed(42)\n rollout_b = get_rollout(env, actions)\n\n assert_equal_rollout(rollout_a, rollout_b)\n\n # For most non-deterministic environments, if we try enough seeds we should\n # eventually get a different result. For deterministic environments, all\n # seeds should produce the same starting state.\n def different_seeds_same_rollout(seed1, seed2):\n new_actions = [env.action_space.sample() for _ in range(10)]\n env.seed(seed1)\n new_rollout_1 = get_rollout(env, new_actions)\n env.seed(seed2)\n new_rollout_2 = get_rollout(env, new_actions)\n return has_same_observations(new_rollout_1, new_rollout_2)\n\n is_deterministic = matches_list(env_name, deterministic_envs)\n same_obs = all(different_seeds_same_rollout(seed, seed + 1) for seed in range(100))\n assert same_obs == is_deterministic\n\n\ndef _check_obs(obs: np.ndarray, obs_space: gym.Space) -> None:\n \"\"\"Check obs is consistent with obs_space.\"\"\"\n if obs_space.shape:\n assert obs.shape == obs_space.shape\n assert obs.dtype == obs_space.dtype\n assert obs in obs_space\n\n\ndef _sample_and_check(env: gym.Env, obs_space: gym.Space) -> bool:\n \"\"\"Sample from env and check return value is of valid type.\"\"\"\n act = env.action_space.sample()\n obs, rew, done, info = env.step(act)\n _check_obs(obs, obs_space)\n assert isinstance(rew, float)\n assert isinstance(done, bool)\n assert isinstance(info, dict)\n return done\n\n\ndef test_rollout_schema(\n env: gym.Env,\n steps_after_done: int = 10,\n max_steps: int = 10000,\n) -> None:\n \"\"\"Check custom environments have correct types on `step` and `reset`.\n\n Args:\n env: The environment to test.\n steps_after_done: The number of steps to take after `done` is True, the nominal\n episode termination. This is an abuse of the Gym API, but we would like the\n environments to handle this case gracefully.\n max_steps: Test fails if we do not get `done` after this many timesteps.\n\n Raises:\n AssertionError if test fails.\n \"\"\"\n obs_space = env.observation_space\n obs = env.reset()\n _check_obs(obs, obs_space)\n\n for _ in range(max_steps):\n done = _sample_and_check(env, obs_space)\n if done:\n break\n\n assert done is True, \"did not get to end of episode\"\n\n for _ in range(steps_after_done):\n _sample_and_check(env, obs_space)\n\n\ndef test_premature_step(env: gym.Env, skip_fn, raises_fn) -> None:\n \"\"\"Test that you must call reset() before calling step().\n\n Example usage in pytest:\n test_premature_step(env, skip_fn=pytest.skip, raises_fn=pytest.raises)\n\n Args:\n env: The environment to test.\n skip_fn: called when the environment is incompatible with the test.\n raises_fn: Context manager to check exception is thrown.\n\n Raises:\n AssertionError if test fails.\n \"\"\"\n if hasattr(env, \"sim\") and hasattr(env, \"model\"): # pragma: no cover\n # We can't use isinstance since importing mujoco_py will fail on\n # machines without MuJoCo installed\n skip_fn(\"MuJoCo environments cannot perform this check.\")\n\n act = env.action_space.sample()\n with raises_fn(Exception): # need to call env.reset() first\n env.step(act)\n\n\ndef test_render(env: gym.Env, raises_fn) -> None:\n \"\"\"Test that render() supports the modes declared.\n\n Example usage in pytest:\n test_render(env, raises_fn=pytest.raises)\n\n Args:\n env: The environment to test.\n raises_fn: Context manager to check NotImplementedError is thrown when\n environment metadata indicates modes are supported.\n\n Raises:\n AssertionError: if test fails. This occurs if:\n (a) `env.render(mode=mode)` fails for any mode declared supported\n in `env.metadata[\"render.modes\"]`; (b) env.render() *succeeds* when\n `env.metadata[\"render.modes\"]` is empty; (c) `env.render(mode=\"rgb_array\")`\n returns different values at the same time step.\n \"\"\"\n env.reset() # make sure environment is in consistent state\n\n render_modes = env.metadata[\"render.modes\"]\n if not render_modes:\n # No modes supported -- render() should fail.\n with raises_fn(NotImplementedError):\n env.render()\n else:\n for mode in render_modes:\n env.render(mode=mode)\n\n # WARNING(adam): there seems to be a memory leak with Gym 0.17.3\n # & MuJoCoPy 1.50.1.68. `MujocoEnv.close()` does not call `finish()`\n # on the viewer (commented out) so the resources are not released.\n # For now this is OK, but may bite if we end up testing a lot of\n # MuJoCo environments.\n is_mujoco = isinstance(env.unwrapped, mujoco_env.MujocoEnv)\n if \"rgb_array\" in render_modes and not is_mujoco:\n # Render should not change without calling `step()`.\n # MuJoCo rendering fails this check, ignore -- not much we can do.\n resa = env.render(mode=\"rgb_array\")\n resb = env.render(mode=\"rgb_array\")\n assert np.allclose(resa, resb)\n\n\nclass CountingEnv(gym.Env):\n \"\"\"At timestep `t` of each episode, has `t == obs == reward / 10`.\n\n Episodes finish after `episode_length` calls to `step()`, or equivalently\n `episode_length` actions. For example, if we have `episode_length=5`,\n then an episode has the following observations and rewards:\n\n ```\n obs = [0, 1, 2, 3, 4, 5]\n rews = [10, 20, 30, 40, 50]\n ```\n \"\"\"\n\n def __init__(self, episode_length: int = 5):\n \"\"\"Initialize a CountingEnv.\n\n Params:\n episode_length: The number of actions before each episode ends.\n \"\"\"\n assert episode_length >= 1\n self.observation_space = gym.spaces.Box(low=0, high=np.inf, shape=())\n self.action_space = gym.spaces.Box(low=0, high=np.inf, shape=())\n self.episode_length = episode_length\n self.timestep = None\n\n def reset(self):\n \"\"\"Reset method for CountingEnv.\"\"\"\n t, self.timestep = 0, 1\n return np.array(t, dtype=self.observation_space.dtype)\n\n def step(self, action):\n \"\"\"Step method for CountingEnv.\"\"\"\n if self.timestep is None: # pragma: no cover\n raise RuntimeError(\"Need to reset before first step().\")\n if np.array(action) not in self.action_space: # pragma: no cover\n raise ValueError(f\"Invalid action {action}\")\n if self.timestep > self.episode_length: # pragma: no cover\n raise ValueError(\"Should reset env. Episode is over.\")\n\n t, self.timestep = self.timestep, self.timestep + 1\n obs = np.array(t, dtype=self.observation_space.dtype)\n rew = t * 10.0\n done = t == self.episode_length\n return obs, rew, done, {}\n","sub_path":"src/seals/testing/envs.py","file_name":"envs.py","file_ext":"py","file_size_in_byte":11209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"131744672","text":"\"\"\" Typings from all qcd module \"\"\"\nfrom typing import List, TypedDict, Tuple\nimport enum\n\n\nclass ResultStates(TypedDict):\n zero_amplitude: List[float]\n one_amplitude: List[complex]\n\n\nclass ResultState(TypedDict):\n zero_amplitude: float\n one_amplitude: complex\n\n\nclass ResultStatesReshaped(TypedDict):\n reshaped_coords_x: List[float]\n reshaped_coords_y: List[float]\n reshaped_coords_z: List[float]\n center: float\n\n\nclass ResultProbabilitiesOneChannel(TypedDict):\n x_input_0: List[float]\n x_input_1: List[float]\n z_output_0: List[float]\n z_output_1: List[complex]\n\n\nclass ResultProbabilities(TypedDict):\n x_input_0: List[List[float]]\n x_input_1: List[List[float]]\n z_output_0: List[List[float]]\n z_output_1: List[List[complex]]\n\n\nclass OneShotResults(TypedDict, total=False):\n initial_states_reshaped: ResultStatesReshaped\n final_states: List[ResultStates]\n final_states_reshaped: List[ResultStatesReshaped]\n probabilities: ResultProbabilities\n attenuation_factors: List[float]\n attenuation_factor_per_state: List[List[float]]\n backend_name: str\n initial_one_state_reshaped: Tuple[float, float, float]\n final_one_state_reshaped: List[Tuple[float, float, float]]\n\n\nclass OptimizationSetup(TypedDict, total=False):\n optimizer_algorithms: List[str]\n optimizer_iterations: List[int]\n eta_partitions: int\n number_channels_to_discriminate: int\n plays: int\n initial_parameters: List[float]\n variable_bounds: List[Tuple[float, float]]\n number_third_channels: int\n\n\nclass TheoreticalOptimizationSetup(TypedDict):\n eta_groups: List[List[float]]\n\n\nclass GuessStrategy(enum.Enum):\n one_bit_same_as_measured = 1\n two_bit_base = 2\n two_bit_neural_network = 3\n\n\nclass CloneSetup(TypedDict, total=False):\n total_clones: int\n id_clone: int\n file_name: str\n path: str\n","sub_path":"qcd/typings/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"381640217","text":"from igraph import *\nfrom algorithm import *\n\n# g = Graph([(0,1), (0,2), (2,3), (3,4), (4,2), (2,5), (5,0), (6,3), (5,6)])\n#\n# g.vs[\"name\"] = [\"Alice\", \"Bob\", \"Claire\", \"Dennis\", \"Esther\", \"Frank\", \"George\"]\n# g.vs[\"age\"] = [25, 31, 18, 47, 22, 23, 50]\n# g.vs[\"gender\"] = [\"f\", \"m\", \"f\", \"m\", \"f\", \"m\", \"m\"]\n# g.es[\"is_formal\"] = [False, False, True, True, True, False, True, False, False]\n#\n# layout = g.layout(\"kk\")\n# color_dict = {\"m\": \"blue\", \"f\": \"pink\"}\n# visual_style = {}\n# visual_style[\"vertex_size\"] = 20\n# visual_style[\"vertex_color\"] = [color_dict[gender] for gender in g.vs[\"gender\"]]\n# visual_style[\"vertex_label\"] = g.vs[\"name\"]\n# visual_style[\"edge_width\"] = [1 + 2 * int(is_formal) for is_formal in g.es[\"is_formal\"]]\n# visual_style[\"layout\"] = layout\n# visual_style[\"bbox\"] = (300, 300)\n# visual_style[\"margin\"] = 20\n# plot(g, **visual_style)\n\n# g = Graph([(0, 1), (0, 2), (2, 1), (3, 4)])\n# g.vs[\"name\"] = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n# visual_style = {}\n# visual_style[\"layout\"] = g.layout(\"kk\")\n# visual_style[\"bbox\"] = (300, 300)\n# visual_style[\"margin\"] = 20\n# visual_style[\"vertex_label\"] = g.vs[\"name\"]\n# visual_style[\"vertex_color\"] = [\"green\"] * len(g.vs[\"name\"])\n# #plot(g, **visual_style)\n# g.get_adjacency()\n\n\nfull_adjacency_matrix_sample = np.array([\n [-1, 0, 1], # A\n [ 1,-1, 0], # B\n [ 0,-1,-1] # C\n])\nlabels_sample = [\"A\", \"B\", \"C\"]\nweights_sample = [1, 2, 10]\nfull_adjacency_matrix_sample = np.array([\n [-1, -1, 0, 0], # a\n [-1, 0, -1, 0], # b\n [0, -1, -1, 0], # c\n [0, 0, 0, -1], # d\n [0, 0, 0, -1] # e\n])\nlabels_sample = [\"a\", \"b\", \"c\", \"d\", \"e\"]\nweights_sample = [1, 2, 10, 1]\n\ng = PartiallyDirectedGraph(full_adjacency_matrix_sample, labels_sample, weights_sample)\ng.plot()\n","sub_path":"playground.py","file_name":"playground.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"255149017","text":"from plugins.plugin import Plugin\n\n__all__ = [\"FirstPlugin\"]\n\nclass FirstPlugin(Plugin):\n \n name = \"firstPlugin\"\n description = \"\"\n version = '0.0.1'\n\n def __init__(self):\n Plugin.__init__(self)\n \n def scan(self, options={}):\n return \"exec function\"","sub_path":"plugins/system/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"72897783","text":"import pandas as pd\nimport numpy as np\n\n#############################\n# THIS WAS A GIT REPO TEST ##\n##############################\n\nname = ['Mubarak', 'Jida', 'Jude', 'Eddie', 'Zamani']\ndepartment = ['NOC', 'Management', 'Data', 'Security', 'Tourism']\nstate = ['Kwara', 'Lagos', 'Benue', 'Akwa ibom', 'Plateau']\nstaff_ind =['MU', 'JI', 'JU', 'ED', 'ZA']\n\nstaff_dict = {'name':name, 'department':department, 'state':state}\nstaff = pd.DataFrame(staff_dict)\nstaff.index = staff_ind\n\n# print(staff)\n\n# print(staff['name'])\n\n# print(staff[['name']]) \n\n# print(staff[['name', 'state']]) \n\n# print(staff[0:4])\n\n# print(type(staff[0:4][0:2]))\n\n# print(staff[0:4][0:2])\n\n# To import data from file, use the code below\n# variable = pd.read_csv('path/to/csv'/file)\n\n# below is a more robust way of using indexing and selecting data from a panda data frame\n# - loc - (label oriented)\n# - iloc - (index position oriented)\n\ncars = pd.read_csv('cars.csv', index_col=0)\nprint(cars)\n\n# Print out observation for Japan\nprint(cars.loc['JPN'])\nprint(cars.loc[['JPN']])\n# Print out drives_right value of Morocco\nprint(cars.loc['MOR', 'drives_right'])\n\n# Print sub-DataFrame\nprint(cars.loc[['RU', 'MOR'], ['country', 'drives_right']])\n#print(cars.iloc[[4,5], [1,2]])\n\n# Print out drives_right column as Series\nprint(cars.loc[:,'drives_right'])\n#print(type(cars.loc[:,'drives_right']))\n\n# Print out drives_right column as DataFrame\nprint(cars.loc[:,['drives_right']])\n#print(type(cars.loc[:,['drives_right']]))\n\n\n# Print out cars_per_cap and drives_right as DataFrame\nprint(cars.loc[:,['cars_per_cap', 'drives_right']])\n# Extract drives_right column as Series: dr\ndr = cars['drives_right']\n\n####################################################\n# Code for loop that adds COUNTRY column\nfor l, r in cars.iterrows():\n cars.loc[l, \"COUNTRY\"] = r['country'].upper()\n\n# Use .apply(str.upper)\ncars['COUNTRY'] = cars['country'].apply(str.upper)\n\n# Use dr to subset cars: sel\nsel = cars[dr]\n\n# Print sel\nprint (sel)\n# Print out observations for Australia and Egypt\n# print(cars.loc['AUS', 'EG'])\n# print(cars.loc[['AUS', 'EG']])\n\n# print(staff.iloc[:,[2]])\n\n#COMPARISON\n\n#NUMPY Comparison functions\n#==> logical_and()\n#==> logical_or()\n#==> logical_not()\n\nmy_house = np.array([18.0, 20.0, 10.75, 9.50])\nyour_house = np.array([14.0, 24.0, 14.25, 9.0])\nprint(my_house >= 18)\nprint(my_house < your_house)\n# my_house greater than 18.5 or smaller than 10\nprint(np.logical_or(my_house > 18.5, my_house < 10))\n\n# Both my_house and your_house smaller than 11\nprint(np.logical_and(my_house < 11, your_house < 11))\n\n#CONTROL-FLOW\n#If-elif-else\n\nroom = \"Kitchen\"\narea = 20\n\nif room == 'Kitchen' and area < 20:\n print('This is not the perfect Kitchen for the house')\nelif room == 'bed' and area >= 20:\n print('This a perfect sized bedroom!')\nelse:\n print('This is a perfect kitchen')\n \n \n#loop\n# areas list\nareas = [11.25, 18.0, 20.0, 10.75, 9.50]\n\n# Change for loop to use enumerate() and update print()\nfor index,a in enumerate(areas):\n print('room ' + str(index) + ': ' + str(a))\n \n#Looping with dictionaries\n# Definition of dictionary\neurope = {'spain':'madrid', 'france':'paris', 'germany':'berlin',\n 'norway':'oslo', 'italy':'rome', 'poland':'warsaw', 'austria':'vienna' }\n \n# Iterate over europe\nfor k, v in europe.items():\n print('the capital of ' + k + ' is ' + v)\n \n # For loop over np_height\nfor no in np_height:\n print(str(no) + \" inches\")\n\n# For loop over np_baseball\nfor bo in np.nditer(np_baseball):\n print(bo)\n \n # Import cars data\nimport pandas as pd\ncars = pd.read_csv('cars.csv', index_col = 0)\n\n# Adapt for loop\nfor lab, row in cars.iterrows() :\n print(lab)\n print(row)\n# Adapt for loop\nfor lab, row in cars.iterrows() :\n print(str(lab) + ': ' + str(row['cars_per_cap']))\n \n \n####################################################\n#RANDOM\n####################################################\n\nnp.random.seed(123)\n\n# Use randint() to simulate a dice\nprint(np.random.randint(1,7))\n\n# Use randint() again\nprint(np.random.randint(1,7))\n\n# Starting step\nstep = 50\n\n# Roll the dice\ndice = np.random.randint(1,7)\n\n# Finish the control construct\nif dice <= 2 :\n step = step - 1\nelif dice > 2 and dice <= 5:\n step = step + 1\nelse:\n step = step + np.random.randint(1,7)\n\n# Print out dice and step\nprint(dice)\nprint(step)\n\n\n# Initialization\nrandom_walk = [0]\n\nfor x in range(100) :\n step = random_walk[-1]\n dice = np.random.randint(1,7)\n\n if dice <= 2:\n step = max(0, step - 1)\n elif dice <= 5:\n step = step + 1\n else:\n step = step + np.random.randint(1,7)\n\n random_walk.append(step)\n\n# Import matplotlib.pyplot as plt\nimport matplotlib.pyplot as plt\n\n# Plot random_walk\nplt.plot(random_walk)\n\n\n\n# Initialize all_walks (don't change this line)\nall_walks = []\n\n# Simulate random walk 10 times\nfor i in range(10) :\n\n # Code from before\n random_walk = [0]\n for x in range(100) :\n step = random_walk[-1]\n dice = np.random.randint(1,7)\n\n if dice <= 2:\n step = max(0, step - 1)\n elif dice <= 5:\n step = step + 1\n else:\n step = step + np.random.randint(1,7)\n random_walk.append(step)\n\n # Append random_walk to all_walks\n all_walks.append(random_walk)\n\n# Print all_walks\nprint(all_walks)\n\n\n# numpy and matplotlib imported, seed set.\n\n# initialize and populate all_walks\nall_walks = []\nfor i in range(10) :\n random_walk = [0]\n for x in range(100) :\n step = random_walk[-1]\n dice = np.random.randint(1,7)\n if dice <= 2:\n step = max(0, step - 1)\n elif dice <= 5:\n step = step + 1\n else:\n step = step + np.random.randint(1,7)\n random_walk.append(step)\n all_walks.append(random_walk)\n\n# Convert all_walks to Numpy array: np_aw\nnp_aw = np.array(all_walks)\n\n# Plot np_aw and show\nplt.plot(np_aw)\n\n# Clear the figure\nplt.clf()\n\n# Transpose np_aw: np_aw_t\nnp_aw_t = np.transpose(np_aw)\n\n# Plot np_aw_t and show\nplt.plot(np_aw_t)\nplt.show()\n\n\n\n# numpy and matplotlib imported, seed set\n\n# Simulate random walk 250 times\nall_walks = []\nfor i in range(250) :\n random_walk = [0]\n for x in range(100) :\n step = random_walk[-1]\n dice = np.random.randint(1,7)\n if dice <= 2:\n step = max(0, step - 1)\n elif dice <= 5:\n step = step + 1\n else:\n step = step + np.random.randint(1,7)\n\n # Implement clumsiness\n if np.random.rand() <= 0.001:\n step = 0\n\n random_walk.append(step)\n all_walks.append(random_walk)\n\n# Create and plot np_aw_t\nnp_aw_t = np.transpose(np.array(all_walks))\nplt.plot(np_aw_t)\nplt.show()\n\n\n# numpy and matplotlib imported, seed set\n\n# Simulate random walk 500 times\nall_walks = []\nfor i in range(500) :\n random_walk = [0]\n for x in range(100) :\n step = random_walk[-1]\n dice = np.random.randint(1,7)\n if dice <= 2:\n step = max(0, step - 1)\n elif dice <= 5:\n step = step + 1\n else:\n step = step + np.random.randint(1,7)\n if np.random.rand() <= 0.001 :\n step = 0\n random_walk.append(step)\n all_walks.append(random_walk)\n\n# Create and plot np_aw_t\nnp_aw_t = np.transpose(np.array(all_walks))\n\n# Select last row from np_aw_t: ends\nends = np_aw_t[-1,:]\n\n# Plot histogram of ends, display plot\nplt.hist(ends)\nplt.show()\n","sub_path":"pandapractice.py","file_name":"pandapractice.py","file_ext":"py","file_size_in_byte":7480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"579305395","text":"from fixture.orm import ORMFixture\nfrom model.contact import Contact\nfrom model.group import Group\n\n\n\ndb = ORMFixture(host=\"127.0.0.1\", name=\"addressbook\", user= \"root\",password = \"\")\ndef test_add_contact_in_group(app,check_ui):\n if len(db.get_contact_list()) == 0:\n app.contact.create(Contact(firstname =\"firstname\",lastname = \"lastname\", address= \"address\", home = \"home\",\n mobile = \"mobile\", work = \"work\", phone_2 = \"phone_2\", email = \"email\", email2 = \"email2\",\n email3= \"email3\"))\n if len(db.get_group_list()) == 0:\n app.group.create(Group(name=\"test\"))\n group=None\n contact=None\n group_list=db.get_group_list()\n for index in range(len(group_list)):\n orm_contacts=db.get_contacts_not_in_group(group_list[index])\n group = group_list[index]\n if len(orm_contacts) > 0:\n contact = orm_contacts[0]\n break\n\n if contact is None:\n contact = db.get_contacts_in_group(group)[0]\n app.contact.remove_contact_from_group(contact.id, group.name)\n\n old_contacts_list = db.get_contacts_in_group(group)\n app.contact.add_contact_in_group(contact.id,group.name)\n new_contacts_list = db.get_contacts_in_group(group)\n assert len(new_contacts_list) == len(old_contacts_list) + 1\n assert contact in new_contacts_list\n\n\n\n\n\n","sub_path":"test/test_add_contact_in_group.py","file_name":"test_add_contact_in_group.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"29"}
+{"seq_id":"454992953","text":"# Utilities for the demand-related parts of the assignment\n\nimport os\nimport boto\nfrom time import sleep\nfrom fabric.api import *\nfrom cuisine import *\nfrom pprint import pprint\n\n\ndef add_tag(resource, tag):\n\tfor (k,v) in tag.items():\n\t\ts = resource.add_tag(k,v)\n\ndef wait(resources, desired_states):\n\tstates = [x.update() for x in resources]\n\twhile set(states) != set(desired_states):\n\t\tprint('current states: {s} vs. desired states: {t}'.format(s=set(states), t=set(desired_states)))\n\t\tsleep(10)\n\t\tstates = [x.update() for x in resources]\n\n\ndef get_instances_from_reservations(conn=None, reservations=None):\n\t# Get instances from reservations. A reservation gives the instance id but does not populate\n\t# the rest of the instance properties, so a separate call is needed.\n\treservations_w_instances = conn.get_all_instances(instance_ids=[r.instance_id for r in reservations])\n\tinstances = [r.instances[0] for r in reservations_w_instances]\n\t# Exclude instances that are terminated or terminating (there's nothing that can be done with them)\n\tinstances = [i for i in instances if i.state != 'terminated' and i.state != 'shutting-down']\n\treturn instances\n\n\ndef create_volume(conn, instance, user=None, snapshot=None, tag=None):\n\t# create volumes if they don't exist\n\tif snapshot:\n\t\tprint('Creating volume from existing snapshot {s}'.format(s=snapshot))\n\t\tvolume = conn.create_volume(size=1, zone=instance.placement, snapshot=snapshot, volume_type='standard')\n\t\tadd_tag(volume, tag)\n\telse:\n\t\tprint(\"No existing test EBS volume. Creating a new one.\")\n\t\tvolume = conn.create_volume(size=1, zone=instance.placement, snapshot=None, volume_type='standard')\n\t\tadd_tag(volume, tag)\n\t\n\treturn volume\n\n\ndef mount_volume(conn=None, instance=None, volume=None, key_path=None, device='/dev/sdf', ubuntu_device='/dev/xvdf', format=False):\n\t# wait(resources=[instance], desired_states=['running'])\n\ttry:\n\t\t# Attach\n\t\tconn.attach_volume(volume_id=volume.id, instance_id=instance.id, device=device)\n\t\tprint('Attaching volume to {dev}'.format(dev=device))\n\t\twait(resources=[volume], desired_states=['in-use'])\n\n\t\t# Format\n\t\tenv.host_string = instance.public_dns_name\n\t\tenv.user = 'ubuntu'\n\t\tenv.key_filename = key_path\n\t\tprint('Formatting the new volume.')\n\t\tmode_sudo()\n\t\tsudo('mkfs.ext4 -q {dev}'.format(dev=ubuntu_device))\n\t\tdir_ensure(location='/vol', mode='000')\n\t\tsudo('''echo \"{dev} /vol auto noatime 0 0\" | sudo tee -a /etc/fstab'''.format(dev=ubuntu_device))\n\n\t\t# Mount\n\t\tsudo('mount /vol')\n\t\tprint('mounted {id} at {loc}'.format(id=volume.id, loc=ubuntu_device))\n\n\texcept boto.exception.EC2ResponseError as e:\n\t\tprint('Volume {v} is already mounted to an instance. File system and mounting assumed.'.format(v=volume.id))\n\t\tpprint(volume.attach_data)\t\n\n\ndef create_image(conn, instance, tag):\n\t# Create image of running instance\n\tprint('Creating image of instance ' + instance.id)\n\twait(resources=[instance], desired_states=['running'])\n\tfilter = {'tag-value':tag['user']}\n\t# delete any existing image for that user (only one image per user is allowed)\n\timages = conn.get_all_images(filters=filter)\n\tfor i in images:\n\t\tprint('Replacing existing image {id}'.format(id=i.id))\n\t\ti.deregister(delete_snapshot=True)\n\tnew_ami = instance.create_image('asst1-image-user-' + tag['user'])\n\t# need to query for the full image object before the tag can be added\n\timage = conn.get_image(new_ami)\n\tadd_tag(image, tag)\n\treturn new_ami\n\n\ndef create_snapshot(conn, volume, tag):\n\tfilter = {'tag-value':tag['user']}\n\tsnapshots = conn.get_all_snapshots(filters=filter)\n\tfor s in snapshots:\n\t\tprint('Deleting existing disk snapshots for user ' + tag['user'])\n\t\ts.delete()\n\t# create new snapshot and tag to user\n\tsnapshot = volume.create_snapshot('Snapshot of User Data Volume ' + tag['user'])\n\tadd_tag(snapshot, tag)\n\tprint('Created snapshot of User Data Volume ' + tag['user'])\n\treturn snapshot\n\n\ndef unmount_volume(volume, instance, ubuntu_device='/dev/xvdf'):\n\t# Prepare for cuisine\n\tenv.host_string = instance.public_dns_name\n\tenv.user = 'ubuntu'\n\tenv.key_filename = key_paths[user]\n\tmode_sudo()\n\tprint('Unmounting volume {id}'.format(id=volume.id))\n\tmode_sudo()\n\tsudo('umount {dev}'.format(dev=ubuntu_device))\n\tvolume.detach()\n\treturn volume\n\n\ndef mount_ssh_directory(server_instance, client_instance, key_name=None, path='/vol'):\n\t# Mounts a network file share on the client instance that points to a drive on the server\n\t# instance. It uses the program sshfs, which is installed on a client machine and can mount\n\t# folders from any machine that client has SSH access to as network folders. Nothing is required\n\t# to be installed on the server machine.\n\tssh_relative_path = '~/.ssh/{key_name}'.format(key_name=key_name)\n\tssh_absolute_path = os.path.expanduser(ssh_relative_path)\n\n\tenv.host_string = client_instance.public_dns_name\n\tenv.user = 'ubuntu'\n\tenv.key_filename = ssh_absolute_path\n\t# Install prerequisites on client machine\n\tsudo('apt-get install sshfs')\n\tsudo('modprobe fuse')\n\tdir_ensure(location=path, mode='000')\n\t# Copy SSH key to client machine, so it is authorized to SSH into the server\n\tput(ssh_absolute_path, ssh_relative_path)\n\tsudo('chmod 600 {ssh_file}'.format(ssh_file=ssh_relative_path))\n\t# Map directory on server to the same directory on the client machine\n\tsudo('sshfs -o IdentityFile={ssh} ubuntu@{dns}:{path} -o allow_other {path}'.format(dns=server_instance.public_dns_name, path=path, ssh=ssh_relative_path))\n","sub_path":"demand.py","file_name":"demand.py","file_ext":"py","file_size_in_byte":5418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"4702469","text":"## get all the LR file\n\nimport sys\nsys.dont_write_bytecode = True\nsys.path.append('./scripts/')\nimport dbn_reduction\nimport os\n\nresultfolder = 'dbn_reduced/'\n\nf = open('RNA.list')\nrnas = f.readlines()\nf.close()\n\n# dbn_count = { dbn:[count, [rna1,rna2,...] ] }\ndbn_count = {}\nfor rna in rnas:\n\t# get dbn\n\trna = rna.strip()\n\tfn = 'rlt/'+rna+'/dssr-2ndstrs.dbn'\n\tif not os.path.exists(fn):\n\t\tcontinue\n\tf = open('rlt/'+rna+'/dssr-2ndstrs.dbn')\n\tlines = f.readlines()\n\tf.close()\n\n\t# reduce dbn\n\tdbn = dbn_reduction.dbn_heavy_heavy_reduction(lines[2].strip())\n\n\t# count dbn\n\tif dbn in dbn_count:\n\t\tdbn_count[dbn][0] += 1\n\t\tdbn_count[dbn][1].append(rna)\n\telse:\n\t\tdbn_count[dbn] = [1, [rna] ]\n\n# get classification of the reduced dbn\nfout = open('heavy_heavy_reduction_classification.txt','w')\nfor dbn in dbn_count.iterkeys():\n\tfout.write( dbn +'\\n' )\n\tfout.write( str(dbn_count[dbn][0]) +'\\t'+ ', '.join(dbn_count[dbn][1]) +'\\n' )\n\tfout.write( '~~~~~~~~~~~~~~~' +'\\n' )\nfout.close()\n","sub_path":"bak/heavy_heavy_reduce_dbn.py","file_name":"heavy_heavy_reduce_dbn.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"313946503","text":"import torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nimport torch.utils.data as Data\n\n\ndef get_dataiter(train=True,batch=256,shuffle=True):\n train_minist,test_minist=download_dataset()\n if train is True:\n data_iter=Data.DataLoader(train_minist,batch,shuffle)\n return data_iter\n else:\n data_iter=Data.DataLoader(test_minist,batch,shuffle)\n return data_iter\n\n\ndef show_data(features, labels):\n _, figs = plt.subplots(1, len(features),figsize=(12,12))\n for fig,feature,label in zip(figs,features,labels):\n fig.imshow(feature.view((28,28)).numpy())\n fig.set_title(label)\n\n plt.show()\n\n\ndef download_dataset():\n \"\"\"\n Download fashion minist dataset from github and store it in ~/Datasets/FashionMNIST. If it exist, return train\n data and test data.\n Data format:\n length is 60000(train)/10000(test) and every element is tuple (tensor,int) every tensor represents picture\n which is 1*28*28 (channel height width) or (C*H*W) which is transformed by (H*W*C)\n :return: train_dataset,test_dataset\n \"\"\"\n minist_train = torchvision.datasets.FashionMNIST(root=\"~/Datasets/FashionMNIST\", train=True, download=True,\n transform=transforms.ToTensor())\n minist_test = torchvision.datasets.FashionMNIST(root=\"~/Datasets/FashionMNIST\", train=False, download=True,\n transform=transforms.ToTensor())\n return minist_train, minist_test\n\n\ndef labels2language(labels):\n language = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']\n return [language[i] for i in labels]\n\n\ndef main():\n minist_train, minist_test = download_dataset()\n ind_list = range(10)\n features=[]\n labels=[]\n for ind in ind_list:\n features.append(minist_train[ind][0])\n labels.append(minist_train[ind][1])\n labels_lan = labels2language(labels)\n show_data(features, labels_lan)\n\nif __name__ == \"__main__\":\n main()","sub_path":"MultiLayer/data_show.py","file_name":"data_show.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"85694362","text":"import tensorflow as tf\nimport numpy as np\n\nsess = tf.Session()\ndata_size = 25\ndata_1d = np.random.normal(size=data_size)\nx_input_1d = tf.placeholder(dtype=tf.float32, shape=[data_size])\n\ndef conv_layer_1d(input_1d, my_filter):\n # Make 1d input into 4d\n input_2d = tf.expand_dims(input_1d, 0)\n input_3d = tf.expand_dims(input_2d, 0)\n input_4d = tf.expand_dims(input_3d, 0)\n # Perfom convolution\n convolution_output = tf.nn.conv2d(input_4d,filter=my_filter,strides=[1,1,1,1], padding=\"VALID\")\n # Now drop extra dimensions\n conv_output_1d = tf.squeeze(convolution_output)\n return(conv_output_1d)\n\nmy_filter = tf.Variable(tf.random_normal(shape=[1,5,1,1]))\nmy_convolution_out = conv_layer_1d(x_input_1d, my_filter)\n\ndef activation(input_1d):\n return(tf.nn.relu(input_1d))\n\nmy_activation_output = activation(my_activation_output)\n\ndef max_pool(input_1d, width):\n # First we make the 1d input 4d\n input_2d = tf.expand_dims(input_1d,0)\n input_3d = tf.expand_dims(input_2d,0)\n input_4d = tf.expand_dims(input_3d,3)\n # Perform the max pool operation\n pool_output = tf.nn.max_pool(input_4d, ksize=[1,1,width,1],strides=[1,1,1,1], padding='VALID')\n pool_output_1d = tf.squeeze(pool_output)\n return(pool_output_1d)\n\nmy_maxpool_output = max_pool(my_activation_output, width=5)\n\ndef fully_connected(input_layer, num_outputs):\n # Create weights\n weight_shapes = tf.squeeze(tf.pack([tf.shape(input_layer)]))\n bias = tf.random_normal(shape=[num_outputs])\n # Make input into 2d\n input_layer_2d = tf.expand_dims(input_layer, 0)\n # perform fully connected operations\n","sub_path":"multi_layer_NN.py","file_name":"multi_layer_NN.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"291063589","text":"#\r\n# Copyright 2018 Chris Bang Sørensen, Niels Hvid, Thomas Lemqvist\r\n#\r\n# Permission is hereby granted, free of charge, to any person obtaining a copy\r\n# of this software and associated documentation files (the \"Software\"), to deal\r\n# in the Software without restriction, including without limitation the rights\r\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\r\n# of the Software, and to permit persons to whom the Software is furnished to do so,\r\n# subject to the following conditions:\r\n#\r\n# The above copyright notice and this permission notice shall be included in all\r\n# copies or substantial portions of the Software.\r\n#\r\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\r\n# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\r\n# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\r\n# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\r\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n#\r\n# Packages to install: (pip install)\r\n# pandas, matplotlib, numpy\r\n#\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.lines as ln\r\n\r\nSoL = 299792458 # Speed of Light ~300 km/s\r\na = SoL / 2400000000 # 2.4 GHz\r\nb = SoL / 433000000 # 433 MHz\r\nc = SoL / 5800000000 # 5.8 GHz\r\nfreqs = {'a': a, 'b': b, 'c': c}\r\nd1 = list(range(0, 101))\r\nd2 = d1.copy()\r\nd2.reverse()\r\ndf = pd.DataFrame({'d1': d1, 'd2': d2})\r\n# df['d1'] = df['d1'] / 1000\r\n# df['d2'] = df['d2'] / 1000\r\nfor l in ['a', 'b', 'c']:\r\n f = freqs[l]\r\n for n in [1, 2, 3]:\r\n key = \"F%i %s\" % (n, l)\r\n df[key] = np.sqrt(\r\n (n * f * (df['d1'] * df['d2']))\r\n /\r\n (df['d1'] + df['d2'])\r\n )\r\n key_neg = '-' + key\r\n df[key_neg] = -1 * df[key]\r\n\r\nprint(df)\r\n\r\nplt.plot(df['d1'], df['F1 a'], c='teal', linestyle=':')\r\nplt.plot(df['d1'], df['F2 a'], c='teal', linestyle=':')\r\nplt.plot(df['d1'], df['F3 a'], c='teal', linestyle=':')\r\nplt.plot(df['d1'], df['-F1 a'], c='teal', linestyle=':')\r\nplt.plot(df['d1'], df['-F2 a'], c='teal', linestyle=':')\r\nplt.plot(df['d1'], df['-F3 a'], c='teal', linestyle=':')\r\n\r\nplt.plot(df['d1'], df['F1 b'], c='orange', linestyle='-.')\r\nplt.plot(df['d1'], df['F2 b'], c='orange', linestyle='-.')\r\nplt.plot(df['d1'], df['F3 b'], c='orange', linestyle='-.')\r\nplt.plot(df['d1'], df['-F1 b'], c='orange', linestyle='-.')\r\nplt.plot(df['d1'], df['-F2 b'], c='orange', linestyle='-.')\r\nplt.plot(df['d1'], df['-F3 b'], c='orange', linestyle='-.')\r\n\r\nplt.plot(df['d1'], df['F1 c'], c='lime', linestyle='--')\r\nplt.plot(df['d1'], df['F2 c'], c='lime', linestyle='--')\r\nplt.plot(df['d1'], df['F3 c'], c='lime', linestyle='--')\r\nplt.plot(df['d1'], df['-F1 c'], c='lime', linestyle='--')\r\nplt.plot(df['d1'], df['-F2 c'], c='lime', linestyle='--')\r\nplt.plot(df['d1'], df['-F3 c'], c='lime', linestyle='--')\r\n\r\nplt.legend(handles=[\r\n ln.Line2D([], [], color='teal', label='2.4 GHz', linestyle=':'),\r\n ln.Line2D([], [], color='orange', label='433 MHz', linestyle='-.'),\r\n ln.Line2D([], [], color='lime', label='5.8 GHz', linestyle='--'),\r\n])\r\nplt.xlabel('Distance [m]')\r\nplt.ylabel('Radius [m]')\r\nplt.savefig('freznel.png')\r\nplt.show()\r\n\r\nprint(np.max(df['F1 a']))\r\n","sub_path":"lab 8/freznel.py","file_name":"freznel.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"634551088","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 1 21:33:41 2018\n\n@author: Gadcet\n\"\"\"\n\n# Read in the data from all countries and combine\n\nusa = pd.read_csv('/Users/Gadcet/Documents/Ani extraction/usa_data.csv')\nusa['country'] = 'USA'\nkenya = pd.read_csv('/Users/Gadcet/Documents/Ani extraction/kenya_data.csv')\nkenya['country'] = 'Kenya'\nnigeria = pd.read_csv('/Users/Gadcet/Documents/Ani extraction/nigeria_data.csv')\nnigeria['country'] = 'Nigeria'\nuk = pd.read_csv('/Users/Gadcet/Documents/Ani extraction/uk_data.csv')\nuk['country'] = 'UK'\n\ndummy_df = pd.concat([usa,kenya,nigeria,uk])\ndummy_df = dummy_df[['author','category', 'country', 'post_body', 'published_date', 'title']]\nprint(len(dummy_df))\n\ndummy_df.columns = ['Author', 'Category', 'Country', 'Text', 'Date', 'Title']\n\n# Assign views, comments etc to each article and then calculate overall points based on the performance of each article\n\nimport random\nfor x in range(10):\n print(random.randint(100,10000))\n \n# Views\nviews_list = []\ncomments_list = []\nshares_list = []\nlikes_list = []\nfor x in range(len(dummy_df)):\n views_list.append(random.randint(10000,1000000))\n comments_list.append(random.randint(100,10000))\n shares_list.append(random.randint(100,10000))\n likes_list.append(random.randint(100,2500))\n\ndummy_df['Views'] = views_list\ndummy_df['Comments'] = comments_list\ndummy_df['Shares'] = shares_list\ndummy_df['Likes'] = likes_list\n\nprint(dummy_df.sample(10))\n\npoints_list = []\nfor i in range(len(dummy_df)):\n temp = ((dummy_df.iloc[i]['Views']*1) + (dummy_df.iloc[i]['Comments']*50) + (dummy_df.iloc[i]['Shares']*50) + (dummy_df.iloc[i]['Likes']*100))\n points_list.append(temp)\ndummy_df['Points'] = points_list\n\n# Filter out the articles that don't have a proper title\nprint(len(dummy_df))\n\ndummy_df = dummy_df.dropna(how='any',axis=0) \nprint(dummy_df.sample(10))\n\n# Create a final output of training data for the models\n\ndummy_df.to_csv('/Users/Gadcet/Documents/Ani extraction/recommender_dummy_data.csv')\n\ndummy_df['Country'].value_counts()\n","sub_path":"All FIles/prepare_dummy_data.py","file_name":"prepare_dummy_data.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"78594789","text":"# coding=utf8\r\n\r\nimport random, requests, hashlib, time\r\nfrom urllib import parse\r\n\r\ndef md5(s):\r\n m = hashlib.md5()\r\n m.update(s.encode(encoding='UTF-8'))\r\n return m.hexdigest()\r\n\r\n\r\ndef fanyi(keyword):\r\n appid = '20190813000326267' # 你的appid\r\n secretKey = '4O9PzAHHLXHuiJM1HFXB' # 你的密钥\r\n\r\n myurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'\r\n q = parse.quote(keyword)\r\n fromLang = 'en'\r\n toLang = 'zh'\r\n salt = random.randint(32768, 65536)\r\n sign = appid + keyword + str(salt) + secretKey\r\n sign = md5(sign)\r\n myurl = myurl + '?appid=' + appid + '&q=' + q + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(\r\n salt) + '&sign=' + sign\r\n\r\n trans_result = ''\r\n try:\r\n result = requests.get(myurl, timeout=10)\r\n if result.status_code == 200:\r\n data = result.json()\r\n print(data)\r\n trans_result = data['trans_result'][0]['dst']\r\n except Exception as e:\r\n print(e)\r\n time.sleep(1)\r\n return trans_result\r\n\r\n\r\nif __name__ == '__main__':\r\n fanyi('苹果')\r\n","sub_path":"amazon/app/fanyi.py","file_name":"fanyi.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"192104237","text":"'''\r\nProgrammer: Alex Urban\r\n06.08.2016\r\nCompiler: Canopy 1.7.2\r\naurban1_3_8\r\n'''\r\n\r\nfrom __future__ import print_function\r\nimport random\r\n\r\ndef days():\r\n ''' This will give me the day of the week!'''\r\n for day in 'MTWRFSS':\r\n print(day + 'day')\r\n for day in range(5,8):\r\n print('It is the ' + str(day) + 'th of September')\r\n \r\n \r\nimport matplotlib.pyplot as plt\r\nplt.ion()\r\n\r\ndef picks():\r\n a = [] #empty list\r\n \r\n a += [random.choice([1,3,10])]\r\n \r\n for choices in range(5):\r\n a += [random.choice([1,3,10])]\r\n \r\n plt.hist(a)\r\n plt.show()\r\n \r\ndef rollHundredPair():\r\n \r\n rollList = []\r\n \r\n for rolls in range(99):\r\n rollList += [random.choice([1,2,3,4,5,6])]\r\n #print(rollList)\r\n \r\n plt.hist(rollList)\r\n plt.show\r\n \r\ndef dice(n):\r\n \r\n sumList = []\r\n diceSum = 0\r\n for items in range(n):\r\n sumList += [random.choice([1,2,3,4,5,6])]\r\n print(sumList)\r\n diceSum = sum(sumList)\r\n print(diceSum)\r\n \r\ndef hangmanDisplay(guessed, secret):\r\n secretHang = ''\r\n for char in secret:\r\n if char in guessed:\r\n secretHang = secretHang + char\r\n else:\r\n secretHang = secretHang + '_'\r\n print(secretHang)\r\n\r\n\r\ndef matches(ticket, winners):\r\n count = 0\r\n for number in winners:\r\n if number in ticket:\r\n count += 1\r\n print(count)\r\n \r\n \r\ndef report(guess, secret):\r\n rightColor = 0\r\n wrongPlace = 0\r\n for color in secret:\r\n if color in guess:\r\n rightColor += 1\r\n for place in secret:\r\n if guess[place] not in secret[place]:\r\n wrongPlace += 1\r\n print(rightColor)\r\n print(wrongPlace)\r\n ","sub_path":"aurban1_3_8.py","file_name":"aurban1_3_8.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"3961745","text":"import argparse\nimport multiprocessing as mp\nimport os\nimport pickle\nimport sys\n\nimport numpy as np\nfrom ase.io import Trajectory, read\nfrom tqdm import tqdm\n\n\ndef check_relaxed_forces(sid, path, thres):\n \"\"\"\n Check all forces in the final frame of adslab is less than a threshold.\n \"\"\"\n final_atoms = read(path)\n forces = final_atoms.get_forces()\n if not (np.max(np.abs(forces)) <= thres):\n print(f\"{sid} doesn't satisfy the force threshold, check trajectory {path}\")\n\n\ndef check_adsorption_energy(sid, path, ref_energy, adsorption_energy):\n final_energy = read(path)\n if (\n not abs((final_energy.get_potential_energy() - ref_energy) - adsorption_energy)\n < 1e-6\n ):\n print(f\"{sid} doesn't satify energy equation\")\n\n\ndef check_DFT_energy(sid, path, e_tol=0.05):\n \"\"\"\n Given a relaxation trajectory, check to see if 1. final energy is less than the initial\n energy, raise error if not. 2) If the energy decreases throuhghout a trajectory (small spikes are okay).\n And 3) if 2 fails, check if it's just a matter of tolerance being too strict by\n considering only the first quarter of the trajectory and sampling every 10th frame\n to check for _almost_ monotonic decrease in energies.\n If any frame(i+1) energy is higher than frame(i) energy, flag it and plot the trajectory.\n \"\"\"\n traj = Trajectory(path)\n if traj[-1].get_potential_energy() > traj[0].get_potential_energy():\n print(\n \"{} has final DFT energy that's higher than the initial energy, check traj {}\".format(\n sid, path\n )\n )\n energies = [traj[i].get_potential_energy() for i in range(len(traj))]\n is_monotonic = all(\n energies[i + 1] - energies[i] < e_tol for i in range(len(energies) - 1)\n )\n if is_monotonic is False:\n print(\n \"There is a spike in energy during the relaxation of {}, double check its trajectory {}\".format(\n sid, path\n )\n )\n is_almost_monotonic = all(\n energies[i] >= energies[i + 10]\n for i in range(0, int(0.25 * len(energies)) - 10, 10)\n )\n if is_almost_monotonic is False:\n print(\n \"almost_monotonic energy check fails, double check trajectory {}\".format(\n path\n )\n )\n\n\ndef check_positions_across_frames_are_different(sid, path):\n \"\"\"\n Given a relaxation trajectory, make sure positions for two consecutive\n frames are not identical.\n \"\"\"\n traj = Trajectory(path)\n positions = [traj[i].get_positions() for i in range(len(traj))]\n is_different = all(\n (positions[i] != positions[i + 1]).any() for i in range(len(positions) - 1)\n )\n if is_different is False:\n print(f\"{sid} has identical positions for some frames, check {path}\")\n\n\ndef read_pkl(fname):\n return pickle.load(open(fname, \"rb\"))\n\n\ndef run_checks(args):\n sysid_list, force_thres, traj_path_by_sysid, ref_energies, ads_energies = args\n for sysid in sysid_list:\n check_relaxed_forces(sysid, traj_path_by_sysid[sysid], force_thres)\n check_adsorption_energy(\n sysid, traj_path_by_sysid[sysid], ref_energies[sysid], ads_energies[sysid]\n )\n check_DFT_energy(sysid, traj_path_by_sysid[sysid])\n check_positions_across_frames_are_different(sysid, traj_path_by_sysid[sysid])\n\n\ndef create_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--sysid_file\",\n type=str,\n help=\"A txt file constains all the system ids (str) of the dataset\",\n )\n parser.add_argument(\n \"--traj_path_by_sysid\",\n type=str,\n help=\"A pickle file that contains a dictionary that maps trajectory path to system ids\",\n )\n parser.add_argument(\n \"--adsorption_energies\",\n type=str,\n help=\"A pickle file that contains a dictionary that maps adsorption energy to system ids\",\n )\n parser.add_argument(\n \"--ref_energies\",\n type=str,\n help=\"A pickle file that contains a dictionary that maps reference energy (E_slab + E_gas) to system ids\",\n )\n parser.add_argument(\n \"--force_tol\",\n type=float,\n default=0.03,\n help=\"Force threshold at which a relaxation is considered converged\",\n )\n parser.add_argument(\n \"--e_tol\",\n type=float,\n default=0.05,\n help=\"Energy threshold to flag a trajectory if potential energy of step i+1 is higher than step i by this amount\",\n )\n parser.add_argument(\n \"--num_workers\", type=int, help=\"Number of processes or no. of dataset chunk\"\n )\n return parser\n\n\nif __name__ == \"__main__\":\n parser = create_parser()\n args = parser.parse_args()\n sysids = open(args.sysid_file).read().splitlines()\n traj_path_by_sysid = read_pkl(args.traj_path_by_sysid)\n adsorption_energy_by_sysid = read_pkl(args.adsorption_energies)\n ref_energy_by_sysid = read_pkl(args.ref_energies)\n force_thres = args.force_tol\n mp_splits = np.array_split(sysids, args.num_workers)\n pool_args = [\n (\n split,\n force_thres,\n traj_path_by_sysid,\n ref_energy_by_sysid,\n adsorption_energy_by_sysid,\n )\n for split in mp_splits\n ]\n pool = mp.Pool(args.num_workers)\n tqdm(pool.imap(run_checks, pool_args), total=len(pool_args))\n","sub_path":"tests/old_tests/check_energy_and_forces.py","file_name":"check_energy_and_forces.py","file_ext":"py","file_size_in_byte":5452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"628031920","text":"\"\"\"\n Fichier : gestion_types_crud.py\n Auteur : OM 2021.03.16\n Gestions des \"routes\" FLASK et des données pour les types.\n\"\"\"\nimport re\nimport sys\n\nfrom flask import flash, session\nfrom flask import render_template\nfrom flask import request\nfrom flask import url_for\nfrom flask import redirect\nfrom flask_wtf import form\n\nfrom APP_FILMS import obj_mon_application\nfrom APP_FILMS.database.connect_db_context_manager import MaBaseDeDonnee\nfrom APP_FILMS.erreurs.msg_erreurs import *\nfrom APP_FILMS.erreurs.exceptions import *\nfrom APP_FILMS.essais_wtf_forms.wtf_forms_1 import MonPremierWTForm\n\n\n\n\"\"\"\n Auteur : OM 2021.03.16\n Définition d'une \"route\" /boisson_afficher\n\n Test : ex : http://127.0.0.1:5005/boisson_afficher\n\n Paramètres : order_by : ASC : Ascendant, DESC : Descendant\n Id_boisson_sel = 0 >> tous les types.\n Id_boisson_sel = \"n\" affiche le genre dont l'id est \"n\"\n\"\"\"\n\n\n@obj_mon_application.route(\"/type_boisson_afficher//\", methods=['GET', 'POST'])\ndef type_boisson_afficher(order_by, Id_boisson_sel):\n if request.method == \"GET\":\n try:\n try:\n # Renvoie une erreur si la connexion est perdue.\n MaBaseDeDonnee().connexion_bd.ping(False)\n except Exception as erreur:\n flash(f\"Dans Gestion types ...terrible erreur, il faut connecter une base de donnée\", \"danger\")\n print(f\"Exception grave Classe constructeur Gestiontypes {erreur.args[0]}\")\n raise MaBdErreurConnexion(f\"{msg_erreurs['ErreurConnexionBD']['message']} {erreur.args[0]}\")\n\n with MaBaseDeDonnee().connexion_bd.cursor() as mc_afficher:\n if order_by == \"ASC\" and Id_boisson_sel == 0:\n strsql_boisson_afficher = \"\"\"SELECT Id_boisson, Marque, Prix_boisson, Quantite_boisson, Date_achat_boisson, Date_peremption_boisson,\n GROUP_CONCAT(type) as Boissontype FROM t_type_boisson\n RIGHT JOIN t_boisson ON t_boisson.Id_boisson = t_type_boisson.fk_boisson\n LEFT JOIN t_type ON t_type.id_type = t_type_boisson.fk_type\n GROUP BY Id_boisson\"\"\"\n mc_afficher.execute(strsql_boisson_afficher)\n elif order_by == \"ASC\":\n # C'EST LA QUE VOUS ALLEZ DEVOIR PLACER VOTRE PROPRE LOGIQUE MySql\n # la commande MySql classique est \"SELECT * FROM t_personne\"\n # Pour \"lever\"(raise) une erreur s'il y a des erreurs sur les noms d'attributs dans la table\n # donc, je précise les champs à afficher\n # Constitution d'un dictionnaire pour associer l'id du genre sélectionné avec un nom de variable\n valeur_Id_boisson_selected_dictionnaire = {\"value_Id_boisson_selected\": Id_boisson_sel}\n strsql_boisson_afficher = \"\"\"SELECTId_boisson, Prix_boisson, Quantite_boisson,Date_achat_boisson,Date_peremption_boisson,Marque,type FROM t_boisson,t_type WHERE Id_boisson = %(value_Id_boisson_selected)s,id_type = %(value_id_type_selected)s\"\"\"\n\n mc_afficher.execute(strsql_boisson_afficher, valeur_Id_boisson_selected_dictionnaire)\n else:\n strsql_boisson_afficher = \"\"\"SELECT Id_boisson, Prix_boisson, Quantite_boisson,Date_achat_boisson,Date_peremption_boisson,Marque,type FROM t_boisson,t_type ORDER BY Id_boisson,id_type DESC\"\"\"\n\n mc_afficher.execute(strsql_boisson_afficher)\n\n data_type_boisson = mc_afficher.fetchall()\n\n print(\"data_type_boisson \", data_type_boisson, \" Type : \", type(data_type_boisson))\n\n # Différencier les messages si la table est vide.\n if not data_type_boisson and Id_boisson_sel == 0:\n flash(\"\"\"La table \"t_personne\" est vide. !!\"\"\", \"warning\")\n elif not data_type_boisson and Id_boisson_sel > 0:\n # Si l'utilisateur change l'Id_personne dans l'URL et que le genre n'existe pas,\n flash(f\"Le Compte demandé n'existe pas !!\", \"warning\")\n else:\n # Dans tous les autres cas, c'est que la table \"t_personne\" est vide.\n # OM 2020.04.09 La ligne ci-dessous permet de donner un sentiment rassurant aux utilisateurs.\n flash(f\"Comptes affichés !!\", \"success\")\n\n except Exception as erreur:\n print(f\"RGG Erreur générale.\")\n # OM 2020.04.09 On dérive \"Exception\" par le \"@obj_mon_application.errorhandler(404)\" fichier \"run_mon_app.py\"\n # Ainsi on peut avoir un message d'erreur personnalisé.\n flash(f\"RGG Exception {erreur}\")\n raise Exception(f\"RGG Erreur générale. {erreur}\")\n raise MaBdErreurOperation(f\"RGG Exception {msg_erreurs['ErreurNomBD']['message']} {erreur}\")\n\n # Envoie la page \"HTML\" au serveur.\n return render_template(\"genres/type_boisson_afficher.html\", data=data_type_boisson)\n\n\n\"\"\"\n nom: edit_type_boisson_selected\n On obtient un objet \"objet_dumpbd\"\n\n Récupère la liste de tous les genres du film sélectionné par le bouton \"MODIFIER\" de \"films_genres_afficher.html\"\n\n Dans une liste déroulante particulière (tags-selector-tagselect), on voit :\n 1) Tous les genres contenus dans la \"t_genre\".\n 2) Les genres attribués au film selectionné.\n 3) Les genres non-attribués au film sélectionné.\n\n On signale les erreurs importantes\n\n\"\"\"\n\n\n@obj_mon_application.route(\"/edit_type_boisson_selected\", methods=['GET', 'POST'])\ndef edit_type_boisson_selected():\n if request.method == \"GET\":\n try:\n with MaBaseDeDonnee().connexion_bd.cursor() as mc_afficher:\n strsql_genres_afficher = \"\"\"SELECT id_type, type FROM t_type ORDER BY id_type ASC\"\"\"\n mc_afficher.execute(strsql_genres_afficher)\n data_genres_all = mc_afficher.fetchall()\n print(\"dans edit_type_boisson_selected ---> data_genres_all\", data_genres_all)\n\n # Récupère la valeur de \"id_film\" du formulaire html \"films_genres_afficher.html\"\n # l'utilisateur clique sur le bouton \"Modifier\" et on récupère la valeur de \"id_film\"\n # grâce à la variable \"id_film_genres_edit_html\" dans le fichier \"films_genres_afficher.html\"\n # href=\"{{ url_for('edit_type_boisson_selected', id_film_genres_edit_html=row.id_film) }}\"\n id_film_genres_edit = request.values['id_film_genres_edit_html']\n\n # Mémorise l'id du film dans une variable de session\n # (ici la sécurité de l'application n'est pas engagée)\n # il faut éviter de stocker des données sensibles dans des variables de sessions.\n session['session_id_film_genres_edit'] = id_film_genres_edit\n\n # Constitution d'un dictionnaire pour associer l'id du film sélectionné avec un nom de variable\n valeur_id_film_selected_dictionnaire = {\"value_valeur_Id_boisson_selected_dict\": id_film_genres_edit}\n\n # Récupère les données grâce à 3 requêtes MySql définie dans la fonction type_boisson_afficher_data\n # 1) Sélection du film choisi\n # 2) Sélection des genres \"déjà\" attribués pour le film.\n # 3) Sélection des genres \"pas encore\" attribués pour le film choisi.\n # ATTENTION à l'ordre d'assignation des variables retournées par la fonction \"type_boisson_afficher_data\"\n data_genre_film_selected, data_genres_films_non_attribues, data_genres_films_attribues = \\\n type_boisson_afficher_data(valeur_id_film_selected_dictionnaire)\n\n print(data_genre_film_selected)\n lst_data_film_selected = [item['id_boisson'] for item in data_genre_film_selected]\n print(\"lst_data_film_selected \", lst_data_film_selected,\n type(lst_data_film_selected))\n\n # Dans le composant \"tags-selector-tagselect\" on doit connaître\n # les genres qui ne sont pas encore sélectionnés.\n lst_data_genres_films_non_attribues = [item['id_type'] for item in data_genres_films_non_attribues]\n session['session_lst_data_genres_films_non_attribues'] = lst_data_genres_films_non_attribues\n print(\"lst_data_genres_films_non_attribues \", lst_data_genres_films_non_attribues,\n type(lst_data_genres_films_non_attribues))\n\n # Dans le composant \"tags-selector-tagselect\" on doit connaître\n # les genres qui sont déjà sélectionnés.\n lst_data_genres_films_old_attribues = [item['id_type'] for item in data_genres_films_attribues]\n session['session_lst_data_genres_films_old_attribues'] = lst_data_genres_films_old_attribues\n print(\"lst_data_genres_films_old_attribues \", lst_data_genres_films_old_attribues,\n type(lst_data_genres_films_old_attribues))\n\n print(\" data data_genre_film_selected\", data_genre_film_selected, \"type \", type(data_genre_film_selected))\n print(\" data data_genres_films_non_attribues \", data_genres_films_non_attribues, \"type \",\n type(data_genres_films_non_attribues))\n print(\" data_genres_films_attribues \", data_genres_films_attribues, \"type \",\n type(data_genres_films_attribues))\n\n # Extrait les valeurs contenues dans la table \"t_genres\", colonne \"intitule_genre\"\n # Le composant javascript \"tagify\" pour afficher les tags n'a pas besoin de l'id_genre\n lst_data_genres_films_non_attribues = [item['type'] for item in data_genres_films_non_attribues]\n print(\"lst_all_genres gf_edit_genre_film_selected \", lst_data_genres_films_non_attribues,\n type(lst_data_genres_films_non_attribues))\n\n except Exception as Exception_edit_genre_film_selected:\n code, msg = Exception_edit_genre_film_selected.args\n flash(f\"{error_codes.get(code, msg)} \", \"danger\")\n flash(f\"Exception edit_type_boisson_selected : {sys.exc_info()[0]} \"\n f\"{Exception_edit_genre_film_selected.args[0]} , \"\n f\"{Exception_edit_genre_film_selected}\", \"danger\")\n\n return render_template(\"genres/boisson_type_modifier_tags_dropbox.html\",\n data_genres=data_genres_all,\n data_film_selected=data_genre_film_selected,\n data_genres_attribues=data_genres_films_attribues,\n data_genres_non_attribues=data_genres_films_non_attribues)\n\n\n\"\"\"\n nom: update_type_boisson_selected\n\n Récupère la liste de tous les genres du film sélectionné par le bouton \"MODIFIER\" de \"films_genres_afficher.html\"\n\n Dans une liste déroulante particulière (tags-selector-tagselect), on voit :\n 1) Tous les genres contenus dans la \"t_genre\".\n 2) Les genres attribués au film selectionné.\n 3) Les genres non-attribués au film sélectionné.\n\n On signale les erreurs importantes\n\"\"\"\n\n\n@obj_mon_application.route(\"/update_type_boisson_selected\", methods=['GET', 'POST'])\ndef update_type_boisson_selected():\n if request.method == \"POST\":\n try:\n # Récupère l'id du film sélectionné\n Id_boisson_selected = session['session_id_film_genres_edit']\n print(\"session['session_id_film_genres_edit'] \", session['session_id_film_genres_edit'])\n\n # Récupère la liste des genres qui ne sont pas associés au film sélectionné.\n old_lst_data_genres_films_non_attribues = session['session_lst_data_genres_films_non_attribues']\n print(\"old_lst_data_genres_films_non_attribues \", old_lst_data_genres_films_non_attribues)\n\n # Récupère la liste des genres qui sont associés au film sélectionné.\n old_lst_data_genres_films_attribues = session['session_lst_data_genres_films_old_attribues']\n print(\"old_lst_data_genres_films_old_attribues \", old_lst_data_genres_films_attribues)\n\n # Effacer toutes les variables de session.\n session.clear()\n\n # Récupère ce que l'utilisateur veut modifier comme genres dans le composant \"tags-selector-tagselect\"\n # dans le fichier \"genres_films_modifier_tags_dropbox.html\"\n new_lst_str_genres_films = request.form.getlist('name_select_tags')\n print(\"new_lst_str_genres_films \", new_lst_str_genres_films)\n\n # OM 2021.05.02 Exemple : Dans \"name_select_tags\" il y a ['4','65','2']\n # On transforme en une liste de valeurs numériques. [4,65,2]\n new_lst_int_genre_film_old = list(map(int, new_lst_str_genres_films))\n print(\"new_lst_genre_film \", new_lst_int_genre_film_old, \"type new_lst_genre_film \",\n type(new_lst_int_genre_film_old))\n\n # Pour apprécier la facilité de la vie en Python... \"les ensembles en Python\"\n # https://fr.wikibooks.org/wiki/Programmation_Python/Ensembles\n # OM 2021.05.02 Une liste de \"id_genre\" qui doivent être effacés de la table intermédiaire \"t_genre_film\".\n lst_diff_genres_delete_b = list(\n set(old_lst_data_genres_films_attribues) - set(new_lst_int_genre_film_old))\n print(\"lst_diff_genres_delete_b \", lst_diff_genres_delete_b)\n\n # Une liste de \"id_genre\" qui doivent être ajoutés à la \"t_genre_film\"\n lst_diff_genres_insert_a = list(\n set(new_lst_int_genre_film_old) - set(old_lst_data_genres_films_attribues))\n print(\"lst_diff_genres_insert_a \", lst_diff_genres_insert_a)\n\n # SQL pour insérer une nouvelle association entre\n # \"fk_film\"/\"id_film\" et \"fk_genre\"/\"id_genre\" dans la \"t_genre_film\"\n strsql_insert_genre_film = \"\"\"INSERT INTO t_type_boisson (id_type_boisson, fk_type, fk_boisson)\n VALUES (NULL, %(value_fk_type)s, %(value_fk_boisson)s)\"\"\"\n\n # SQL pour effacer une (des) association(s) existantes entre \"id_film\" et \"id_genre\" dans la \"t_genre_film\"\n strsql_delete_genre_film = \"\"\"DELETE FROM t_type_boisson WHERE fk_type = %(value_fk_type)s AND fk_boisson = %(value_fk_boisson)s\"\"\"\n\n with MaBaseDeDonnee() as mconn_bd:\n # Pour le film sélectionné, parcourir la liste des genres à INSÉRER dans la \"t_genre_film\".\n # Si la liste est vide, la boucle n'est pas parcourue.\n for id_type_ins in lst_diff_genres_insert_a:\n # Constitution d'un dictionnaire pour associer l'id du film sélectionné avec un nom de variable\n # et \"id_type_ins\" (l'id du genre dans la liste) associé à une variable.\n valeurs_film_sel_genre_sel_dictionnaire = {\"value_fk_boisson\": Id_boisson_selected,\n \"value_fk_type\": id_type_ins}\n\n mconn_bd.mabd_execute(strsql_insert_genre_film, valeurs_film_sel_genre_sel_dictionnaire)\n\n # Pour le film sélectionné, parcourir la liste des genres à EFFACER dans la \"t_genre_film\".\n # Si la liste est vide, la boucle n'est pas parcourue.\n for id_type_del in lst_diff_genres_delete_b:\n # Constitution d'un dictionnaire pour associer l'id du film sélectionné avec un nom de variable\n # et \"id_type_del\" (l'id du genre dans la liste) associé à une variable.\n valeurs_film_sel_genre_sel_dictionnaire = {\"value_fk_boisson\": Id_boisson_selected,\n \"value_fk_type\": id_type_del}\n\n # Du fait de l'utilisation des \"context managers\" on accède au curseur grâce au \"with\".\n # la subtilité consiste à avoir une méthode \"mabd_execute\" dans la classe \"MaBaseDeDonnee\"\n # ainsi quand elle aura terminé l'insertion des données le destructeur de la classe \"MaBaseDeDonnee\"\n # sera interprété, ainsi on fera automatiquement un commit\n mconn_bd.mabd_execute(strsql_delete_genre_film, valeurs_film_sel_genre_sel_dictionnaire)\n\n except Exception as Exception_update_genre_film_selected:\n code, msg = Exception_update_genre_film_selected.args\n flash(f\"{error_codes.get(code, msg)} \", \"danger\")\n flash(f\"Exception update_type_boisson_selected : {sys.exc_info()[0]} \"\n f\"{Exception_update_genre_film_selected.args[0]} , \"\n f\"{Exception_update_genre_film_selected}\", \"danger\")\n\n # Après cette mise à jour de la table intermédiaire \"t_genre_film\",\n # on affiche les films et le(urs) genre(s) associé(s).\n return redirect(url_for('type_boisson_afficher',order_by=\"ASC\", Id_boisson_sel=0))\n\n\n\"\"\"\n nom: type_boisson_afficher_data\n\n Récupère la liste de tous les genres du film sélectionné par le bouton \"MODIFIER\" de \"films_genres_afficher.html\"\n Nécessaire pour afficher tous les \"TAGS\" des genres, ainsi l'utilisateur voit les genres à disposition\n\n On signale les erreurs importantes\n\"\"\"\n\n\ndef type_boisson_afficher_data(valeur_Id_boisson_selected_dict):\n print(\"valeur_Id_boisson_selected_dict...\", valeur_Id_boisson_selected_dict)\n try:\n\n strsql_film_selected = \"\"\"SELECT id_boisson, Prix_boisson, Quantite_boisson, Date_achat_boisson, Date_peremption_boisson, Marque, GROUP_CONCAT(id_type) as GenresFilms FROM t_type_boisson\n INNER JOIN t_boisson ON t_boisson.id_boisson = t_type_boisson.fk_boisson\n INNER JOIN t_type ON t_type.id_type = t_type_boisson.fk_type\n WHERE id_boisson = %(value_valeur_Id_boisson_selected_dict)s\"\"\"\n\n strsql_genres_films_non_attribues = \"\"\"SELECT id_type, type FROM t_type WHERE id_type not in(SELECT id_type as idGenresFilms FROM t_type_boisson\n INNER JOIN t_boisson ON t_boisson.id_boisson = t_type_boisson.fk_boisson\n INNER JOIN t_type ON t_type.id_type = t_type_boisson.fk_type\n WHERE id_boisson = %(value_valeur_Id_boisson_selected_dict)s)\"\"\"\n\n strsql_genres_films_attribues = \"\"\"SELECT id_boisson, id_type, type FROM t_type_boisson\n INNER JOIN t_boisson ON t_boisson.id_boisson = t_type_boisson.fk_boisson\n INNER JOIN t_type ON t_type.id_type = t_type_boisson.fk_type\n WHERE id_boisson = %(value_valeur_Id_boisson_selected_dict)s\"\"\"\n\n # Du fait de l'utilisation des \"context managers\" on accède au curseur grâce au \"with\".\n with MaBaseDeDonnee().connexion_bd.cursor() as mc_afficher:\n # Envoi de la commande MySql\n mc_afficher.execute(strsql_genres_films_non_attribues, valeur_Id_boisson_selected_dict)\n # Récupère les données de la requête.\n data_genres_films_non_attribues = mc_afficher.fetchall()\n # Affichage dans la console\n print(\"type_boisson_afficher_data ----> data_genres_films_non_attribues \", data_genres_films_non_attribues,\n \" Type : \",\n type(data_genres_films_non_attribues))\n\n # Envoi de la commande MySql\n mc_afficher.execute(strsql_film_selected, valeur_Id_boisson_selected_dict)\n # Récupère les données de la requête.\n data_film_selected = mc_afficher.fetchall()\n # Affichage dans la console\n print(\"data_film_selected \", data_film_selected, \" Type : \", type(data_film_selected))\n\n # Envoi de la commande MySql\n mc_afficher.execute(strsql_genres_films_attribues, valeur_Id_boisson_selected_dict)\n # Récupère les données de la requête.\n data_genres_films_attribues = mc_afficher.fetchall()\n # Affichage dans la console\n print(\"data_genres_films_attribues \", data_genres_films_attribues, \" Type : \",\n type(data_genres_films_attribues))\n\n # Retourne les données des \"SELECT\"\n return data_film_selected, data_genres_films_non_attribues, data_genres_films_attribues\n except pymysql.Error as pymysql_erreur:\n code, msg = pymysql_erreur.args\n flash(f\"{error_codes.get(code, msg)} \", \"danger\")\n flash(f\"pymysql.Error Erreur dans type_boisson_afficher_data : {sys.exc_info()[0]} \"\n f\"{pymysql_erreur.args[0]} , \"\n f\"{pymysql_erreur}\", \"danger\")\n except Exception as exception_erreur:\n code, msg = exception_erreur.args\n flash(f\"{error_codes.get(code, msg)} \", \"danger\")\n flash(f\"Exception Erreur dans type_boisson_afficher_data : {sys.exc_info()[0]} \"\n f\"{exception_erreur.args[0]} , \"\n f\"{exception_erreur}\", \"danger\")\n except pymysql.err.IntegrityError as IntegrityError_type_boisson_afficher_data:\n code, msg = IntegrityError_type_boisson_afficher_data.args\n flash(f\"{error_codes.get(code, msg)} \", \"danger\")\n flash(f\"pymysql.err.IntegrityError Erreur dans type_boisson_afficher_data : {sys.exc_info()[0]} \"\n f\"{IntegrityError_type_boisson_afficher_data.args[0]} , \"\n f\"{IntegrityError_type_boisson_afficher_data}\", \"danger\")\n\n\n\n\n\n\n\n","sub_path":"APP_FILMS/genres/gestion_type_boisson_crud.py","file_name":"gestion_type_boisson_crud.py","file_ext":"py","file_size_in_byte":22081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"651084735","text":"from FullStackWeb.movie_trailer import media , fresh_tomatoes\r\n\r\n\"\"\"\r\nToy Story Movie Details\r\n\"\"\"\r\nts_title=\"Toy Story\"\r\nts_storyline=\"A cowboy doll is profoundly threatened \" \\\r\n \"and jealous when a new spaceman figure supplants him as top toy in a boy's room.\"\r\nts_poster_image_url=\"https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg\"\r\nts_trailer_youtube_url=\"https://youtu.be/KYz2wyBy3kc?t=5s\"\r\n\r\ntoy_story = media.Movie(ts_title,ts_storyline,ts_poster_image_url,ts_trailer_youtube_url)\r\n\r\n\"\"\"\r\nAvatar Movie\r\n\"\"\"\r\n\r\na_title=\"Avatar\"\r\na_storyline=\"A paraplegic marine dispatched to the moon Pandora on a \" \\\r\n \"unique mission becomes torn between following his orders \" \\\r\n \"and protecting the world he feels is his home\"\r\na_poster_image_url = \"https://upload.wikimedia.org/wikipedia/en/b/b0/Avatar-Teaser-Poster.jpg\"\r\na_trailer_youtube_url=\"https://youtu.be/d1_JBMrrYw8?t=4s\"\r\n\r\navatar = media.Movie(a_title,a_storyline,a_poster_image_url,a_trailer_youtube_url)\r\n\r\n\"\"\"\r\nThe Boss Baby\r\n\"\"\"\r\n\r\nb_title=\"The Boss Baby\"\r\nb_storyline=\"A suit-wearing, briefcase-carrying baby pairs up with his 7-year old\" \\\r\n \" brother to stop the dastardly plot of the CEO of Puppy Co.\"\r\nb_poster_image_url=\"https://upload.wikimedia.org/wikipedia/en/0/0e/The_Boss_Baby_poster.jpg\"\r\nb_trailer_youtube_url=\"https://youtu.be/k397HRbTtWI?t=1s\"\r\n\r\nbossBaby = media.Movie(b_title,b_storyline,b_poster_image_url,b_trailer_youtube_url)\r\n\r\n\r\n\"\"\"\r\nMother!\r\n\"\"\"\r\n\r\nm_title=\"Mother !\"\r\nm_storyline=\"A couple's relationship is tested when uninvited guests arrive at their home, disrupting their tranquil existence.\"\r\nm_poster_image_url=\"https://upload.wikimedia.org/wikipedia/en/9/94/Mother%212017.jpg\"\r\nm_trailer_youtube_url=\"https://youtu.be/XpICoc65uh0?t=7s\"\r\n\r\nmother = media.Movie(m_title,m_storyline,m_poster_image_url,m_trailer_youtube_url)\r\n\r\n\r\n\"\"\"\r\nM.S. Dhoni: The Untold Story\r\n\r\n\"\"\"\r\n\r\ndhoni_title=\"M.S. Dhoni: The Untold Story\"\r\ndhoni_storyline=\"The untold story of Mahendra Singh Dhoni's journey from ticket \" \\\r\n \"collector to trophy collector - the world-cup-winning captain of the Indian Cricket Team.\"\r\ndhoni_poster_image_url=\"https://upload.wikimedia.org/wikipedia/en/3/33/M.S._Dhoni_-_The_Untold_Story_poster.jpg\"\r\ndhoni_trailer_youtube_url=\"https://youtu.be/6L6XqWoS8tw\"\r\n\r\ndhoni = media.Movie(dhoni_title,dhoni_storyline,dhoni_poster_image_url,dhoni_trailer_youtube_url)\r\n\r\n\r\n\"\"\"\r\nDangal\r\n\"\"\"\r\n\r\nDangal_title=\"Dangal\"\r\nDangal_storyline=\"Former wrestler Mahavir Singh Phogat \" \\\r\n \"and his two wrestler daughters struggle towards glory at \" \\\r\n \"the Commonwealth Games in the face of societal oppression.\"\r\nDangal_poster_image_url=\"https://upload.wikimedia.org/wikipedia/en/9/99/Dangal_Poster.jpg\"\r\nDangal_trailer_youtube_url=\"https://youtu.be/x_7YlGv9u1g\"\r\n\r\nDangal = media.Movie(Dangal_title,Dangal_storyline,Dangal_poster_image_url,Dangal_trailer_youtube_url)\r\n\r\n#Creating List of Movies.\r\nmovies=[toy_story,avatar,bossBaby,mother,dhoni,Dangal]\r\n\r\n#Launch the WebSite\r\nfresh_tomatoes.open_movies_page(movies)","sub_path":"movie_trailer/entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":3103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"626579427","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 10 13:04:10 2017\r\n\r\nAuthor: Tim Caffrey Chan.\r\n\"\"\"\r\n\r\nimport os\r\nimport cv2\r\nimport dlib\r\n\r\n\r\ndef VideoOpen(_filename, _pathname):\r\n \"\"\"\r\n Open a video file and return a videocapture object.\r\n \r\n :Param:\r\n :_filename: The video file name. (i.e. \"Twitter_01\").\r\n \r\n :_pathname: The file directory that contains the video file. (i.e. \".\\Face Recognition\\Facebook Video\").\r\n \r\n :Return: A video object and a boolean type variable indicates whether the video file is open.\r\n \"\"\"\r\n _file_path = _pathname + \"\\\\\"\r\n _file = _file_path + _filename + \".mp4\"\r\n _video = cv2.VideoCapture(_file)\r\n if _video.isOpened():\r\n return (_video, True)\r\n else:\r\n return (None, False)\r\n\r\ndef Video_2_Image(_video, _timestep, _flag, _filename):\r\n \"\"\"\r\n Transform a video frame to image and then save the image into the file directory \"Video_Trans\".\r\n \r\n :Param:\r\n :_video: A video object.\r\n \r\n :_timestep: The time interval for extracting frames.\r\n \r\n :_flag: A boolean variable indicates whether the video object is available. \r\n \"\"\"\r\n _image_id = 0\r\n _file_path = \".\\Face Recognition\\\\Video_Trans\\\\\" + _filename\r\n # Check the directory\r\n if os.path.exists(_file_path):\r\n pass\r\n else:\r\n os.makedirs(_file_path)\r\n # Save image\r\n while _flag:\r\n _flag, _frame = _video.read()\r\n if (_video.get(cv2.CAP_PROP_POS_FRAMES) - 1) % _timestep == 0:\r\n cv2.imwrite(_file_path + \"\\\\\" + \\\r\n str(_image_id) + \".jpg\", _frame)\r\n _image_id += 1\r\n _video.release()\r\n\r\n\r\ndef List_File(_parrent_path, _filetype=\"mp4\"):\r\n \"\"\"\r\n List all the video file (image file) included in the file directory \"_parrent_path\"\r\n \r\n :Param:\r\n :_parrent_path: The file directory. (i.e. \".\\Face Recognition\\\\\")\r\n \r\n :_filetype: The file type, \"jpg\" or \"mp4\"\r\n \"\"\"\r\n _path = []\r\n _file = []\r\n _children_path = os.listdir(_parrent_path)\r\n for _path_temp in _children_path:\r\n if os.path.isdir(_parrent_path + _path_temp):\r\n _files_list = os.listdir(_parrent_path + _path_temp)\r\n for _file_list in _files_list:\r\n if _file_list[-3:] == _filetype:\r\n _path.append(_parrent_path + _path_temp)\r\n _file.append(_file_list[:-4])\r\n return (_path, _file)\r\n\r\ndef Video_Process():\r\n \"\"\"\r\n Main function of the video to image proccess.\r\n \"\"\"\r\n path_name, file_name = List_File(\".\\Face Recognition\\\\\")\r\n for i in range(len(file_name)):\r\n video, flag = VideoOpen(file_name[i], path_name[i])\r\n if flag:\r\n Video_2_Image(video, 150, flag, file_name[i])\r\n else:\r\n print(\"Error Arise\" + str(i))\r\n\r\ndef Boundary_Check(_imgshape=None, _icon=None):\r\n \"\"\"\r\n Make sure the icon boundaries are within the image. And return the extended boundaries. \r\n \r\n :Param:\r\n :_imgshape: The shape of original image.\r\n \r\n :_icon: A rectangle object produces by the face detector.\r\n \r\n :Return: A trimmed tuple representation of the extended boundaries in (left, right, top, bottom) order.\r\n \"\"\"\r\n if _imgshape is None or _icon is None:\r\n return [0, 0, 0, 0]\r\n else:\r\n _iconpos = []\r\n _iconshape = [max(0, _icon.left()), min(_imgshape[1], _icon.right()), \\\r\n max(0, _icon.top()), min(_imgshape[0], _icon.bottom())]\r\n _iconwidth = _iconshape[1] - _iconshape[0]\r\n _iconheight = _iconshape[3] - _iconshape[2]\r\n _iconpos.append(max(0, _iconshape[0] - round(0.6 * _iconwidth)))\r\n _iconpos.append(min(_imgshape[1], _iconshape[1] + round(0.6 * _iconwidth)))\r\n _iconpos.append(max(0, _iconshape[2] - round(0.6 * _iconheight)))\r\n _iconpos.append(min(_imgshape[0], _iconshape[3] + round(0.6 * _iconheight)))\r\n return _iconpos\r\n\r\ndef Image_Cut(_pathname, _filename, counter=0):\r\n \"\"\"\r\n Read the image and check if there are faces, and then cut out faces from the original image \r\n and save them as new jpg file.\r\n \r\n :Param:\r\n \r\n :_pathname: The directory where the image file is located.\r\n \r\n :_filename: The original image file name which you want to run the face detection.\r\n \r\n :counter: A counter that is used to note down the number of icons have been detected.\r\n \r\n :Return: The number of icons have been detected.\r\n \r\n \"\"\"\r\n image_name = _pathname + \"\\\\\" + _filename + \".jpg\"\r\n img = cv2.imread(image_name)\r\n img_temp = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n detector = dlib.get_frontal_face_detector()\r\n faces = detector(img_temp, 1)\r\n if len(faces) > 0:\r\n for i in range(len(faces)):\r\n iconpos = Boundary_Check(img.shape, faces[i])\r\n icon = img[iconpos[2]: iconpos[3], iconpos[0]: iconpos[1], :]\r\n cv2.imwrite(\".\\Face Recognition\\\\Icon_Detection\\\\\" + _pathname[41:] + \"_\" + \\\r\n _filename + \"_\" + str(counter) + \".jpg\", \\\r\n icon)\r\n counter += 1\r\n else:\r\n with open(\".\\Face Recognition\\log.txt\", \"a\") as logfile:\r\n logfile.write(image_name)\r\n logfile.write(\"\\n\")\r\n cv2.imwrite(\".\\Face Recognition\\\\Icon_Undetected\\\\\" + _pathname[41:] + \"_\" + \\\r\n _filename + \".jpg\", img)\r\n return counter\r\n \r\ndef Icon_Detection(_parentpath, _filetype=\"jpg\"):\r\n \"\"\"\r\n Main fnction of face detection.\r\n \"\"\"\r\n path_name, file_name = List_File(_parentpath, _filetype)\r\n counter = 0\r\n for k in range(len(file_name)):\r\n counter = Image_Cut(path_name[k], file_name[k], counter)\r\n","sub_path":"Data_Pretreat.py","file_name":"Data_Pretreat.py","file_ext":"py","file_size_in_byte":5756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"3"}
+{"seq_id":"23200620","text":"import random\n\nfrom django.db.models import Count, F\nfrom django.http import HttpResponse\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n\nfrom api import constants, utilities_notion\nfrom api.models import (\n Question,\n Category,\n Tag,\n Quiz,\n QuestionStat,\n QuizStat,\n Contribution,\n)\nfrom api.serializers import (\n QuestionSerializer,\n CategorySerializer,\n TagSerializer,\n QuizSerializer,\n QuizFullSerializer,\n QuestionStatSerializer,\n QuizStatSerializer,\n ContributionSerializer,\n)\n\n\ndef api_home(request):\n return HttpResponse(\n \"\"\"\n